Programs & Examples On #Svk

svk is a decentralized version control system which makes use of the two underlying layers of Subversion.

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Inline Form nested within Horizontal Form in Bootstrap 3

I have created a demo for you.

Here is how your nested structure should be in Bootstrap 3:

<div class="form-group">
    <label for="birthday" class="col-xs-2 control-label">Birthday</label>
    <div class="col-xs-10">
        <div class="form-inline">
            <div class="form-group">
                <input type="text" class="form-control" placeholder="year"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="month"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="day"/>
            </div>
        </div>
    </div>
</div>

Notice how the whole form-inline is nested within the col-xs-10 div containing the control of the horizontal form. In other terms, the whole form-inline is the "control" of the birthday label in the main horizontal form.

Note that you will encounter a left and right margin problem by nesting the inline form within the horizontal form. To fix this, add this to your css:

.form-inline .form-group{
    margin-left: 0;
    margin-right: 0;
}

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

How to keep the header static, always on top while scrolling?

After looking through all the answers, I found a slightly different way with minimum CSS and no JS, only the height of the header needs to be set correctly in #content, in this case 60px

CSS:

#header {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 10;
}
#content {
  margin-top: 60px;
  z-index:1;
}

HTML:

<body>
  <div id="header" style="background-color:GRAY; text-align:center; border-bottom:1px SOLID BLACK; color:WHITE; line-height:50px; font-size:40px">
     My Large Static Header
  </div>
  <div id="content">
     <!-- All page content here -->
  </div>
</body>

how to update the multiple rows at a time using linq to sql?

This is what I did:

EF:

using (var context = new SomeDBContext())
{
    foreach (var item in model.ShopItems)  // ShopItems is a posted list with values 
    {    
        var feature = context.Shop
                             .Where(h => h.ShopID == 123 && h.Type == item.Type).ToList();

        feature.ForEach(a => a.SortOrder = item.SortOrder);
    }

    context.SaveChanges();
}

Hope helps someone.

How to concatenate string and int in C?

Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

Creating a generic method in C#

I like to start with a class like this class settings { public int X {get;set;} public string Y { get; set; } // repeat as necessary

 public settings()
 {
    this.X = defaultForX;
    this.Y = defaultForY;
    // repeat ...
 }
 public void Parse(Uri uri)
 {
    // parse values from query string.
    // if you need to distinguish from default vs. specified, add an appropriate property

 }

This has worked well on 100's of projects. You can use one of the many other parsing solutions to parse values.

Validating file types by regular expression

You can embed case insensitity into the regular expression like so:

\.(?i:)(?:jpg|gif|doc|pdf)$

Any reason to prefer getClass() over instanceof when generating .equals()?

This is something of a religious debate. Both approaches have their problems.

  • Use instanceof and you can never add significant members to subclasses.
  • Use getClass and you violate the Liskov substitution principle.

Bloch has another relevant piece of advice in Effective Java Second Edition:

  • Item 17: Design and document for inheritance or prohibit it

Manually map column names with class properties

Here is a simple solution that doesn't require attributes allowing you to keep infrastructure code out of your POCOs.

This is a class to deal with the mappings. A dictionary would work if you mapped all the columns, but this class allows you to specify just the differences. In addition, it includes reverse maps so you can get the field from the column and the column from the field, which can be useful when doing things such as generating sql statements.

public class ColumnMap
{
    private readonly Dictionary<string, string> forward = new Dictionary<string, string>();
    private readonly Dictionary<string, string> reverse = new Dictionary<string, string>();

    public void Add(string t1, string t2)
    {
        forward.Add(t1, t2);
        reverse.Add(t2, t1);
    }

    public string this[string index]
    {
        get
        {
            // Check for a custom column map.
            if (forward.ContainsKey(index))
                return forward[index];
            if (reverse.ContainsKey(index))
                return reverse[index];

            // If no custom mapping exists, return the value passed in.
            return index;
        }
    }
}

Setup the ColumnMap object and tell Dapper to use the mapping.

var columnMap = new ColumnMap();
columnMap.Add("Field1", "Column1");
columnMap.Add("Field2", "Column2");
columnMap.Add("Field3", "Column3");

SqlMapper.SetTypeMap(typeof (MyClass), new CustomPropertyTypeMap(typeof (MyClass), (type, columnName) => type.GetProperty(columnMap[columnName])));

How to use Collections.sort() in Java?

Use this method Collections.sort(List,Comparator) . Implement a Comparator and pass it to Collections.sort().

class RecipeCompare implements Comparator<Recipe> {

    @Override
    public int compare(Recipe o1, Recipe o2) {
        // write comparison logic here like below , it's just a sample
        return o1.getID().compareTo(o2.getID());
    }
}

Then use the Comparator as

Collections.sort(recipes,new RecipeCompare());

Is there a way to collapse all code blocks in Eclipse?

I noticed few things:

Ctrl+/ toggles Folding-enabled or -disabled.

It is Ctrl+* that expands. Ctrl+Shift+* collapses just like Ctrl+Shift+/

anchor jumping by using javascript

You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.

Here is a lazier way to do that:

function jump(h){
    var url = location.href;               //Save down the URL without hash.
    location.href = "#"+h;                 //Go to the target element.
    history.replaceState(null,null,url);   //Don't like hashes. Changing it back.
}

This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:

function jump(h){
    var top = document.getElementById(h).offsetTop; //Getting Y of target element
    window.scrollTo(0, top);                        //Go there directly or some transition
}?

Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/

You can also use .scrollIntoView:

document.getElementById(h).scrollIntoView();   //Even IE6 supports this

(Well I lied. It's not complicated at all.)

How do you embed binary data in XML?

Base64 overhead is 33%.

BaseXML for XML1.0 overhead is only 20%. But it's not a standard and only have a C implementation yet. Check it out if you're concerned with data size. Note that however browsers tends to implement compression so that it is less needed.

I developed it after the discussion in this thread: Encoding binary data within XML : alternatives to base64.

How to determine if binary tree is balanced?

#include <iostream>
#include <deque>
#include <queue>

struct node
{
    int data;
    node *left;
    node *right;
};

bool isBalanced(node *root)
{
    if ( !root)
    {
        return true;
    }

    std::queue<node *> q1;
    std::queue<int>  q2;
    int level = 0, last_level = -1, node_count = 0;

    q1.push(root);
    q2.push(level);

    while ( !q1.empty() )
    {
        node *current = q1.front();
        level = q2.front();

        q1.pop();
        q2.pop();

        if ( level )
        {
            ++node_count;
        }

                if ( current->left )
                {
                        q1.push(current->left);
                        q2.push(level + 1);
                }

                if ( current->right )
                {
                        q1.push(current->right);
                        q2.push(level + 1);
                }

        if ( level != last_level )
        {
            std::cout << "Check: " << (node_count ? node_count - 1 : 1) << ", Level: " << level << ", Old level: " << last_level << std::endl;
            if ( level && (node_count - 1) != (1 << (level-1)) )
            {
                return false;
            }

            last_level = q2.front();
            if ( level ) node_count = 1;
        }
    }

    return true;
}

int main()
{
    node tree[15];

    tree[0].left  = &tree[1];
    tree[0].right = &tree[2];
    tree[1].left  = &tree[3];
    tree[1].right = &tree[4];
    tree[2].left  = &tree[5];
    tree[2].right = &tree[6];
    tree[3].left  = &tree[7];
    tree[3].right = &tree[8];
    tree[4].left  = &tree[9];   // NULL;
    tree[4].right = &tree[10];  // NULL;
    tree[5].left  = &tree[11];  // NULL;
    tree[5].right = &tree[12];  // NULL;
    tree[6].left  = &tree[13];
    tree[6].right = &tree[14];
    tree[7].left  = &tree[11];
    tree[7].right = &tree[12];
    tree[8].left  = NULL;
    tree[8].right = &tree[10];
    tree[9].left  = NULL;
    tree[9].right = &tree[10];
    tree[10].left = NULL;
    tree[10].right= NULL;
    tree[11].left = NULL;
    tree[11].right= NULL;
    tree[12].left = NULL;
    tree[12].right= NULL;
    tree[13].left = NULL;
    tree[13].right= NULL;
    tree[14].left = NULL;
    tree[14].right= NULL;

    std::cout << "Result: " << isBalanced(tree) << std::endl;

    return 0;
}

Finding a substring within a list in Python

All the answers work but they always traverse the whole list. If I understand your question, you only need the first match. So you don't have to consider the rest of the list if you found your first match:

mylist = ['abc123', 'def456', 'ghi789']
sub = 'abc'
next((s for s in mylist if sub in s), None) # returns 'abc123'

If the match is at the end of the list or for very small lists, it doesn't make a difference, but consider this example:

import timeit

mylist = ['abc123'] + ['xyz123']*1000
sub = 'abc'

timeit.timeit('[s for s in mylist if sub in s]', setup='from __main__ import mylist, sub', number=100000)
# for me 7.949463844299316 with Python 2.7, 8.568840944994008 with Python 3.4
timeit.timeit('next((s for s in mylist if sub in s), None)', setup='from __main__ import mylist, sub', number=100000) 
# for me 0.12696599960327148 with Python 2.7, 0.09955992100003641 with Python 3.4

Listening for variable changes in JavaScript

This is an old thread but I stumbled onto second highest answer (custom listeners) while looking for a solution using Angular. While the solution works, angular has a better built in way to resolve this using @Output and event emitters. Going off of the example in custom listener answer:

ChildComponent.html

<button (click)="increment(1)">Increment</button>

ChildComponent.ts

import {EventEmitter, Output } from '@angular/core';

@Output() myEmitter: EventEmitter<number> = new EventEmitter<number>();

private myValue: number = 0;

public increment(n: number){
  this.myValue += n;

  // Send a change event to the emitter
  this.myEmitter.emit(this.myValue);
}

ParentComponent.html

<child-component (myEmitter)="monitorChanges($event)"></child-component>
<br/>
<label>{{n}}</label>

ParentComponent.ts

public n: number = 0;

public monitorChanges(n: number){
  this.n = n;
  console.log(n);
}

This will now update non parent each time the child button is clicked. Working stackblitz

Convert UIImage to NSData and convert back to UIImage in Swift?

Thanks. Helped me a lot. Converted to Swift 3 and worked

To save: let data = UIImagePNGRepresentation(image)

To load: let image = UIImage(data: data)

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

How do I auto-resize an image to fit a 'div' container?

A simple solution (4-step fix!!) that seems to work for me, is below. The example uses the width to determine the overall size, but you can also flip it to use the height instead.

  1. Apply CSS styling to the image container (for example, <img>)
  2. Set the width property to the dimension you want
    • For dimensions, use % for relative size, or autoscaling (based on image container or display)
    • Use px (or other) for a static, or set dimension
  3. Set the height property to automatically adjust, based on the width
  4. ENJOY!

For example,

<img style="width:100%; height:auto;"
    src="https://googledrive.com/host/0BwDx0R31u6sYY1hPWnZrencxb1k/thanksgiving.png"
/>

How to trigger click on page load?

$(function(){

    $(selector).click();

});

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

In case anyone else faces this, it's a case of PHP not having access to the mysql client libraries. Having a MySQL server on the system is not the correct fix. Fix for ubuntu (and PHP 5):

sudo apt-get install php5-mysql

After installing the client, the webserver should be restarted. In case you're using apache, the following should work:

sudo service apache2 restart

How to get file name when user select a file via <input type="file" />?

I'll answer this question via Simple Javascript that is supported in all browsers that I have tested so far (IE8 to IE11, Chrome, FF etc).

Here is the code.

_x000D_
_x000D_
function GetFileSizeNameAndType()_x000D_
        {_x000D_
        var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE._x000D_
_x000D_
        var totalFileSize = 0;_x000D_
_x000D_
        // VALIDATE OR CHECK IF ANY FILE IS SELECTED._x000D_
        if (fi.files.length > 0)_x000D_
        {_x000D_
            // RUN A LOOP TO CHECK EACH SELECTED FILE._x000D_
            for (var i = 0; i <= fi.files.length - 1; i++)_x000D_
            {_x000D_
                //ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE_x000D_
                var fsize = fi.files.item(i).size;_x000D_
                totalFileSize = totalFileSize + fsize;_x000D_
                document.getElementById('fp').innerHTML =_x000D_
                document.getElementById('fp').innerHTML_x000D_
                +_x000D_
                '<br /> ' + 'File Name is <b>' + fi.files.item(i).name_x000D_
                +_x000D_
                '</b> and Size is <b>' + Math.round((fsize / 1024)) //DEFAULT SIZE IS IN BYTES SO WE DIVIDING BY 1024 TO CONVERT IT IN KB_x000D_
                +_x000D_
                '</b> KB and File Type is <b>' + fi.files.item(i).type + "</b>.";_x000D_
            }_x000D_
        }_x000D_
        document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";_x000D_
    }
_x000D_
    <p>_x000D_
        <input type="file" id="file" multiple onchange="GetFileSizeNameAndType()" />_x000D_
    </p>_x000D_
_x000D_
    <div id="fp"></div>_x000D_
    <p>_x000D_
        <div id="divTotalSize"></div>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

*Please note that we are displaying filesize in KB (Kilobytes). To get in MB divide it by 1024 * 1024 and so on*.

It'll perform file outputs like these on selecting Snapshot of a sample output of this code

jQuery’s .bind() vs. .on()

From the jQuery documentation:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

http://api.jquery.com/bind/

Table with fixed header and fixed column on pure css

An actual pure CSS solution with a fixed header row and first column

I had to create a table with both a fixed header and a fixed first column using pure CSS and none of the answers here were quite what I wanted.

The position: sticky property supports both sticking to the top (as I've seen it used the most) and to the side in modern versions of Chrome, Firefox, and Edge. This can be combined with a div that has the overflow: scroll property to give you a table with fixed headers that can be placed anywhere on your page:

Place your table in a container:

<div class="container">
  <table></table>
</div>

Use overflow: scroll on your container to enable scrolling:

div.container {
  overflow: scroll;
}

As Dagmar pointed out in the comments, the container also requires a max-width and a max-height.

Use position: sticky to have table cells stick to the edge and top, right, or left to choose which edge to stick to:

thead th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
}

tbody th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  left: 0;
}

As MarredCheese mentioned in the comments, if your first column contains <td> elements instead of <th> elements, you can use tbody td:first-child in your CSS instead of tbody th

To have the header in the first column stick to the left, use:

thead th:first-child {
  left: 0;
  z-index: 1;
}

_x000D_
_x000D_
/* Use overflow:scroll on your container to enable scrolling: */

div {
  max-width: 400px;
  max-height: 150px;
  overflow: scroll;
}


/* Use position: sticky to have it stick to the edge
 * and top, right, or left to choose which edge to stick to: */

thead th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
}

tbody th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  left: 0;
}


/* To have the header in the first column stick to the left: */

thead th:first-child {
  left: 0;
  z-index: 2;
}


/* Just to display it nicely: */

thead th {
  background: #000;
  color: #FFF;
  /* Ensure this stays above the emulated border right in tbody th {}: */
  z-index: 1;
}

tbody th {
  background: #FFF;
  border-right: 1px solid #CCC;
  /* Browsers tend to drop borders on sticky elements, so we emulate the border-right using a box-shadow to ensure it stays: */
  box-shadow: 1px 0 0 0 #ccc;
}

table {
  border-collapse: collapse;
}

td,
th {
  padding: 0.5em;
}
_x000D_
<div>
  <table>
    <thead>
      <tr>
        <th></th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
    </tbody>
  </table>
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/qwubvg9m/1/

ImportError: No module named win32com.client

I realize this post is old but I wanted to add that I had to take an extra step to get this to work.

Instead of just doing:

pip install pywin32

I had use use the -m flag to get this to work properly. Without it I was running into an issue where I was still getting the error ImportError: No module named win32com.

So to fix this you can give this a try:

python -m pip install pywin32

This worked for me and has worked on several version of python where just doing pip install pywin32 did not work.

Versions tested on:

3.6.2, 3.7.6, 3.8.0, 3.9.0a1.

Oracle database: How to read a BLOB?

If you use the Oracle native data provider rather than the Microsoft driver then you can get at all field types

Dim cn As New Oracle.DataAccess.Client.OracleConnection
Dim cm As New Oracle.DataAccess.Client.OracleCommand
Dim dr As Oracle.DataAccess.Client.OracleDataReader

The connection string does not require a Provider value so you would use something like:

"Data Source=myOracle;UserID=Me;Password=secret"

Open the connection:

cn.ConnectionString = "Data Source=myOracle;UserID=Me;Password=secret"
cn.Open()

Attach the command and set the Sql statement

cm.Connection = cn
cm.CommandText = strCommand

Set the Fetch size. I use 4000 because it's as big as a varchar can be

cm.InitialLONGFetchSize = 4000

Start the reader and loop through the records/columns

dr = cm.ExecuteReader

Do while dr.read()
    strMyLongString = dr(i)
Loop

You can be more specific with the read, eg dr.GetOracleString(i) dr.GetOracleClob(i) etc. if you first identify the data type in the column. If you're reading a LONG datatype then the simple dr(i) or dr.GetOracleString(i) works fine. The key is to ensure that the InitialLONGFetchSize is big enough for the datatype. Note also that the native driver does not support CommandBehavior.SequentialAccess for the data reader but you don't need it and also, the LONG field does not even have to be the last field in the select statement.

Permission denied error while writing to a file in Python

To answer your first question: yes, if the file is not there Python will create it.

Secondly, the user (yourself) running the python script doesn't have write privileges to create a file in the directory.

Angular 2 @ViewChild annotation returns undefined

Here's something that worked for me.

@ViewChild('mapSearch', { read: ElementRef }) mapInput: ElementRef;

ngAfterViewInit() {
  interval(1000).pipe(
        switchMap(() => of(this.mapInput)),
        filter(response => response instanceof ElementRef),
        take(1))
        .subscribe((input: ElementRef) => {
          //do stuff
        });
}

So I basically set a check every second until the *ngIf becomes true and then I do my stuff related to the ElementRef.

Force page scroll position to top at page refresh in HTML

You can use location.replace instead of location.reload:

location.replace(location.href);

This way page will reload with scroll on top.

Displaying a message in iOS which has the same functionality as Toast in Android

Here's your solution :
Put Below code into your Xcode project and enjoy,

- (void)showMessage:(NSString*)message atPoint:(CGPoint)point {
const CGFloat fontSize = 16;

UILabel* label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:@"Helvetica-Bold" size:fontSize];
label.text = message;
label.textColor = UIColorFromRGB(0x07575B);
[label sizeToFit];

label.center = point;

[self.view addSubview:label];

[UIView animateWithDuration:0.3 delay:1 options:0 animations:^{
    label.alpha = 0;
} completion:^(BOOL finished) {
    label.hidden = YES;
    [label removeFromSuperview];
}];
}

How to use ?

[self showMessage:@"Toast in iOS" atPoint:CGPointMake(160, 695)];

JavaScript + Unicode regexes

In JavaScript, \w and \d are ASCII, while \s is Unicode. Don't ask me why. JavaScript does support \p with Unicode categories, which you can use to emulate a Unicode-aware \w and \d.

For \d use \p{N} (numbers)

For \w use [\p{L}\p{N}\p{Pc}\p{M}] (letters, numbers, underscores, marks)

Update: Unfortunately, I was wrong about this. JavaScript does does not officially support \p either, though some implementations may still support this. The only Unicode support in JavaScript regexes is matching specific code points with \uFFFF. You can use those in ranges in character classes.

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

What is the maximum possible length of a .NET string?

Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).

UPDATE: After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException at 1,000,000,000 characters.

using System;
using System.Collections.Generic;

public class MyClass
{
    public static void Main()
    {
        int i = 100000000;
        try
        {
            for (i = i; i <= int.MaxValue; i += 5000)
            {
                string value = new string('x', i);
                //WL(i);
            }
        }
        catch (Exception exc)
        {
            WL(i);
            WL(exc);
        }
        WL(i);
        RL();
    }

    #region Helper methods

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }

    private static void RL()
    {
        Console.ReadLine(); 
    }

    private static void Break() 
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}

Angular - Set headers for every request

I has able to choose a simplier solution > Add a new Headers to the defaults options merge or load by your api get (or other) function.

get(endpoint: string, params?: any, options?: RequestOptions) {
  if (!options) {
    options = new RequestOptions();
    options.headers = new Headers( { "Accept": "application/json" } ); <<<<
  }
  // [...] 
}

Of course you can externalize this Headers in default options or whatever in your class. This is in the Ionic generated api.ts @Injectable() export class API {}

It is very quick and it work for me. I didn't want json/ld format.

How to use the 'main' parameter in package.json?

One important function of the main key is that it provides the path for your entry point. This is very helpful when working with nodemon. If you work with nodemon and you define the main key in your package.json as let say "main": "./src/server/app.js", then you can simply crank up the server with typing nodemon in the CLI with root as pwd instead of nodemon ./src/server/app.js.

Program does not contain a static 'Main' method suitable for an entry point

I have got the same error but then I found out that I typed small m instead of capital M in Main method

How to remove duplicates from a list?

The "contains" method searched for whether the list contains an entry that returns true from Customer.equals(Object o). If you have not overridden equals(Object) in Customer or one of its parents then it will only search for an existing occurrence of the same object. It may be this was what you wanted, in which case your code should work. But if you were looking for not having two objects both representing the same customer, then you need to override equals(Object) to return true when that is the case.

It is also true that using one of the implementations of Set instead of List would give you duplicate removal automatically, and faster (for anything other than very small Lists). You will still need to provide code for equals.

You should also override hashCode() when you override equals().

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

BernardSaucier has already given you an answer. My post is not an answer but an explanation as to why you shouldn't be using UsedRange.

UsedRange is highly unreliable as shown HERE

To find the last column which has data, use .Find and then subtract from it.

With Sheets("Sheet1")
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        lastCol = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByColumns, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Column
    Else
        lastCol = 1
    End If
End With

If lastCol > 8 Then
    'Debug.Print ActiveSheet.UsedRange.Columns.Count - 8

    'The above becomes

    Debug.Print lastCol - 8
End If

How do I set the figure title and axes labels font size in Matplotlib?

You can also do this globally via a rcParams dictionary:

import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
          'figure.figsize': (15, 5),
         'axes.labelsize': 'x-large',
         'axes.titlesize':'x-large',
         'xtick.labelsize':'x-large',
         'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

TypeScript: Creating an empty typed container array

The existing answers missed an option, so here's a complete list:

// 1. Explicitly declare the type
var arr: Criminal[] = [];

// 2. Via type assertion
var arr = <Criminal[]>[];
var arr = [] as Criminal[];

// 3. Using the Array constructor
var arr = new Array<Criminal>();
  1. Explicitly specifying the type is the general solution for whenever type inference fails for a variable declaration.

  2. The advantage of using a type assertion (sometimes called a cast, but it's not really a cast in TypeScript) works for any expression, so it can be used even when no variable is declared. There are two syntaxes for type assertions, but only the latter will work in combination with JSX if you care about that.

  3. Using the Array constructor is something that will only help you in this specific use case, but which I personally find the most readable. However, there is a slight performance impact at runtime*. Also, if someone were crazy enough to redefine the Array constructor, the meaning could change.

It's a matter of personal preference, but I find the third option the most readable. In the vast majority of cases the mentioned downsides would be negligible and readability is the most important factor.

*: Fun fact; at the time of writing the performance difference was 60% in Chrome, while in Firefox there was no measurable performance difference.

How can I enable cURL for an installed Ubuntu LAMP stack?

Try this:

sudo apt-get install -y curl

Delete directories recursively in Java

Two ways to fail with symlinks and the above code... and don't know the solution.

Way #1

Run this to create a test:

echo test > testfile
mkdir dirtodelete
ln -s badlink dirtodelete/badlinktodelete

Here you see your test file and test directory:

$ ls testfile dirtodelete
testfile

dirtodelete:
linktodelete

Then run your commons-io deleteDirectory(). It crashes saying the file is not found. Not sure what the other examples do here. The Linux rm command would simply delete the link, and rm -r on the directory would also.

Exception in thread "main" java.io.FileNotFoundException: File does not exist: /tmp/dirtodelete/linktodelete

Way #2

Run this to create a test:

mkdir testdir
echo test > testdir/testfile
mkdir dirtodelete
ln -s ../testdir dirtodelete/dirlinktodelete

Here you see your test file and test directory:

$ ls dirtodelete testdir
dirtodelete:
dirlinktodelete

testdir:
testfile

Then run your commons-io deleteDirectory() or the example code people posted. It deletes not only the directory, but your testfile which is outside the directory being deleted. (It dereferences the directory implicitly, and deletes the contents). rm -r would delete the link only. You need to use something like this delete the dereferenced files: "find -L dirtodelete -type f -exec rm {} \;".

$ ls dirtodelete testdir
ls: cannot access dirtodelete: No such file or directory
testdir:

Android Studio error: "Environment variable does not point to a valid JVM installation"

Providing both JAVA_HOME and JDK_HOME with identical Path without \bin helped for me! My settings:

  • JAVA_HOME

\Program Files\Java\jdk1.8.0_05

  • JDK_HOME

%JAVA_HOME%

  • PATH

...%JAVA_HOME%\bin

Can I catch multiple Java exceptions in the same catch clause?

Within Java 7 you can define multiple catch clauses like:

catch (IllegalArgumentException | SecurityException e)
{
    ...
}

How to read json file into java with simple JSON library

You can use jackson library and simply use these 3 lines to convert your json file to Java Object.

ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);

Spring Boot - How to get the running port

Please make sure you have imported the correct package

import org.springframework.core.env.Environment;

and then use the Environment object

@Autowired
private Environment env;    // Environment Object containts the port number

 @GetMapping("/status")
  public String status()
    {
   return "it is runing on"+(env.getProperty("local.server.port"));
    }

How to implement the Android ActionBar back button?

Android Annotations:

@OptionsItem(android.R.id.home)
void homeSelected() {
    onBackPressed();
}

Source: https://github.com/excilys/androidannotations

How to send json data in the Http request using NSURLRequest

I would suggest to use ASIHTTPRequest

ASIHTTPRequest is an easy to use wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier. It is written in Objective-C and works in both Mac OS X and iPhone applications.

It is suitable performing basic HTTP requests and interacting with REST-based services (GET / POST / PUT / DELETE). The included ASIFormDataRequest subclass makes it easy to submit POST data and files using multipart/form-data.


Please note, that the original author discontinued with this project. See the followring post for reasons and alternatives: http://allseeing-i.com/%5Brequest_release%5D;

Personally I am a big fan of AFNetworking

Simpler way to create dictionary of separate variables?

>>> a = 1
>>> b = 1
>>> id(a)
34120408
>>> id(b)
34120408
>>> a is b
True
>>> id(a) == id(b)
True

this way get varname for a maybe 'a' or 'b'.

Combining the results of two SQL queries as separate columns

You can use a CROSS JOIN:

SELECT *
FROM (  SELECT SUM(Fdays) AS fDaysSum 
        FROM tblFieldDays 
        WHERE tblFieldDays.NameCode=35 
        AND tblFieldDays.WeekEnding=1) A -- use you real query here
CROSS JOIN (SELECT SUM(CHdays) AS hrsSum 
            FROM tblChargeHours 
            WHERE tblChargeHours.NameCode=35 
            AND tblChargeHours.WeekEnding=1) B -- use you real query here

How to debug "ImagePullBackOff"?

I faced the similar situation and it turned out that with the actualisation of Docker Desktop I was signed out and after I signed back in all works fine again.

Padding a table row

The trick is to give padding on the td elements, but make an exception for the first (yes, it's hacky, but sometimes you have to play by the browser's rules):

td {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;   
}

td:first-child {
  padding-left:20px;
  padding-right:0;
}

First-child is relatively well supported: https://developer.mozilla.org/en-US/docs/CSS/:first-child

You can use the same reasoning for the horizontal padding by using tr:first-child td.

Alternatively, exclude the first column by using the not operator. Support for this is not as good right now, though.

td:not(:first-child) {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;       
}

How to upgrade PowerShell version from 2.0 to 3.0

  1. Install Chocolatey
  2. Run the following commands in CMD

    • choco install powershell

    • choco upgrade powershell

Read specific columns from a csv file with csv module?

Thanks to the way you can index and subset a pandas dataframe, a very easy way to extract a single column from a csv file into a variable is:

myVar = pd.read_csv('YourPath', sep = ",")['ColumnName']

A few things to consider:

The snippet above will produce a pandas Series and not dataframe. The suggestion from ayhan with usecols will also be faster if speed is an issue. Testing the two different approaches using %timeit on a 2122 KB sized csv file yields 22.8 ms for the usecols approach and 53 ms for my suggested approach.

And don't forget import pandas as pd

Creating a list of objects in Python

It shouldn't be necessary to recreate the SimpleClass object each time, as some are suggesting, if you're simply using it to output data based on its attributes. However, you're not actually creating an instance of the class; you're simply creating a reference to the class object itself. Therefore, you're adding a reference to the same class attribute to the list (instead of instance attribute), over and over.

Instead of:

x = SimpleClass

you need:

x = SimpleClass()

Activity has leaked window that was originally added

Try this code:

public class Sample extends Activity(){
@Override
 public void onCreate(Bundle instance){

}
 @Override
    public void onStop() {
        super.onStop();
      progressdialog.dismiss(); // try this
    }

}

Connecting to local SQL Server database using C#

I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.

Hope that helps.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

This is a recurring subject in Stackoverflow and since I was unable to find a relevant implementation I decided to accept the challenge.

I made some modifications to the squares demo present in OpenCV and the resulting C++ code below is able to detect a sheet of paper in the image:

void find_squares(Mat& image, vector<vector<Point> >& squares)
{
    // blur will enhance edge detection
    Mat blurred(image);
    medianBlur(image, blurred, 9);

    Mat gray0(blurred.size(), CV_8U), gray;
    vector<vector<Point> > contours;

    // find squares in every color plane of the image
    for (int c = 0; c < 3; c++)
    {
        int ch[] = {c, 0};
        mixChannels(&blurred, 1, &gray0, 1, ch, 1);

        // try several threshold levels
        const int threshold_level = 2;
        for (int l = 0; l < threshold_level; l++)
        {
            // Use Canny instead of zero threshold level!
            // Canny helps to catch squares with gradient shading
            if (l == 0)
            {
                Canny(gray0, gray, 10, 20, 3); // 

                // Dilate helps to remove potential holes between edge segments
                dilate(gray, gray, Mat(), Point(-1,-1));
            }
            else
            {
                    gray = gray0 >= (l+1) * 255 / threshold_level;
            }

            // Find contours and store them in a list
            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

            // Test contours
            vector<Point> approx;
            for (size_t i = 0; i < contours.size(); i++)
            {
                    // approximate contour with accuracy proportional
                    // to the contour perimeter
                    approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

                    // Note: absolute value of an area is used because
                    // area may be positive or negative - in accordance with the
                    // contour orientation
                    if (approx.size() == 4 &&
                            fabs(contourArea(Mat(approx))) > 1000 &&
                            isContourConvex(Mat(approx)))
                    {
                            double maxCosine = 0;

                            for (int j = 2; j < 5; j++)
                            {
                                    double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                                    maxCosine = MAX(maxCosine, cosine);
                            }

                            if (maxCosine < 0.3)
                                    squares.push_back(approx);
                    }
            }
        }
    }
}

After this procedure is executed, the sheet of paper will be the largest square in vector<vector<Point> >:

opencv paper sheet detection

I'm letting you write the function to find the largest square. ;)

Selenium WebDriver can't find element by link text

The problem might be in the rest of the html, the part that you didn't post.

With this example (I just closed the open tags):

<a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026" href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026">
<div class="col-lg-2 col-sm-3 col-xs-4 item-list-image">
<img ng-src="csa/images/library/Service_Design.png" src="csa/images/library/Service_Design.png">
</div>
<div class="col-lg-8 col-sm-9 col-xs-8">
<div class="col-xs-12">
    <p>
    <strong class="ng-binding">Smoke Sequential</strong>
    </p>
    </div>
</div>
</a>

I was able to find the element without trouble with:

driver.findElement(By.linkText("Smoke Sequential")).click();

If there is more text inside the element, you could try a find by partial link text:

driver.findElement(By.partialLinkText("Sequential")).click();

Cast a Double Variable to Decimal

Well this is an old question and I indeed made use of some of the answers shown here. Nevertheless, in my particular scenario it was possible that the double value that I wanted to convert to decimal was often bigger than decimal.MaxValue. So, instead of handling exceptions I wrote this extension method:

    public static decimal ToDecimal(this double @double) => 
        @double > (double) decimal.MaxValue ? decimal.MaxValue : (decimal) @double;

The above approach works if you do not want to bother handling overflow exceptions and if such a thing happen you want just to keep the max possible value(my case), but I am aware that for many other scenarios this would not be the expected behavior and may be the exception handling will be needed.

How to remove empty lines with or without whitespace in Python

I use this solution to delete empty lines and join everything together as one line:

match_p = re.sub(r'\s{2}', '', my_txt) # my_txt is text above

HttpServletRequest - Get query string parameters, no form data

As the other answers state there is no way getting query string parameters using servlet api.

So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)

I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.

Example: username=james&username=smith&password=pwd1,pwd2 will return

password : [pwd1, pwd2] (length = 2)

username : [james, smith] (length = 2)

public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
    Map<String, String[]> queryParameters = new HashMap<>();
    String queryString = request.getQueryString();
    if (StringUtils.isNotEmpty(queryString)) {
        queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
        String[] parameters = queryString.split("&");
        for (String parameter : parameters) {
            String[] keyValuePair = parameter.split("=");
            String[] values = queryParameters.get(keyValuePair[0]);
            //length is one if no value is available.
            values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
                    ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
            queryParameters.put(keyValuePair[0], values);
        }
    }
    return queryParameters;
}

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Safe String to BigDecimal conversion

I needed a solution to convert a String to a BigDecimal without knowing the locale and being locale-independent. I couldn't find any standard solution for this problem so i wrote my own helper method. May be it helps anybody else too:

Update: Warning! This helper method works only for decimal numbers, so numbers which always have a decimal point! Otherwise the helper method could deliver a wrong result for numbers between 1000 and 999999 (plus/minus). Thanks to bezmax for his great input!

static final String EMPTY = "";
static final String POINT = '.';
static final String COMMA = ',';
static final String POINT_AS_STRING = ".";
static final String COMMA_AS_STRING = ",";

/**
     * Converts a String to a BigDecimal.
     *     if there is more than 1 '.', the points are interpreted as thousand-separator and will be removed for conversion
     *     if there is more than 1 ',', the commas are interpreted as thousand-separator and will be removed for conversion
     *  the last '.' or ',' will be interpreted as the separator for the decimal places
     *  () or - in front or in the end will be interpreted as negative number
     *
     * @param value
     * @return The BigDecimal expression of the given string
     */
    public static BigDecimal toBigDecimal(final String value) {
        if (value != null){
            boolean negativeNumber = false;

            if (value.containts("(") && value.contains(")"))
               negativeNumber = true;
            if (value.endsWith("-") || value.startsWith("-"))
               negativeNumber = true;

            String parsedValue = value.replaceAll("[^0-9\\,\\.]", EMPTY);

            if (negativeNumber)
               parsedValue = "-" + parsedValue;

            int lastPointPosition = parsedValue.lastIndexOf(POINT);
            int lastCommaPosition = parsedValue.lastIndexOf(COMMA);

            //handle '1423' case, just a simple number
            if (lastPointPosition == -1 && lastCommaPosition == -1)
                return new BigDecimal(parsedValue);
            //handle '45.3' and '4.550.000' case, only points are in the given String
            if (lastPointPosition > -1 && lastCommaPosition == -1){
                int firstPointPosition = parsedValue.indexOf(POINT);
                if (firstPointPosition != lastPointPosition)
                    return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY));
                else
                    return new BigDecimal(parsedValue);
            }
            //handle '45,3' and '4,550,000' case, only commas are in the given String
            if (lastPointPosition == -1 && lastCommaPosition > -1){
                int firstCommaPosition = parsedValue.indexOf(COMMA);
                if (firstCommaPosition != lastCommaPosition)
                    return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY));
                else
                    return new BigDecimal(parsedValue.replace(COMMA, POINT));
            }
            //handle '2.345,04' case, points are in front of commas
            if (lastPointPosition < lastCommaPosition){
                parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY);
                return new BigDecimal(parsedValue.replace(COMMA, POINT));
            }
            //handle '2,345.04' case, commas are in front of points
            if (lastCommaPosition < lastPointPosition){
                parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY);
                return new BigDecimal(parsedValue);
            }
            throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal.");
        }
        return null;
    }

Of course i've tested the method:

@Test(dataProvider = "testBigDecimals")
    public void toBigDecimal_defaultLocaleTest(String stringValue, BigDecimal bigDecimalValue){
        BigDecimal convertedBigDecimal = DecimalHelper.toBigDecimal(stringValue);
        Assert.assertEquals(convertedBigDecimal, bigDecimalValue);
    }
    @DataProvider(name = "testBigDecimals")
    public static Object[][] bigDecimalConvertionTestValues() {
        return new Object[][] {
                {"5", new BigDecimal(5)},
                {"5,3", new BigDecimal("5.3")},
                {"5.3", new BigDecimal("5.3")},
                {"5.000,3", new BigDecimal("5000.3")},
                {"5.000.000,3", new BigDecimal("5000000.3")},
                {"5.000.000", new BigDecimal("5000000")},
                {"5,000.3", new BigDecimal("5000.3")},
                {"5,000,000.3", new BigDecimal("5000000.3")},
                {"5,000,000", new BigDecimal("5000000")},
                {"+5", new BigDecimal("5")},
                {"+5,3", new BigDecimal("5.3")},
                {"+5.3", new BigDecimal("5.3")},
                {"+5.000,3", new BigDecimal("5000.3")},
                {"+5.000.000,3", new BigDecimal("5000000.3")},
                {"+5.000.000", new BigDecimal("5000000")},
                {"+5,000.3", new BigDecimal("5000.3")},
                {"+5,000,000.3", new BigDecimal("5000000.3")},
                {"+5,000,000", new BigDecimal("5000000")},
                {"-5", new BigDecimal("-5")},
                {"-5,3", new BigDecimal("-5.3")},
                {"-5.3", new BigDecimal("-5.3")},
                {"-5.000,3", new BigDecimal("-5000.3")},
                {"-5.000.000,3", new BigDecimal("-5000000.3")},
                {"-5.000.000", new BigDecimal("-5000000")},
                {"-5,000.3", new BigDecimal("-5000.3")},
                {"-5,000,000.3", new BigDecimal("-5000000.3")},
                {"-5,000,000", new BigDecimal("-5000000")},
                {null, null}
        };
    }

How do I fix the indentation of selected lines in Visual Studio

Selecting all the text you wish to format and pressing CtrlK, CtrlF shortcut applies the indenting and space formatting.

As specified in the Formatting pane (of the language being used) in the Text Editor section of the Options dialog.

See VS Shortcuts for more.

How to access remote server with local phpMyAdmin client?

In Ubuntu

Just you need to modify a single file in PHPMyAdmin folder i.e. “config.inc.php”.Just add below lines to your “config.inc.php”.

File location : /var/lib/phpmyadmin/config.inc.php OR /etc/phpmyadmin/config.inc.php

Maybe you don't have the permission for editing that file, just give the permission using this command

sudo chmod 777 /var/lib/phpmyadmin/config.inc.php

OR (in different systems you may have to check with these two locations)

sudo chmod 777 /etc/phpmyadmin/config.inc.php

Then copy and paste the code in your config.inc.php file

    $i++;
    $cfg['Servers'][$i]['auth_type']     = 'cookie';
    $cfg['Servers'][$i]['verbose'] = 'Database Server 2';
    $cfg['Servers'][$i]['host'] = '34.12.123.31';
    $cfg['Servers'][$i]['connect_type']  = 'tcp';
    $cfg['Servers'][$i]['compress']      = false;
    $cfg['Servers'][$i]['AllowNoPassword'] = false;

And make the appropriate changes with your server details

What REST PUT/POST/DELETE calls should return by a convention?

I like Alfonso Tienda responce from HTTP status code for update and delete?

Here are some Tips:

DELETE

  • 200 (if you want send some additional data in the Response) or 204 (recommended).

  • 202 Operation deleted has not been committed yet.

  • If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204, but it's true that idempotent doesn't necessarily imply the same response)

Other errors:

  • 400 Bad Request (Malformed syntax or a bad query is strange but possible).
  • 401 Unauthorized Authentication failure
  • 403 Forbidden: Authorization failure or invalid Application ID.
  • 405 Not Allowed. Sure.
  • 409 Resource Conflict can be possible in complex systems.
  • And 501, 502 in case of errors.

PUT

If you're updating an element of a collection

  • 200/204 with the same reasons as DELETE above.
  • 202 if the operation has not been commited yet.

The referenced element doesn't exists:

  • PUT can be 201 (if you created the element because that is your behaviour)

  • 404 If you don't want to create elements via PUT.

  • 400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).

  • 401 Unauthorized

  • 403 Forbidden: Authentication failure or invalid Application ID.

  • 405 Not Allowed. Sure.

  • 409 Resource Conflict can be possible in complex systems, as in DELETE.

  • 422 Unprocessable entity It helps to distinguish between a "Bad request" (e.g. malformed XML/JSON) and invalid field values

  • And 501, 502 in case of errors.

How do you do exponentiation in C?

Similar to an earlier answer, this will handle positive and negative integer powers of a double nicely.

double intpow(double a, int b)
{
  double r = 1.0;
  if (b < 0)
  {
    a = 1.0 / a;
    b = -b;
  }
  while (b)
  {
    if (b & 1)
      r *= a;
    a *= a;
    b >>= 1;
  }
  return r;
}

How to show loading spinner in jQuery?

JavaScript

$.listen('click', '#captcha', function() {
    $('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />');
    $.get("/captcha/new", null, function(data) {
        $('#captcha-block').html(data);
    }); 
    return false;
});

CSS

#loading { background: url(/image/loading.gif) no-repeat center; }

How to resume Fragment from BackStack if exists

Step 1: Implement an interface with your activity class

public class AuthenticatedMainActivity extends Activity implements FragmentManager.OnBackStackChangedListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        .............
        FragmentManager fragmentManager = getFragmentManager();           
        fragmentManager.beginTransaction().add(R.id.frame_container,fragment, "First").addToBackStack(null).commit();
    }

    private void switchFragment(Fragment fragment){            
      FragmentManager fragmentManager = getFragmentManager();
      fragmentManager.beginTransaction()
        .replace(R.id.frame_container, fragment).addToBackStack("Tag").commit();
    }

    @Override
    public void onBackStackChanged() {
    FragmentManager fragmentManager = getFragmentManager();

    System.out.println("@Class: SummaryUser : onBackStackChanged " 
            + fragmentManager.getBackStackEntryCount());

    int count = fragmentManager.getBackStackEntryCount();

    // when a fragment come from another the status will be zero
    if(count == 0){

        System.out.println("again loading user data");

        // reload the page if user saved the profile data

        if(!objPublicDelegate.checkNetworkStatus()){

            objPublicDelegate.showAlertDialog("Warning"
                    , "Please check your internet connection");

        }else {

            objLoadingDialog.show("Refreshing data..."); 

            mNetworkMaster.runUserSummaryAsync();
        }

        // IMPORTANT: remove the current fragment from stack to avoid new instance
        fragmentManager.removeOnBackStackChangedListener(this);

    }// end if
   }       
}

Step 2: When you call the another fragment add this method:

String backStateName = this.getClass().getName();

FragmentManager fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this); 

Fragment fragmentGraph = new GraphFragment();
Bundle bundle = new Bundle();
bundle.putString("graphTag",  view.getTag().toString());
fragmentGraph.setArguments(bundle);

fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragmentGraph)
.addToBackStack(backStateName)
.commit();

How can I create a dynamically sized array of structs?

Here is how I would do it in C++

size_t size = 500;
char* dynamicAllocatedString = new char[ size ];

Use same principal for any struct or c++ class.

How to convert timestamps to dates in Bash?

You can use GNU date, for example,

$ sec=1267619929
$ date -d "UTC 1970-01-01 $sec secs"

or

$ date -ud @1267619929

Python: Remove division decimal

When a number as a decimal it is usually a float in Python.

If you want to remove the decimal and keep it an integer (int). You can call the int() method on it like so...

>>> int(2.0)
2

However, int rounds down so...

>>> int(2.9)
2

If you want to round to the nearest integer you can use round:

>>> round(2.9)
3.0
>>> round(2.4)
2.0

And then call int() on that:

>>> int(round(2.9))
3
>>> int(round(2.4))
2

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

Trouble setting up git with my GitHub Account error: could not lock config file

I have "experienced" this error on Windows because my name (and hence %HOMEPATH%) contains a non ascii character (é). Either git or cmd.exe or anything else could not cope with this.

Batch files : How to leave the console window open

rem Just use "pause" at the end of the batch file.
...
......
.......
pause

What are Maven goals and phases and what is their difference?

The definitions are detailed at the Maven site's page Introduction to the Build Lifecycle, but I have tried to summarize:

Maven defines 4 items of a build process:

  1. Lifecycle

    Three built-in lifecycles (aka build lifecycles): default, clean, site. (Lifecycle Reference)

  2. Phase

    Each lifecycle is made up of phases, e.g. for the default lifecycle: compile, test, package, install, etc.

  3. Plugin

    An artifact that provides one or more goals.

    Based on packaging type (jar, war, etc.) plugins' goals are bound to phases by default. (Built-in Lifecycle Bindings)

  4. Goal

    The task (action) that is executed. A plugin can have one or more goals.

    One or more goals need to be specified when configuring a plugin in a POM. Additionally, in case a plugin does not have a default phase defined, the specified goal(s) can be bound to a phase.

Maven can be invoked with:

  1. a phase (e.g clean, package)
  2. <plugin-prefix>:<goal> (e.g. dependency:copy-dependencies)
  3. <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal> (e.g. org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile)

with one or more combinations of any or all, e.g.:

mvn clean dependency:copy-dependencies package

RunAs A different user when debugging in Visual Studio

cmd.exe is located in different locations in different versions of Windows. To avoid needing the location of cmd.exe, you can use the command moogs wrote without calling "cmd.exe /C".

Here's an example that worked for me:

  1. Open Command Prompt
  2. Change directory to where your application's .exe file is located.
  3. Execute the following command: runas /user:domain\username Application.exe

So the final step will look something like this in Command Prompt:

C:\Projects\MyProject\bin\Debug>runas /user:domain\username Application.exe

Note: the domain name was required in my situation.

Get difference between two dates in months using Java

If you can't use JodaTime, you can do the following:

Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);

int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);

Note that if your dates are 2013-01-31 and 2013-02-01, you get a distance of 1 month this way, which may or may not be what you want.

Trying to use Spring Boot REST to Read JSON String from POST

I think the simplest/handy way to consuming JSON is using a Java class that resembles your JSON: https://stackoverflow.com/a/6019761

But if you can't use a Java class you can use one of these two solutions.

Solution 1: you can do it receiving a Map<String, Object> from your controller:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object> payload) 
    throws Exception {

  System.out.println(payload);

}

Using your request:

curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process

Solution 2: otherwise you can get the POST payload as a String:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST,
    consumes = "text/plain")
public void process(@RequestBody String payload) throws Exception {

  System.out.println(payload);

}

Then parse the string as you want. Note that must be specified consumes = "text/plain" on your controller. In this case you must change your request with Content-type: text/plain:

curl -H "Accept: application/json" -H "Content-type: text/plain" -X POST \
-d '{"name":"value"}' http://localhost:8080/myservice/process

Create a table without a header in Markdown

I got this working with Bitbucket's Markdown by using a empty link:

[]()  | 
------|------
Row 1 | row 2

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

How to use wget in php?

This method is only one class and doesn't require importing other libraries or reusing code.

Personally I use this script that I made a while ago. Located here but for those who don't want to click on that link you can view it below. It lets the developer use the static method HTTP::GET($url, $options) to use the get method in curl while being able to pass through custom curl options. You can also use HTTP::POST($url, $options) but I hardly use that method.

/**
  *  echo HTTP::POST('http://accounts.kbcomp.co',
  *      array(
  *            'user_name'=>'[email protected]',
  *            'user_password'=>'demo1234'
  *      )
  *  );
  *  OR
  *  echo HTTP::GET('http://api.austinkregel.com/colors/E64B3B/1');
  *                  
  */

class HTTP{
   public static function GET($url,Array $options=array()){
    $ch = curl_init();
    if(count($options>0)){
       curl_setopt_array($ch, $options);
       curl_setopt($ch, CURLOPT_URL, $url);
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
     }
   }
   public static function POST($url, $postfields, $options = null){
       $ch = curl_init();
       $options = array(
          CURLOPT_URL=>$url,
          CURLOPT_RETURNTRANSFER => TRUE,
          CURLOPT_POSTFIELDS => $postfields,
          CURLOPT_HEADER => true
          //CURLOPT_HTTPHEADER, array('Content-Type:application/json')
          ); 
       if(count($options>0)){
           curl_setopt_array($ch, $options);
       }
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
   }
}

SELECT INTO USING UNION QUERY

select *
into new_table
from table_A
UNION
Select * 
From table_B

This only works if Table_A and Table_B have the same schemas

Windows batch: echo without new line

Sample 1: This works and produces Exit code = 0. That is Good. Note the "." , directly after echo.

C:\Users\phife.dog\gitrepos\1\repo_abc\scripts #
@echo.| set /p JUNK_VAR=This is a message displayed like Linux echo -n would display it ... & echo %ERRORLEVEL%

This is a message displayed like Linux echo -n would display it ... 0

Sample 2: This works but produces Exit code = 1. That is Bad. Please note the lack of ".", after echo. That appears to be the difference.

C:\Users\phife.dog\gitrepos\1\repo_abc\scripts #
@echo | set /p JUNK_VAR=This is a message displayed like Linux echo -n would display it ... & echo %ERRORLEVEL%

This is a message displayed like Linux echo -n would display it ... 1

Ternary operators in JavaScript without an "else"

In your case i see the ternary operator as redundant. You could assign the variable directly to the expression, using ||, && operators.

!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null ;

will become :

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

It's more clear, it's more "javascript" style.

I can't install python-ldap

python3 does not support python-ldap. Rather to install ldap3.

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

Determine if char is a num or letter

<ctype.h> includes a range of functions for determining if a char represents a letter or a number, such as isalpha, isdigit and isalnum.

The reason why int a = (int)theChar won't do what you want is because a will simply hold the integer value that represents a specific character. For example the ASCII number for '9' is 57, and for 'a' it's 97.

Also for ASCII:

  • Numeric - if (theChar >= '0' && theChar <= '9')
  • Alphabetic -
    if (theChar >= 'A' && theChar <= 'Z' || theChar >= 'a' && theChar <= 'z')

Take a look at an ASCII table to see for yourself.

How to get the text of the selected value of a dropdown list?

The easiest way is through css3 $("select option:selected") and then use the .text() or .html() function. depending on what you want to have.

Does "git fetch --tags" include "git fetch"?

In most situations, git fetch should do what you want, which is 'get anything new from the remote repository and put it in your local copy without merging to your local branches'. git fetch --tags does exactly that, except that it doesn't get anything except new tags.

In that sense, git fetch --tags is in no way a superset of git fetch. It is in fact exactly the opposite.

git pull, of course, is nothing but a wrapper for a git fetch <thisrefspec>; git merge. It's recommended that you get used to doing manual git fetching and git mergeing before you make the jump to git pull simply because it helps you understand what git pull is doing in the first place.

That being said, the relationship is exactly the same as with git fetch. git pull is the superset of git pull --tags.

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

I had the same issue. I checked the version of System.Data.SqlServerCe in C:\Windows\assembly. It was 3.5.1.0. So I installed version 4.0.0 from below link (x86) and works fine.

http://www.microsoft.com/download/en/details.aspx?id=17876

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

How to run shell script file using nodejs?

You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.

hi.sh

echo "Hi There!"

node_program.js

const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
        (error, stdout, stderr) => {
            console.log(stdout);
            console.log(stderr);
            if (error !== null) {
                console.log(`exec error: ${error}`);
            }
        });

Here, when I run the nodejs file, it will execute the shell file and the output would be:

Run

node node_program.js

output

Hi There!

You can execute any script just by mentioning the shell command or shell script in exec callback.

Hope this helps! Happy coding :)

PPT to PNG with transparent background

Here is my preferred quickest and easiest solution. Works well if all slides have the same background color that you want to remove.

Step 1. In Powerpoint, "Save As" (shortcut F12) PNG, "All Slides".

Now you have a folder full of these PNG images of all your slides. The problem is that they still have a background. So now:

Step 2. Batch remove background color of all the PNG images, for example by following the steps in this SE answer.

Ripple effect on Android Lollipop CardView

I wasn't happy with AppCompat, so I wrote my own CardView and backported ripples. Here it's running on Galaxy S with Gingerbread, so it's definitely possible.

Demo of Ripple on Galaxy S

For more details check the source code.

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

Launch custom android application from android browser

You need to add a pseudo-hostname to the CALLBACK_URL 'app://' doesn't make sense as a URL and cannot be parsed.

Route.get() requires callback functions but got a "object Undefined"

(1) Make sure that you have imported the corresponding controller file in router file

(2) Make sure that the function name written in the any of the router.get() or router.post() in router.js file is exactly same as the function name written in the corresponding controller file

(3) Make sure that you have written module.exports=router; at the bottom of router.js file

How do I start/stop IIS Express Server?

You can stop any IIS Express application or you can stop all application. Right click on IIS express icon , which is located at right bottom corner of task bar. Then Select Show All Application

enter image description here

Remove all whitespace in a string

"Whitespace" includes space, tabs, and CRLF. So an elegant and one-liner string function we can use is str.translate:

Python 3

' hello  apple '.translate(str.maketrans('', '', ' \n\t\r'))

OR if you want to be thorough:

import string
' hello  apple'.translate(str.maketrans('', '', string.whitespace))

Python 2

' hello  apple'.translate(None, ' \n\t\r')

OR if you want to be thorough:

import string
' hello  apple'.translate(None, string.whitespace)

Hiding and Showing TabPages in tabControl

TabPanel1.Visible = true; // Show Tabpage 1
TabPanel1.Visible = false; //Hide Tabpage 1

Where can I find the assembly System.Web.Extensions dll?

I had this issue when converting an older project to use a new version of Visual Studio. Upon conversion, the project target framework was set to 2.0

I was able to solve this issue by changing the target framework to be 3.5.

Mongoose: Get full list of users

Well, if you really want to return a mapping from _id to user, you could always do:

server.get('/usersList', function(req, res) {
  User.find({}, function(err, users) {
    var userMap = {};

    users.forEach(function(user) {
      userMap[user._id] = user;
    });

    res.send(userMap);  
  });
});

find() returns all matching documents in an array, so your last code snipped sends that array to the client.

How to pause a vbscript execution?

With 'Enter' is better use ReadLine() or Read(2), because key 'Enter' generate 2 symbols. If user enter any text next Pause() also wil be skipped even with Read(2). So ReadLine() is better:

Sub Pause()
    WScript.Echo ("Press Enter to continue")
    z = WScript.StdIn.ReadLine()
End Sub

More examples look in http://technet.microsoft.com/en-us/library/ee156589.aspx

How to show android checkbox at right side?

You can use this also,

<CheckBox
       android:layout_width="match_parent"     
       android:layout_height="@dimen/button_height_35"
       android:text="@string/english"
       android:checked="true"
       android:paddingEnd="@dimen/padding_5"
       android:paddingStart="@dimen/padding_5"
       android:layoutDirection="rtl"
       android:drawablePadding="@dimen/padding_5"
       android:drawableEnd="@drawable/ic_english"
       style="@style/TextStyleSemiBold"
       android:textSize="@dimen/text_15"
       android:button="@drawable/language_selector"/>

Does Python have “private” variables in classes?

About sources (to change the access rights and thus bypass language encapsulation like java or C ++): You don't always have the sources and EVEN if you do, the sources are managed by a system that only allows certain programmers to access a source (in a professional context). Often, every programmer is responsible for certain classes and therefore knows what he can and cannot do. The source manager also locks the sources being modified and of course, manages the access rights of programmers.

So i trust more in software than in human, by experience. So convention is good but MULTIPLE protections are better, like access management (real private variable) + sources management.

How to count items in JSON data

You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':

len(data['result'][0]['run'])

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

This project should be helpful - maps touch events to click events in a way that allows jQuery UI to work on iPad and iPhone without any changes. Just add the JS to any existing project.

http://code.google.com/p/jquery-ui-for-ipad-and-iphone/

How can an html element fill out 100% of the remaining screen height, using css only?

In this instance I want my main content div to be liquid height so that the whole page takes up 100% of the browser height.

height: 100vh;

JSHint and jQuery: '$' is not defined

Instead of recommending the usual "turn off the JSHint globals", I recommend using the module pattern to fix this problem. It keeps your code "contained" and gives a performance boost (based on Paul Irish's "10 things I learned about Jquery").

I tend to write my module patterns like this:

(function (window) {
    // Handle dependencies
    var angular = window.angular,
        $ = window.$,
        document = window.document;

    // Your application's code
}(window))

You can get these other performance benefits (explained more here):

  • When minifying code, the passed in window object declaration gets minified as well. e.g. window.alert() become m.alert().
  • Code inside the self-executing anonymous function only uses 1 instance of the window object.
  • You cut to the chase when calling in a window property or method, preventing expensive traversal of the scope chain e.g. window.alert() (faster) versus alert() (slower) performance.
  • Local scope of functions through "namespacing" and containment (globals are evil). If you need to break up this code into separate scripts, you can make a submodule for each of those scripts, and have them imported into one main module.

How to Resize a Bitmap in Android?

try this this code :

BitmapDrawable drawable = (BitmapDrawable) imgview.getDrawable();
Bitmap bmp = drawable.getBitmap();
Bitmap b = Bitmap.createScaledBitmap(bmp, 120, 120, false);

I hope it's useful.

How do I speed up the gwt compiler?

  • Split your application into multiple modules or entry points and re-compile then only when needed.
  • Analyse your application using the trunk version - which provides the Story of your compile. This may or may not be relevant to the 1.6 compiler but it can indicate what's going on.

Laravel 5 not finding css files

In the root path create a .htaccess file with

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/public/ 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f



RewriteRule ^(.*)$ /public/$1 
#RewriteRule ^ index.php [L]
RewriteRule ^(/)?$ public/index.php [L] 
</IfModule>

In public directory create a .htaccess file

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

if you have done any changes in public/index.php file correct them with the right path then your site will be live.

what will solve with this?

  • Hosting issue of laravel project.
  • Css not work on laravel.
  • Laravel site not work.
  • laravel site load with domain/public/index.php
  • laravel project does not redirect correctly

How can I move all the files from one folder to another using the command line?

Lookup move /? on Windows and man mv on Unix systems

MySQL Query - Records between Today and Last 30 Days

SELECT
    *
FROM
    < table_name >
WHERE
    < date_field > BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY)
AND NOW();

C Linking Error: undefined reference to 'main'

You're not including the C file that contains main() when compiling, so the linker isn't seeing it.

You need to add it:

$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

Comparison of DES, Triple DES, AES, blowfish encryption for data

All of these schemes, except AES and Blowfish, have known vulnerabilities and should not be used.
However, Blowfish has been replaced by Twofish.

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

How to solve ADB device unauthorized in Android ADB host device?

You must be prompted in your s4 screen to authorize that computer. You can tell it to remember it. This is for security reasons, occurring in Android 4.4+

Table border left and bottom

You need to use the border property as seen here: jsFiddle

HTML:

<table width="770">
    <tr>
        <td class="border-left-bottom">picture (border only to the left and bottom ) </td>
        <td>text</td>
    </tr>
    <tr>
        <td>text</td>
        <td class="border-left-bottom">picture (border only to the left and bottom) </td>
    </tr>
</table>`

CSS:

td.border-left-bottom{
    border-left: solid 1px #000;
    border-bottom: solid 1px #000;
}

Find largest and smallest number in an array

int main () //start of main fcn
{

    int values[ 20 ]; //delcares array and how many elements
    int small,big; //declares integer
     for ( int i = 0; i < 20; i++ ) //counts to 20 and prompts user for value and stores it
    {
        cout << "Enter value " << i << ": ";
        cin >> values[i];
    }
    big=small=values[0]; //assigns element to be highest or lowest value
    for (int i = 0; i < 20; i++) //works out bigggest number
    {
        if(values[i]>big) //compare biggest value with current element
        {
            big=values[i];
        }
         if(values[i]<small) //compares smallest value with current element
        {
            small=values[i];
        }
    }
     cout << "The biggest number is " << big << endl; //prints outs biggest no
    cout << "The smallest number is " << small << endl; //prints out smalles no
}

Utility of HTTP header "Content-Type: application/force-download" for mobile?

application/force-download is not a standard MIME type. It's a hack supported by some browsers, added fairly recently.

Your question doesn't really make any sense. It's like asking why Internet Explorer 4 doesn't support the latest CSS 3 functionality.

Change a Nullable column to NOT NULL with Default Value

I think you will need to do this as three separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.

ALTER TABLE dbo.MyTable
ADD CONSTRAINT my_Con DEFAULT GETDATE() for created

UPDATE MyTable SET Created = GetDate() where Created IS NULL

ALTER TABLE dbo.MyTable 
ALTER COLUMN Created DATETIME NOT NULL 

Going to a specific line number using Less in Unix

From within less (in Linux):

 g and the line number to go forward

 G and the line number to go backwards

Used alone, g and G will take you to the first and last line in a file respectively; used with a number they are both equivalent.

An example; you want to go to line 320123 of a file,

press 'g' and after the colon type in the number 320123

Additionally you can type '-N' inside less to activate / deactivate the line numbers. You can as a matter of fact pass any command line switches from inside the program, such as -j or -N.

NOTE: You can provide the line number in the command line to start less (less +number -N) which will be much faster than doing it from inside the program:

less +12345 -N /var/log/hugelogfile

This will open a file displaying the line numbers and starting at line 12345

Source: man 1 less and built-in help in less (less 418)

Two values from one input in python?

In Python 3, raw_input() was renamed to input().

input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So you can do this way

x, y = input('Enter two numbers separating by a space: ').split();
print(int(x) + int(y))

If you do not put two numbers using a space you would get a ValueError exception. So that is good to go.

N.B. If you need old behavior of input(), use eval(input())

If my interface must return Task what is the best way to have a no-operation implementation?

Task.Delay(0) as in the accepted answer was a good approach, as it is a cached copy of a completed Task.

As of 4.6 there's now Task.CompletedTask which is more explicit in its purpose, but not only does Task.Delay(0) still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask.

The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0) was better than the accepted answer.

Switch android x86 screen resolution

I'd like to clarify one small gotcha here. You must use CustomVideoMode1 before CustomVideoMode2, etc. VirtualBox recognizes these modes in order starting from 1 and if you skip a number, it will not recognize anything at or beyond the number you skipped. This caught me by surprise.

Running code after Spring Boot starts

you can use @Component

@RequiredArgsConstructor
@Component
@Slf4j
public class BeerLoader implements CommandLineRunner {
    //declare 

    @Override
    public void run(String... args) throws Exception {
        //some code here 

    }

Is right click a Javascript event?

No, but you can detect what mouse button was used in the "onmousedown" event... and from there determine if it was a "right-click".

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.

Since c++11 mutable can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):

int x = 0;
auto f1 = [=]() mutable {x = 42;};  // OK
auto f2 = [=]()         {x = 42;};  // Error: a by-value capture cannot be modified in a non-mutable lambda

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Then the problem came back. I uninstalled both Microsoft.CodeDom.Providers.DotNetCompilerPlatform and Uninstall-package Microsoft.Net.Compilers but no help. Then installed - no help. Cleaned project and built no help. Restarted server no help.Then I noticed the project needed not the latest one which is currently 1.0.5 but 1.0.3 as that was the error could not load the 1.0.3 version. So I installed that dll version instead and now it works.

java: use StringBuilder to insert at the beginning

Difference Between String, StringBuilder And StringBuffer Classes
String
String is immutable ( once created can not be changed )object. The object created as a
String is stored in the Constant String Pool.
Every immutable object in Java is thread-safe, which implies String is also thread-safe. String
can not be used by two threads simultaneously.
String once assigned can not be changed.
StringBuffer
StringBuffer is mutable means one can change the value of the object. The object created
through StringBuffer is stored in the heap. StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this, it does not allow two threads to simultaneously access the same method. Each
method can be accessed by one thread at a time.
But being thread-safe has disadvantages too as the performance of the StringBuffer hits due
to thread-safe property. Thus StringBuilder is faster than the StringBuffer when calling the
same methods of each class.
String Buffer can be converted to the string by using
toString() method.

    StringBuffer demo1 = new StringBuffer("Hello") ;

// The above object stored in heap and its value can be changed.
/
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is the same as the StringBuffer, that is it stores the object in heap and it can also
be modified. The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread-safe.
StringBuilder is fast as it is not thread-safe.
/
// The above object is stored in the heap and its value can be modified
/
// Above statement is right as it modifies the value which is allowed in the StringBuilder

How do I call one constructor from another in Java?

You can a constructor from another constructor of same class by using "this" keyword. Example -

class This1
{
    This1()
    {
        this("Hello");
        System.out.println("Default constructor..");
    }
    This1(int a)
    {
        this();
        System.out.println("int as arg constructor.."); 
    }
    This1(String s)
    {
        System.out.println("string as arg constructor..");  
    }

    public static void main(String args[])
    {
        new This1(100);
    }
}

Output - string as arg constructor.. Default constructor.. int as arg constructor..

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

XHR polling vs SSE vs WebSockets

  • XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.

    The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia

  • Server Sent Events Client sends request to server. Server sends new data to webpage at any time.

    Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla

  • WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.

    The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia

Algorithm for solving Sudoku

There are four steps to solve a sudoku puzzle:

  1. Identify all possibilities for each cell (getting from the row, column and box) and try to develop a possible matrix. 2.Check for double pair, if it exists then remove these two values from all the cells in that row/column/box, wherever the pair exists If any cell is having single possiblity then assign that run step 1 again
  2. Check for each cell with each row, column and box. If the cell has one value which does not belong in the other possible values then assign that value to that cell. run step 1 again
  3. If the sudoku is still not solved, then we need to start the following assumption, Assume the first possible value and assign. Then run step 1–3 If still not solved then do it for next possible value and run it in recursion.
  4. If the sudoku is still not solved, then we need to start the following assumption, Assume the first possible value and assign. Then run step 1–3

If still not solved then do it for next possible value and run it in recursion.

import math
import sys


def is_solved(l):
    for x, i in enumerate(l):
        for y, j in enumerate(i):
            if j == 0:
                # Incomplete
                return None
            for p in range(9):
                if p != x and j == l[p][y]:
                    # Error
                    print('horizontal issue detected!', (x, y))
                    return False
                if p != y and j == l[x][p]:
                    # Error
                    print('vertical issue detected!', (x, y))
                    return False
            i_n, j_n = get_box_start_coordinate(x, y)
            for (i, j) in [(i, j) for p in range(i_n, i_n + 3) for q in range(j_n, j_n + 3)
                           if (p, q) != (x, y) and j == l[p][q]]:
                    # Error
                print('box issue detected!', (x, y))
                return False
    # Solved
    return True


def is_valid(l):
    for x, i in enumerate(l):
        for y, j in enumerate(i):
            if j != 0:
                for p in range(9):
                    if p != x and j == l[p][y]:
                        # Error
                        print('horizontal issue detected!', (x, y))
                        return False
                    if p != y and j == l[x][p]:
                        # Error
                        print('vertical issue detected!', (x, y))
                        return False
                i_n, j_n = get_box_start_coordinate(x, y)
                for (i, j) in [(i, j) for p in range(i_n, i_n + 3) for q in range(j_n, j_n + 3)
                               if (p, q) != (x, y) and j == l[p][q]]:
                        # Error
                    print('box issue detected!', (x, y))
                    return False
    # Solved
    return True


def get_box_start_coordinate(x, y):
    return 3 * int(math.floor(x/3)), 3 * int(math.floor(y/3))


def get_horizontal(x, y, l):
    return [l[x][i] for i in range(9) if l[x][i] > 0]


def get_vertical(x, y, l):
    return [l[i][y] for i in range(9) if l[i][y] > 0]


def get_box(x, y, l):
    existing = []
    i_n, j_n = get_box_start_coordinate(x, y)
    for (i, j) in [(i, j) for i in range(i_n, i_n + 3) for j in range(j_n, j_n + 3)]:
        existing.append(l[i][j]) if l[i][j] > 0 else None
    return existing


def detect_and_simplify_double_pairs(l, pl):
    for (i, j) in [(i, j) for i in range(9) for j in range(9) if len(pl[i][j]) == 2]:
        temp_pair = pl[i][j]
        for p in (p for p in range(j+1, 9) if len(pl[i][p]) == 2 and len(set(pl[i][p]) & set(temp_pair)) == 2):
            for q in (q for q in range(9) if q != j and q != p):
                pl[i][q] = list(set(pl[i][q]) - set(temp_pair))
                if len(pl[i][q]) == 1:
                    l[i][q] = pl[i][q].pop()
                    return True
        for p in (p for p in range(i+1, 9) if len(pl[p][j]) == 2 and len(set(pl[p][j]) & set(temp_pair)) == 2):
            for q in (q for q in range(9) if q != i and p != q):
                pl[q][j] = list(set(pl[q][j]) - set(temp_pair))
                if len(pl[q][j]) == 1:
                    l[q][j] = pl[q][j].pop()
                    return True
        i_n, j_n = get_box_start_coordinate(i, j)
        for (a, b) in [(a, b) for a in range(i_n, i_n+3) for b in range(j_n, j_n+3)
                       if (a, b) != (i, j) and len(pl[a][b]) == 2 and len(set(pl[a][b]) & set(temp_pair)) == 2]:
            for (c, d) in [(c, d) for c in range(i_n, i_n+3) for d in range(j_n, j_n+3)
                           if (c, d) != (a, b) and (c, d) != (i, j)]:
                pl[c][d] = list(set(pl[c][d]) - set(temp_pair))
                if len(pl[c][d]) == 1:
                    l[c][d] = pl[c][d].pop()
                    return True
    return False


def update_unique_horizontal(x, y, l, pl):
    tl = pl[x][y]
    for i in (i for i in range(9) if i != y):
        tl = list(set(tl) - set(pl[x][i]))
    if len(tl) == 1:
        l[x][y] = tl.pop()
        return True
    return False


def update_unique_vertical(x, y, l, pl):
    tl = pl[x][y]
    for i in (i for i in range(9) if i != x):
        tl = list(set(tl) - set(pl[i][y]))
    if len(tl) == 1:
        l[x][y] = tl.pop()
        return True
    return False


def update_unique_box(x, y, l, pl):
    tl = pl[x][y]
    i_n, j_n = get_box_start_coordinate(x, y)
    for (i, j) in [(i, j) for i in range(i_n, i_n+3) for j in range(j_n, j_n+3) if (i, j) != (x, y)]:
        tl = list(set(tl) - set(pl[i][j]))
    if len(tl) == 1:
        l[x][y] = tl.pop()
        return True
    return False


def find_and_place_possibles(l):
    while True:
        pl = populate_possibles(l)
        if pl != False:
            return pl


def populate_possibles(l):
    pl = [[[]for j in i] for i in l]
    for (i, j) in [(i, j) for i in range(9) for j in range(9) if l[i][j] == 0]:
        p = list(set(range(1, 10)) - set(get_horizontal(i, j, l) +
                                         get_vertical(i, j, l) + get_box(i, j, l)))
        if len(p) == 1:
            l[i][j] = p.pop()
            return False
        else:
            pl[i][j] = p
    return pl


def find_and_remove_uniques(l, pl):
    for (i, j) in [(i, j) for i in range(9) for j in range(9) if l[i][j] == 0]:
        if update_unique_horizontal(i, j, l, pl) == True:
            return True
        if update_unique_vertical(i, j, l, pl) == True:
            return True
        if update_unique_box(i, j, l, pl) == True:
            return True
    return False


def try_with_possibilities(l):
    while True:
        improv = False
        pl = find_and_place_possibles(l)
        if detect_and_simplify_double_pairs(
                l, pl) == True:
            continue
        if find_and_remove_uniques(
                l, pl) == True:
            continue
        if improv == False:
            break
    return pl


def get_first_conflict(pl):
    for (x, y) in [(x, y) for x, i in enumerate(pl) for y, j in enumerate(i) if len(j) > 0]:
        return (x, y)


def get_deep_copy(l):
    new_list = [i[:] for i in l]
    return new_list


def run_assumption(l, pl):
    try:
        c = get_first_conflict(pl)
        fl = pl[c[0]
                ][c[1]]
        # print('Assumption Index : ', c)
        # print('Assumption List: ',  fl)
    except:
        return False
    for i in fl:
        new_list = get_deep_copy(l)
        new_list[c[0]][c[1]] = i
        new_pl = try_with_possibilities(new_list)
        is_done = is_solved(new_list)
        if is_done == True:
            l = new_list
            return new_list
        else:
            new_list = run_assumption(new_list, new_pl)
            if new_list != False and is_solved(new_list) == True:
                return new_list
    return False


if __name__ == "__main__":
    l = [
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 8, 0, 0, 0, 0, 4, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 6, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [2, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 2, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0]
    ]
    # This puzzle copied from Hacked rank test case
    if is_valid(l) == False:
        print("Sorry! Invalid.")
        sys.exit()
    pl = try_with_possibilities(l)
    is_done = is_solved(l)
    if is_done == True:
        for i in l:
            print(i)
        print("Solved!!!")
        sys.exit()

    print("Unable to solve by traditional ways")
    print("Starting assumption based solving")
    new_list = run_assumption(l, pl)
    if new_list != False:
        is_done = is_solved(new_list)
        print('is solved ? - ', is_done)
        for i in new_list:
            print(i)
        if is_done == True:
            print("Solved!!! with assumptions.")
        sys.exit()
    print(l)
    print("Sorry! No Solution. Need to fix the valid function :(")
    sys.exit()

What evaluates to True/False in R?

If you think about it, comparing numbers to logical statements doesn't make much sense. However, since 0 is often associated with "Off" or "False" and 1 with "On" or "True", R has decided to allow 1 == TRUE and 0 == FALSE to both be true. Any other numeric-to-boolean comparison should yield false, unless it's something like 3 - 2 == TRUE.

Font.createFont(..) set color and size (java.awt.Font)

Well, once you have your font, you can invoke deriveFont. For example,

helvetica = helvetica.deriveFont(Font.BOLD, 12f);

Changes the font's style to bold and its size to 12 points.

How to initialize all members of an array to the same value?

int i;
for (i = 0; i < ARRAY_SIZE; ++i)
{
  myArray[i] = VALUE;
}

I think this is better than

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5...

incase the size of the array changes.

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

In my case I had a console application, I just unchecked Prefer 32-bit on Build projet properties tab and then I add this to my app.config:

<runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="2.112.1.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

How do I hide anchor text without hiding the anchor?

Try

 a{
    line-height: 0; 
    font-size: 0;
    color: transparent; 
 }


The color: transparent; covers an issue with Webkit browsers still displaying 1px of the text.

How do I do a bulk insert in mySQL using node.js

I ran into this today (mysql 2.16.0) and thought I'd share my solution:

const items = [
    {name: 'alpha', description: 'describes alpha', value: 1},
    ...
];

db.query(
    'INSERT INTO my_table (name, description, value) VALUES ?',
    [items.map(item => [item.name, item.description, item.value])],
    (error, results) => {...}
);

TOMCAT - HTTP Status 404

To get your program to run, please put jsp files under web-content and not under WEB-INF because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:

http://localhost:8080/YourProject/yourfile.jsp

then your problem will be solved.

Label axes on Seaborn Barplot

Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', 
              data = fake, 
              color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

AS per point 1, your PEAR path is c:\xampplite\php\pear\

However, your path is pointing to \xampplite\php\pear\PEAR

Putting the two one above the other you can clearly see one is too long:

c:\xampplite\php\pear\

\xampplite\php\pear\PEAR

Your include path is set to go one PEAR too deep into the pear tree. The PEAR subfolder of the pear folder includes the PEAR component. You need to adjust your include path up one level.

(you don't need the c: by the way, your path is fine as is, just too deep)

Cmake is not able to find Python-libraries

You can fix the errors by appending to the cmake command the -DPYTHON_LIBRARY and -DPYTHON_INCLUDE_DIR flags filled with the respective folders.

Thus, the trick is to fill those parameters with the returned information from the python interpreter, which is the most reliable. This may work independently of your python location/version (also for Anaconda users):

$ cmake .. \
-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())")  \
-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))")

If the version of python that you want to link against cmake is Python3.X and the default python symlink points to Python2.X, python3 -c ... can be used instead of python -c ....

In case that the error persists, you may need to update the cmake to a higher version as stated by @pdpcosta and repeat the process again.

bash shell nested for loop

One one line (semi-colons necessary):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).

PHP Warning: Division by zero

A lot of the answers here do not work for (string)"0.00".

Try this:

if (isset($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

Or even more strict:

if (isset($_POST['num1']) && is_numeric($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

X close button only using css

Try This Cross In CSS

_x000D_
_x000D_
.close {_x000D_
  position: absolute;_x000D_
  right: 32px;_x000D_
  top: 32px;_x000D_
  width: 32px;_x000D_
  height: 32px;_x000D_
  opacity: 0.3;_x000D_
}_x000D_
.close:hover {_x000D_
  opacity: 1;_x000D_
}_x000D_
.close:before, .close:after {_x000D_
  position: absolute;_x000D_
  left: 15px;_x000D_
  content: ' ';_x000D_
  height: 33px;_x000D_
  width: 2px;_x000D_
  background-color: #333;_x000D_
}_x000D_
.close:before {_x000D_
  transform: rotate(45deg);_x000D_
}_x000D_
.close:after {_x000D_
  transform: rotate(-45deg);_x000D_
}
_x000D_
<a href="#" class="close">
_x000D_
_x000D_
_x000D_

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

Best way to make WPF ListView/GridView sort on column-header clicking?

After search alot, finaly i found simple here https://www.wpf-tutorial.com/listview-control/listview-how-to-column-sorting/

private GridViewColumnHeader listViewSortCol = null;
private SortAdorner listViewSortAdorner = null;
private void GridViewColumnHeader_Click(object sender, RoutedEventArgs e)
{
  GridViewColumnHeader column = (sender as GridViewColumnHeader);
  string sortBy = column.Tag.ToString();
  if (listViewSortCol != null)
  {
    AdornerLayer.GetAdornerLayer(listViewSortCol).Remove(listViewSortAdorner);
    yourListView.Items.SortDescriptions.Clear();
  }

  ListSortDirection newDir = ListSortDirection.Ascending;
  if (listViewSortCol == column && listViewSortAdorner.Direction == newDir)
    newDir = ListSortDirection.Descending;

  listViewSortCol = column;
  listViewSortAdorner = new SortAdorner(listViewSortCol, newDir);
  AdornerLayer.GetAdornerLayer(listViewSortCol).Add(listViewSortAdorner);
  yourListView.Items.SortDescriptions.Add(new SortDescription(sortBy, newDir));
}

Class:

public class SortAdorner : Adorner
{
    private static Geometry ascGeometry =
        Geometry.Parse("M 0 4 L 3.5 0 L 7 4 Z");

    private static Geometry descGeometry =
        Geometry.Parse("M 0 0 L 3.5 4 L 7 0 Z");

    public ListSortDirection Direction { get; private set; }

    public SortAdorner(UIElement element, ListSortDirection dir)
        : base(element)
    {
        this.Direction = dir;
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);

        if(AdornedElement.RenderSize.Width < 20)
            return;

        TranslateTransform transform = new TranslateTransform
            (
                AdornedElement.RenderSize.Width - 15,
                (AdornedElement.RenderSize.Height - 5) / 2
            );
        drawingContext.PushTransform(transform);

        Geometry geometry = ascGeometry;
        if(this.Direction == ListSortDirection.Descending)
            geometry = descGeometry;
        drawingContext.DrawGeometry(Brushes.Black, null, geometry);

        drawingContext.Pop();
    }
}

Xaml

<GridViewColumn Width="250">
  <GridViewColumn.Header>
    <GridViewColumnHeader Tag="Name" Click="GridViewColumnHeader_Click">Name</GridViewColumnHeader>
  </GridViewColumn.Header>
  <GridViewColumn.CellTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding Name}" ToolTip="{Binding Name}"/>
    </DataTemplate>
  </GridViewColumn.CellTemplate>
</GridViewColumn>

Center the content inside a column in Bootstrap 4

_x000D_
_x000D_
.row>.col, .row>[class^=col-] {_x000D_
    padding-top: .75rem;_x000D_
    padding-bottom: .75rem;_x000D_
    background-color: rgba(86,61,124,.15);_x000D_
    border: 1px solid rgba(86,61,124,.2);_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
  <div class="row justify-content-md-center">_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 2_x000D_
    </div>_x000D_
    <div class="col col-lg-2">_x000D_
      3 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

Convert int (number) to string with leading zeros? (4 digits)

Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.

string text = no.ToString("0000");

How to install and run Typescript locally in npm?

As of npm 5.2.0, once you've installed locally via

npm i typescript --save-dev

...you no longer need an entry in the scripts section of package.json -- you can now run the compiler with npx:

npx tsc

Now you don't have to update your package.json file every time you want to compile with different arguments.

How to get elements with multiple classes

querySelectorAll with standard class selectors also works for this.

document.querySelectorAll('.class1.class2');

How to send string from one activity to another?

 Intent intent = new Intent(activity1.this, activity2.class);
 intent.putExtra("message", message);
 startActivity(intent);

In activity2, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :

  Bundle bundle = getIntent().getExtras();
  String message = bundle.getString("message");

How to extract hours and minutes from a datetime.datetime object?

Don't know how you want to format it, but you can do:

print("Created at %s:%s" % (t1.hour, t1.minute))

for example.

Apache Spark: The number of cores vs. the number of executors

Short answer: I think tgbaggio is right. You hit HDFS throughput limits on your executors.

I think the answer here may be a little simpler than some of the recommendations here.

The clue for me is in the cluster network graph. For run 1 the utilization is steady at ~50 M bytes/s. For run 3 the steady utilization is doubled, around 100 M bytes/s.

From the cloudera blog post shared by DzOrd, you can see this important quote:

I’ve noticed that the HDFS client has trouble with tons of concurrent threads. A rough guess is that at most five tasks per executor can achieve full write throughput, so it’s good to keep the number of cores per executor below that number.

So, let's do a few calculations see what performance we expect if that is true.


Run 1: 19 GB, 7 cores, 3 executors

  • 3 executors x 7 threads = 21 threads
  • with 7 cores per executor, we expect limited IO to HDFS (maxes out at ~5 cores)
  • effective throughput ~= 3 executors x 5 threads = 15 threads

Run 3: 4 GB, 2 cores, 12 executors

  • 2 executors x 12 threads = 24 threads
  • 2 cores per executor, so hdfs throughput is ok
  • effective throughput ~= 12 executors x 2 threads = 24 threads

If the job is 100% limited by concurrency (the number of threads). We would expect runtime to be perfectly inversely correlated with the number of threads.

ratio_num_threads = nthread_job1 / nthread_job3 = 15/24 = 0.625
inv_ratio_runtime = 1/(duration_job1 / duration_job3) = 1/(50/31) = 31/50 = 0.62

So ratio_num_threads ~= inv_ratio_runtime, and it looks like we are network limited.

This same effect explains the difference between Run 1 and Run 2.


Run 2: 19 GB, 4 cores, 3 executors

  • 3 executors x 4 threads = 12 threads
  • with 4 cores per executor, ok IO to HDFS
  • effective throughput ~= 3 executors x 4 threads = 12 threads

Comparing the number of effective threads and the runtime:

ratio_num_threads = nthread_job2 / nthread_job1 = 12/15 = 0.8
inv_ratio_runtime = 1/(duration_job2 / duration_job1) = 1/(55/50) = 50/55 = 0.91

It's not as perfect as the last comparison, but we still see a similar drop in performance when we lose threads.

Now for the last bit: why is it the case that we get better performance with more threads, esp. more threads than the number of CPUs?

A good explanation of the difference between parallelism (what we get by dividing up data onto multiple CPUs) and concurrency (what we get when we use multiple threads to do work on a single CPU) is provided in this great post by Rob Pike: Concurrency is not parallelism.

The short explanation is that if a Spark job is interacting with a file system or network the CPU spends a lot of time waiting on communication with those interfaces and not spending a lot of time actually "doing work". By giving those CPUs more than 1 task to work on at a time, they are spending less time waiting and more time working, and you see better performance.

Set default value of an integer column SQLite

Use the SQLite keyword default

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, "
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER DEFAULT 0);");

This link is useful: http://www.sqlite.org/lang_createtable.html

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

What is the difference between background and background-color

background will supercede all previous background-color, background-image, etc. specifications. It's basically a shorthand, but a reset as well.

I will sometimes use it to overwrite previous background specifications in template customizations, where I would want the following:

background: white url(images/image1.jpg) top left repeat;

to be the following:

background: black;

So, all parameters (background-image, background-position, background-repeat) will reset to their default values.

How to prevent a dialog from closing when a button is clicked

Kotlin

val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_userinput, null)
        val dialogBuilder = MaterialAlertDialogBuilder(requireContext(), R.style.AlertDialogTheme)
   
        dialogBuilder.setView(dialogView)
        dialogBuilder.setCancelable(false)
        dialogBuilder.setPositiveButton("send",null)
        dialogBuilder.setNegativeButton("cancel") { dialog,_ ->
        dialog.dismiss()
        }


        val alertDialog = dialogBuilder.create()
        alertDialog.show()

        val positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
        positiveButton.setOnClickListener {
            val myInputText = dialogView.etxt_userinput.text.toString().trim()
            if(myInputText.isNotEmpty()){
             //Do something
            }else{
                //Prompt error
                dialogView.etxt_userinput.error = "Please fill this"
            }
        }

We just create an AlertDialog with the dialogBuilder and then just set the positive button as we want

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

I had the same problem. I tried these steps:

  1. Closed the Visual Studio 2017
  2. Removed the [solutionPath].vs\config\applicationhost.config
  3. Reopened the solution and clicked on [Create Virtual Directory]
  4. Tried to run => ERR_CONNECTION_REFUSED
  5. FAILED

Another try:

  1. Closed the Visual Studio 2017
  2. Removed the [solutionPath].vs\config\applicationhost.config
  3. Removed the .\Documents\IISExpress\config\applicationhost.config
  4. Reopened the solution and clicked on [Create Virtual Directory]
  5. Tried to run => ERR_CONNECTION_REFUSED
  6. FAILED

Another try:

  1. Closed the Visual Studio 2017
  2. Removed the [solutionPath].vs\config\applicationhost.config
  3. Removed the .\Documents\IISExpress\config\applicationhost.config
  4. Added 127.0.0.1 localhost to C:\Windows\System32\drivers\etc\hosts
  5. Reopened the solution and clicked on [Create Virtual Directory]
  6. Tried to run => ERR_CONNECTION_REFUSED
  7. FAILED

WHAT IT WORKED:

  1. Close the Visual Studio 2017
  2. Remove the [solutionPath].vs\config\applicationhost.config
  3. Start "Manage computer certificates" and Locate certificate "localhost" in Personal-> Certificates enter image description here
  4. Remove that certificate (do this on your own risk)
  5. Start Control Panel\All Control Panel Items\Programs and Features
  6. Locate "IIS 10.0 Express" (or your own IIS Express version)
  7. Click on "Repair" enter image description here
  8. Reopen the solution and clicked on [Create Virtual Directory]
  9. Start the web-project.
  10. You will get this question:enter image description here. Click "Yes"
  11. You will get this Question: enter image description here. Click "Yes"
  12. Now it works.

Why can't I declare static methods in an interface?

With Java 8, interfaces can now have static methods.

For example, Comparator has a static naturalOrder() method.

The requirement that interfaces cannot have implementations has also been relaxed. Interfaces can now declare "default" method implementations, which are like normal implementations with one exception: if you inherit both a default implementation from an interface and a normal implementation from a superclass, the superclass's implementation will always take priority.

SQL Server Script to create a new user

If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name

Declare @userName as varchar(50); 
Declare @defaultDataBaseName as varchar(50);
Declare @LoginCreationScript as varchar(max);
Declare @UserCreationScript as varchar(max);
Declare @TempUserCreationScript as varchar(max);
set @defaultDataBaseName = 'data1';
set @userName = 'domain\userName';
set @LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS 
WITH DEFAULT_DATABASE ={dataBaseName}'

set @UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set @LoginCreationScript=Replace(Replace(@LoginCreationScript, '{userName}', @userName), '{dataBaseName}', @defaultDataBaseName)
set @UserCreationScript =Replace(@UserCreationScript, '{userName}', @userName)
Execute(@LoginCreationScript)

/*User creation and role assignment*/
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', @defaultDataBaseName)
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db2')
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db3')
Execute(@TempUserCreationScript)

AngularJS - Trigger when radio button is selected

Another approach is using Object.defineProperty to set valueas a getter setter property in the controller scope, then each change on the value property will trigger a function specified in the setter:

The HTML file:

<input type="radio" ng-model="value" value="one"/>
<input type="radio" ng-model="value" value="two"/>
<input type="radio" ng-model="value" value="three"/>

The javascript file:

var _value = null;
Object.defineProperty($scope, 'value', {
  get: function () {
    return _value;
  },         
  set: function (value) {
    _value = value;
    someFunction();
  }
});

see this plunker for the implementation

What does int argc, char *argv[] mean?

Both of

int main(int argc, char *argv[]);
int main();

are legal definitions of the entry point for a C or C++ program. Stroustrup: C++ Style and Technique FAQ details some of the variations that are possible or legal for your main function.

What is the difference between HTML tags <div> and <span>?

<div> is a block-level element and <span> is an inline element.

If you wanted to do something with some inline text, <span> is the way to go since it will not introduce line breaks that a <div> would.


As noted by others, there are some semantics implied with each of these, most significantly the fact that a <div> implies a logical division in the document, akin to maybe a section of a document or something, a la:

<div id="Chapter1">
   <p>Lorem ipsum dolor sit amet, <span id="SomeSpecialText1">consectetuer adipiscing</span> elit. Duis congue vehicula purus.</p>
   <p>Nam <span id="SomeSpecialText2">eget magna nec</span> sapien fringilla euismod. Donec hendrerit.</p> 
</div>

java.io.FileNotFoundException: (Access is denied)

Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.

Convert boolean to int in Java

That depends on the situation. Often the most simple approach is the best because it is easy to understand:

if (something) {
    otherThing = 1;
} else {
    otherThing = 0;
}

or

int otherThing = something ? 1 : 0;

But sometimes it useful to use an Enum instead of a boolean flag. Let imagine there are synchronous and asynchronous processes:

Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());

In Java, enum can have additional attributes and methods:

public enum Process {

    SYNCHRONOUS (0),
    ASYNCHRONOUS (1);

    private int code;
    private Process (int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

How to send email by using javascript or jquery

You can send Email by Jquery just follow these steps 

include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :

$( document ).ready(function() {
 Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});

how can I login anonymously with ftp (/usr/bin/ftp)?

As others point out, the user name is usually anonymous, and the password is usually your e-mail address, but this is not universally true, and has been found not to work for certain anonymous FTP sites. For example, at least some cPanel sites seem to deviate from the norm, and if given the traditional user name without domain, one of various errors may result:

If the server uses Pure-FTP as the FTP server:

421 Can't change directory to /var/ftp/ error message.

If the server uses ProFTP as the FTP server:

530 Login Authentication Failed error message.

When one of the aforementioned errors occurs when attempting anonymous access, try including a domain with the username. For example, where example.com is the domain used in your e-mail address:

User name: [email protected]

In the specific case of a cPanel site, the password value is unimportant, and may be left blank, but there is no harm in providing a "traditional" anonymous password formatted as an e-mail address.

For reference, this answer is based on content found on a documentation.cpanel.net Anonymous FTP page. At the time of this writing, it stated:

When users log in to FTP anonymously, they must format usernames as [email protected], where example.com represents the user's domain name. This requirement directs your server to the correct public_ftp directory.

Expression ___ has changed after it was checked

I couldnt comment on @Biranchi s post since I dont have enough reputation, but it fixed the problem for me.

One thing to note! If adding changeDetection: ChangeDetectionStrategy.OnPush on the component didn't work, and its a child component (dumb component) try adding it to the parent also.

This fixed the bug, but I wonder what are the side effects of this.

Add another class to a div

You can append a class to the className member, with a leading space.

document.getElementById('hello').className += ' new-class';

See https://developer.mozilla.org/En/DOM/Element.className

How to use componentWillMount() in React Hooks?

This is the way how I simulate constructor in functional components using the useRef hook:

function Component(props) {
    const willMount = useRef(true);
    if (willMount.current) {
        console.log('This runs only once before rendering the component.');
        willMount.current = false;        
    }

    return (<h1>Meow world!</h1>);
}

Here is the lifecycle example:

function RenderLog(props) {
    console.log('Render log: ' + props.children);
    return (<>{props.children}</>);
}

function Component(props) {

    console.log('Body');
    const [count, setCount] = useState(0);
    const willMount = useRef(true);

    if (willMount.current) {
        console.log('First time load (it runs only once)');
        setCount(2);
        willMount.current = false;
    } else {
        console.log('Repeated load');
    }

    useEffect(() => {
        console.log('Component did mount (it runs only once)');
        return () => console.log('Component will unmount');
    }, []);

    useEffect(() => {
        console.log('Component did update');
    });

    useEffect(() => {
        console.log('Component will receive props');
    }, [count]);


    return (
        <>
        <h1>{count}</h1>
        <RenderLog>{count}</RenderLog>
        </>
    );
}
[Log] Body
[Log] First time load (it runs only once)
[Log] Body
[Log] Repeated load
[Log] Render log: 2
[Log] Component did mount (it runs only once)
[Log] Component did update
[Log] Component will receive props

Of course Class components don't have Body steps, it's not possible to make 1:1 simulation due to different concepts of functions and classes.

Maven error :Perhaps you are running on a JRE rather than a JDK?

This is because of running jre rather than jdk, to install jdk follow below steps

Installing java 8 in amazon linux/redhat

--> yum search java | grep openjdk

--> yum install java-1.8.0-openjdk-headless.x86_64

--> yum install java-1.8.0-openjdk-devel.x86_64

--> update-alternatives --config java #pick java 1.8 and press 1

--> update-alternatives --config javac #pick java 1.8 and press 2

Thank You

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

If you have persian language and must show the numbers to users in persian language:

static public string ToFaString         (this string value)
        {
            // 1728 , 1584
            string result = "";
            if (value != null)
            {
                char[] resChar = value.ToCharArray();
                for (int i = 0; i < resChar.Length; i++)
                {
                    if (resChar[i] >= '0' && resChar[i] <= '9')
                        result += (char)(resChar[i] + 1728);
                    else
                        result += resChar[i];
                }
            }
            return result;
        }

How can I position my jQuery dialog to center?

Try this for older versions and somebody who don't want to use position:

$("#dialog-div-id").dialog({position: ['center', 'top'],....

How to convert a char array to a string?

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long

Javascript Drag and drop for touch devices

For anyone looking to use this and keep the 'click' functionality (as John Landheer mentions in his comment), you can do it with just a couple of modifications:

Add a couple of globals:

var clickms = 100;
var lastTouchDown = -1;

Then modify the switch statement from the original to this:

var d = new Date();
switch(event.type)
{
    case "touchstart": type = "mousedown"; lastTouchDown = d.getTime(); break;
    case "touchmove": type="mousemove"; lastTouchDown = -1; break;        
    case "touchend": if(lastTouchDown > -1 && (d.getTime() - lastTouchDown) < clickms){lastTouchDown = -1; type="click"; break;} type="mouseup"; break;
    default: return;
}

You may want to adjust 'clickms' to your tastes. Basically it's just watching for a 'touchstart' followed quickly by a 'touchend' to simulate a click.

Fatal error: Call to undefined function mb_strlen()

On Centos, RedHat, Fedora and other yum-my systems it is much simpler than the PHP manual suggests:

yum install php-mbstring
service httpd restart

What is the use of join() in Python threading?

With join - interpreter will wait until your process get completed or terminated

>>> from threading import Thread
>>> import time
>>> def sam():
...   print 'started'
...   time.sleep(10)
...   print 'waiting for 10sec'
... 
>>> t = Thread(target=sam)
>>> t.start()
started

>>> t.join() # with join interpreter will wait until your process get completed or terminated
done?   # this line printed after thread execution stopped i.e after 10sec
waiting for 10sec
>>> done?

without join - interpreter wont wait until process get terminated,

>>> t = Thread(target=sam)
>>> t.start()
started
>>> print 'yes done' #without join interpreter wont wait until process get terminated
yes done
>>> waiting for 10sec

What is Domain Driven Design?

As in TDD & BDD you/ team focus the most on test and behavior of the system than code implementation.

Similar way when system analyst, product owner, development team and ofcourse the code - entities/ classes, variables, functions, user interfaces processes communicate using the same language, its called Domain Driven Design

DDD is a thought process. When modeling a design of software you need to keep business domain/process in the center of attention rather than data structures, data flows, technology, internal and external dependencies.

There are many approaches to model systerm using DDD

  • event sourcing (using events as a single source of truth)
  • relational databases
  • graph databases
  • using functional languages

Domain object:

In very naive words, an object which

  • has name based on business process/flow
  • has complete control on its internal state i.e exposes methods to manipulate state.
  • always fulfill all business invariants/business rules in context of its use.
  • follows single responsibility principle

Finding the number of days between two dates

I have tried almost all of the ways as in answers given. But neither DateTime nor date_create gave me correct answers in all my test cases. Specially test with February & March dates or December & January dates.

So, I came-up with mixed solution.

public static function getMonthsDaysDiff($fromDate, $toDate, $includingEnding = false){
    $d1=new DateTime($fromDate);
    $d2=new DateTime($toDate);
    if($includingEnding === true){
        $d2 = $d2->modify('+1 day');
    }
    $diff = $d2->diff($d1);
    $months = (($diff->format('%y') * 12) + $diff->format('%m'));

    $lastSameDate = $d1->modify("+$months month");
    $days = date_diff(
        date_create($d2->format('Y-m-d')),
        date_create($lastSameDate->format('Y-m-d'))
    )->format('%a');

    $return = ['months' => $months,
        'days' => $days];
}

I know, performance wise this quite expensive. And you can extend it to get Years as well.

Sql Server : How to use an aggregate function like MAX in a WHERE clause

But its still giving an error message in Query Builder. I am using SqlServerCe 2008.

SELECT         Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount, 
                     Order_Details.TotalPrice
FROM           Order_Products INNER JOIN
                     Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
                     Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING        (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))

I replaced WHERE with HAVING as said by @powerlord. But still showing an error.

Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]

How do I combine two lists into a dictionary in Python?

I don't know about best (simplest? fastest? most readable?), but one way would be:

dict(zip([1, 2, 3, 4], [a, b, c, d]))

SQL get the last date time record

SELECT * FROM table
WHERE Dates IN (SELECT max(Dates) FROM table);

Spring Boot - Handle to Hibernate SessionFactory

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

where entityManagerFactory is an JPA EntityManagerFactory.

ResultSet exception - before start of result set

Basically you are positioning the cursor before the first row and then requesting data. You need to move the cursor to the first row.

 result.next();
 String foundType = result.getString(1);

It is common to do this in an if statement or loop.

if(result.next()){
   foundType = result.getString(1);
}

How would you count occurrences of a string (actually a char) within a string?

Regex.Matches(input,  Regex.Escape("stringToMatch")).Count