Programs & Examples On #Data objects

Reverse colormap in matplotlib

The standard colormaps also all have reversed versions. They have the same names with _r tacked on to the end. (Documentation here.)

Javascript call() & apply() vs bind()?

JavaScript Call()

const person = {
    name: "Lokamn",
    dob: 12,
    print: function (value,value2) {
        console.log(this.dob+value+value2)
    }
}
const anotherPerson= {
     name: "Pappu",
     dob: 12,
}
 person.print.call(anotherPerson,1,2)

JavaScript apply()

    name: "Lokamn",
    dob: 12,
    print: function (value,value2) {
        console.log(this.dob+value+value2)
    }
}
const anotherPerson= {
     name: "Pappu",
     dob: 12,
}
 person.print.apply(anotherPerson,[1,2])

**call and apply function are difference call take separate argument but apply take array like:[1,2,3] **

JavaScript bind()

    name: "Lokamn",
    dob: 12,
    anotherPerson: {
        name: "Pappu",
        dob: 12,
        print2: function () {
            console.log(this)
        }
    }
}

var bindFunction = person.anotherPerson.print2.bind(person)
 bindFunction()

How do you change the colour of each category within a highcharts column chart?

This worked for me. Its tedious to set all the colour options for a series, especially if it's dynamic

plotOptions: {
  column: {
   colorByPoint: true
  }
}

javascript filter array of objects

_x000D_
_x000D_
var nameList = [_x000D_
{name:'x', age:20, email:'[email protected]'},_x000D_
{name:'y', age:60, email:'[email protected]'},_x000D_
{name:'Joe', age:22, email:'[email protected]'},_x000D_
{name:'Abc', age:40, email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var filteredValue = nameList.filter(function (item) {_x000D_
      return item.name == "Joe" && item.age < 30;_x000D_
});_x000D_
_x000D_
//To See Output Result as Array_x000D_
console.log(JSON.stringify(filteredValue));
_x000D_
_x000D_
_x000D_

You can simply use javascript :)

How to get the first and last date of the current year?

The best way to get First Date and Last Date of a year Is

SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '01' + '-' + '01' AS DATE) FIRST_DATE
SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '12' + '-' + '31' AS DATE) LAST_DATE

How to get diff between all files inside 2 folders that are on the web?

You urls are not in the same repository, so you can't do it with the svn diff command.

svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'

Another way you could do it, is export each repos using svn export, and then use the diff command to compare the 2 directories you exported.

// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2

// Compare exported directories
diff repos1 repos2 > file.diff

How to save a list to a file and read it as a list type?

If you want you can use numpy's save function to save the list as file. Say you have two lists

sampleList1=['z','x','a','b']
sampleList2=[[1,2],[4,5]]

here's the function to save the list as file, remember you need to keep the extension .npy

def saveList(myList,filename):
    # the filename should mention the extension 'npy'
    np.save(filename,myList)
    print("Saved successfully!")

and here's the function to load the file into a list

def loadList(filename):
    # the filename should mention the extension 'npy'
    tempNumpyArray=np.load(filename)
    return tempNumpyArray.tolist()

a working example

>>> saveList(sampleList1,'sampleList1.npy')
>>> Saved successfully!
>>> saveList(sampleList2,'sampleList2.npy')
>>> Saved successfully!

# loading the list now 
>>> loadedList1=loadList('sampleList1.npy')
>>> loadedList2=loadList('sampleList2.npy')

>>> loadedList1==sampleList1
>>> True

>>> print(loadedList1,sampleList1)

>>> ['z', 'x', 'a', 'b'] ['z', 'x', 'a', 'b']

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

\df <schema>.*

in psql gives the necessary information.

To see the query that's used internally connect to a database with psql and supply an extra "-E" (or "--echo-hidden") option and then execute the above command.

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

How to show loading spinner in jQuery?

As well as setting global defaults for ajax events, you can set behaviour for specific elements. Perhaps just changing their class would be enough?

$('#myForm').ajaxSend( function() {
    $(this).addClass('loading');
});
$('#myForm').ajaxComplete( function(){
    $(this).removeClass('loading');
});

Example CSS, to hide #myForm with a spinner:

.loading {
    display: block;
    background: url(spinner.gif) no-repeat center middle;
    width: 124px;
    height: 124px;
    margin: 0 auto;
}
/* Hide all the children of the 'loading' element */
.loading * {
    display: none;  
}

How to pass data from 2nd activity to 1st activity when pressed back? - android

Activity1 should start Activity2 with startActivityForResult().

Activity2 should use setResult() to send data back to Activity1.

In Activity2,

@Override
public void onBackPressed() {
    String data = mEditText.getText();
    Intent intent = new Intent();
    intent.putExtra("MyData", data);
    setResult(resultcode, intent);
}

In Activity1,

onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String myStr=data.getStringExtra("MyData");
            mTextView.setText(myStr);
        }
    }
}

Select distinct values from a list using LINQ in C#

You can use GroupBy with anonymous type, and then get First:

list.GroupBy(e => new { 
                          empLoc = e.empLoc, 
                          empPL = e.empPL, 
                          empShift = e.empShift 
                       })

    .Select(g => g.First());

Change the current directory from a Bash script

This is my current way of doing it for bash (tested on Debian). Maybe there's a better way:

Don't do it with exec bash, for example like this:

#!/bin/bash
cd $1
exec bash

because while it appears to work, after you run it and your script finishes, yes you'll be in the correct directory, but you'll be in it in a subshell, which you can confirm by pressing Ctrl+D afterwards, and you'll see it exits the subshell, putting you back in your original directory.

This is usually not a state you want a script user to be left in after the script they run returns, because it's non-obvious that they're in a subshell and now they basically have two shells open when they thought they only had one. They might continue using this subshell and not realize it, and it could have unintended consequences.

If you really want the script to exit and leave open a subshell in the new directory, it's better if you change the PS1 variable so the script user has a visual indicator that they still have a subshell open.

Here's an example I came up with. It is two files, an outer.sh which you call directly, and an inner.sh which is sourced inside the outer.sh script. The outer script sets two variables, then sources the inner script, and afterwards it echoes the two variables (the second one has just been modified by the inner script). Afterwards it makes a temp copy of the current user's ~/.bashrc file, adds an override for the PS1 variable in it, as well as a cleanup routine, and finally it runs exec bash --rcfile pointing at the .bashrc.tmp file to initialize bash with a modified environment, including the modified prompt and the cleanup routine.

After outer.sh exits, you'll be left inside a subshell in the desired directory (in this case testdir/ which was entered into by the inner.sh script) with a visual indicator making it clear to you, and if you exit out of the subshell, the .bashrc.tmp file will be deleted by the cleanup routine, and you'll be back in the directory you started in.

Maybe there's a smarter way to do it, but that's the best way I could figure out in about 40 minutes of experimenting:

file 1: outer.sh

#!/bin/bash

var1="hello"
var2="world"

source inner.sh

echo $var1
echo $var2

cp ~/.bashrc .bashrc.tmp

echo 'export PS1="(subshell) $PS1"' >> .bashrc.tmp

cat <<EOS >> .bashrc.tmp
cleanup() {
    echo "cleaning up..."
    rm .bashrc.tmp
}

trap 'cleanup' 0
EOS

exec bash --rcfile .bashrc.tmp

file 2: inner.sh

cd testdir
var2="bird"

then run:

$ mkdir testdir
$ chmod 755 outer.sh

$ ./outer.sh

it should output:

hello
bird

and then drop you into your subshell using exec bash, but with a modified prompt which makes that obvious, something like:

(subshell) user@computername:~/testdir$

and if you Ctrl-D out of the subshell, it should clean up by deleting a temporary .bashrc.tmp file in the testdir/ directory

I wonder if there's a better way than having to copy the .bashrc file like that though to change the PS1 var properly in the subshell...

Can I change the headers of the HTTP request sent by the browser?

I don't think it's possible to do it in the way you are trying to do it.

Indication of the accepted data format is usually done through adding the extension to the resource name. So, if you have resource like

/resources/resource

and GET /resources/resource returns its HTML representation, to indicate that you want its XML representation instead, you can use following pattern:

/resources/resource.xml

You have to do the accepted content type determination magic on the server side, then.

Or use Javascript as James suggests.

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Shell - How to find directory of some command?

An alternative to type -a is command -V

Since most of the times I am interested in the first result only, I also pipe from head. This way the screen will not flood with code in case of a bash function.

command -V lshw | head -n1

Python JSON serialize a Decimal object

Simplejson 2.1 and higher has native support for Decimal type:

>>> json.dumps(Decimal('3.9'), use_decimal=True)
'3.9'

Note that use_decimal is True by default:

def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
    allow_nan=True, cls=None, indent=None, separators=None,
    encoding='utf-8', default=None, use_decimal=True,
    namedtuple_as_object=True, tuple_as_array=True,
    bigint_as_string=False, sort_keys=False, item_sort_key=None,
    for_json=False, ignore_nan=False, **kw):

So:

>>> json.dumps(Decimal('3.9'))
'3.9'

Hopefully, this feature will be included in standard library.

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

If you want to filter rows by a certain number of columns with null values, you may use this:

df.iloc[df[(df.isnull().sum(axis=1) >= qty_of_nuls)].index]

So, here is the example:

Your dataframe:

>>> df = pd.DataFrame([range(4), [0, np.NaN, 0, np.NaN], [0, 0, np.NaN, 0], range(4), [np.NaN, 0, np.NaN, np.NaN]])
>>> df
     0    1    2    3
0  0.0  1.0  2.0  3.0
1  0.0  NaN  0.0  NaN
2  0.0  0.0  NaN  0.0
3  0.0  1.0  2.0  3.0
4  NaN  0.0  NaN  NaN

If you want to select the rows that have two or more columns with null value, you run the following:

>>> qty_of_nuls = 2
>>> df.iloc[df[(df.isnull().sum(axis=1) >=qty_of_nuls)].index]
     0    1    2   3
1  0.0  NaN  0.0 NaN
4  NaN  0.0  NaN NaN

Any way to limit border length?

CSS generated content can solve this for you:

_x000D_
_x000D_
div {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
_x000D_
/* Main div for border to extend to 50% from bottom left corner */_x000D_
_x000D_
div:after {_x000D_
  content: "";_x000D_
  background: black;_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  height: 50%;_x000D_
  width: 1px;_x000D_
}
_x000D_
<div>Lorem Ipsum</div>
_x000D_
_x000D_
_x000D_

(note - the content: ""; declaration is necessary in order for the pseudo-element to render)

Task<> does not contain a definition for 'GetAwaiter'

I had the same issue, I had to remove the async keyword from the method and also remove the await keyword from the calling method to use getawaiter() without any error.

Plot smooth line with PyPlot

See the scipy.interpolate documentation for some examples.

The following example demonstrates its use, for linear and cubic spline interpolation:

>>> from scipy.interpolate import interp1d

>>> x = np.linspace(0, 10, num=11, endpoint=True)
>>> y = np.cos(-x**2/9.0)
>>> f = interp1d(x, y)
>>> f2 = interp1d(x, y, kind='cubic')

>>> xnew = np.linspace(0, 10, num=41, endpoint=True)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
>>> plt.legend(['data', 'linear', 'cubic'], loc='best')
>>> plt.show()

enter image description here

Encrypt and decrypt a String in java

Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.

I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.

If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.

How do I revert to a previous package in Anaconda?

I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.

Passing null arguments to C# methods

Yes. There are two kinds of types in .NET: reference types and value types.

References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.

Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.

The usage is slightly different, though.

// Both of these types mean the same thing, the ? is just C# shorthand.
private void Example(int? arg1, Nullable<int> arg2)
{
    if (arg1.HasValue)
        DoSomething();

    arg1 = null; // Valid.
    arg1 = 123;  // Also valid.

    DoSomethingWithInt(arg1); // NOT valid!
    DoSomethingWithInt(arg1.Value); // Valid.
}

How to check if one DateTime is greater than the other in C#

        if (new DateTime(5000) > new DateTime(1000))
        {
            Console.WriteLine("i win");
        }

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

npm install -g increase-memory-limit

increase-memory-limit

OR

  1. Navigate to %appdata% -> npm folder or C:\Users\{user_name}\AppData\Roaming\npm
  2. Open ng.cmd in your favorite editor
  3. Add --max_old_space_size=8192 to the IF and ELSE block

now ng.cmd file looks like this after the change:

@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe" "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
)

Is there any way I can define a variable in LaTeX?

This works for me: \newcommand{\variablename}{the text}

For eg: \newcommand\m{100}

So when you type " \m\ is my mark " in the source code,

the pdf output displays as :

100 is my mark

Get an object attribute

Use getattr if you have an attribute in string form:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'

Otherwise use the dot .:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> u.name
'John'

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Collectors.toMap() keyMapper -- more succinct expression?

You can use a lambda:

Collectors.toMap(p -> p.getLast(), Function.identity())

or, more concisely, you can use a method reference using :::

Collectors.toMap(Person::getLast, Function.identity())

and instead of Function.identity, you can simply use the equivalent lambda:

Collectors.toMap(Person::getLast, p -> p)

If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.

Java - using System.getProperty("user.dir") to get the home directory

way of getting home directory of current user is

String currentUsersHomeDir = System.getProperty("user.home");

and to append path separator

String otherFolder = currentUsersHomeDir + File.separator + "other";

File.separator

The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

Print very long string completely in pandas dataframe

Another easier way to print the whole string is to call values on the dataframe.

df = pd.DataFrame({'one' : ['one', 'two', 
      'This is very long string very long string very long string veryvery long string']})

print(df.values)

The Output will be

[['one']
 ['two']
 ['This is very long string very long string very long string veryvery long string']]

What's wrong with overridable method calls in constructors?

Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.

class A {

    protected int minWeeklySalary;
    protected int maxWeeklySalary;

    protected static final int MIN = 1000;
    protected static final int MAX = 2000;

    public A() {
        setSalaryRange();
    }

    protected void setSalaryRange() {
        throw new RuntimeException("not implemented");
    }

    public void pr() {
        System.out.println("minWeeklySalary: " + minWeeklySalary);
        System.out.println("maxWeeklySalary: " + maxWeeklySalary);
    }
}

class B extends A {

    private int factor = 1;

    public B(int _factor) {
        this.factor = _factor;
    }

    @Override
    protected void setSalaryRange() {
        this.minWeeklySalary = MIN * this.factor;
        this.maxWeeklySalary = MAX * this.factor;
    }
}

public static void main(String[] args) {
    B b = new B(2);
    b.pr();
}

The result would actually be:

minWeeklySalary: 0

maxWeeklySalary: 0

This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.

I hope that would help someone.

gradient descent using python and numpy

I know this question already have been answer but I have made some update to the GD function :

  ### COST FUNCTION

def cost(theta,X,y):
     ### Evaluate half MSE (Mean square error)
     m = len(y)
     error = np.dot(X,theta) - y
     J = np.sum(error ** 2)/(2*m)
     return J

 cost(theta,X,y)



def GD(X,y,theta,alpha):

    cost_histo = [0]
    theta_histo = [0]

    # an arbitrary gradient, to pass the initial while() check
    delta = [np.repeat(1,len(X))]
    # Initial theta
    old_cost = cost(theta,X,y)

    while (np.max(np.abs(delta)) > 1e-6):
        error = np.dot(X,theta) - y
        delta = np.dot(np.transpose(X),error)/len(y)
        trial_theta = theta - alpha * delta
        trial_cost = cost(trial_theta,X,y)
        while (trial_cost >= old_cost):
            trial_theta = (theta +trial_theta)/2
            trial_cost = cost(trial_theta,X,y)
            cost_histo = cost_histo + trial_cost
            theta_histo = theta_histo +  trial_theta
        old_cost = trial_cost
        theta = trial_theta
    Intercept = theta[0] 
    Slope = theta[1]  
    return [Intercept,Slope]

res = GD(X,y,theta,alpha)

This function reduce the alpha over the iteration making the function too converge faster see Estimating linear regression with Gradient Descent (Steepest Descent) for an example in R. I apply the same logic but in Python.

Check if string contains \n Java

I'd rather trust JDK over System property. Following is a working snippet.

    private boolean checkIfStringContainsNewLineCharacters(String str){
        if(!StringUtils.isEmpty(str)){
            Scanner scanner = new Scanner(str);
            scanner.nextLine();
            boolean hasNextLine =  scanner.hasNextLine();
            scanner.close();
            return hasNextLine;
        }
        return false;
    }

How do you use the ? : (conditional) operator in JavaScript?

Ternary expressions are very useful in JS, especially React. Here's a simplified answer to the many good, detailed ones provided.

condition ? expressionIfTrue : expressionIfFalse

Think of expressionIfTrue as the OG if statement rendering true;
think of expressionIfFalse as the else statement.

Example:

var x = 1;
(x == 1) ? y=x : y=z;

this checked the value of x, the first y=(value) returned if true, the second return after the colon : returned y=(value) if false.

Set object property using reflection

I have just published a Nuget package that allows setting up not only the first level Properties but also nested properties in the given object in any depth.

Here is the package

Sets the value of a property of an object by its path from the root.

The object can be a complex object and the property can be multi level deep nested property or it can be a property directly under the root. ObjectWriter will find the property using the property path parameter and update its value. Property path is the appended names of the properties visited from root to the end node property which we want to set, delimited by the delimiter string parameter.

Usage:

For setting up the properties directly under the object root:

Ie. LineItem class has an int property called ItemId

LineItem lineItem = new LineItem();

ObjectWriter.Set(lineItem, "ItemId", 13, delimiter: null);

For setting up nested property multiple levels below the object root:

Ie. Invite class has a property called State, which has a property called Invite (of Invite type), which has a property called Recipient, which has a property called Id.

To make things even more complex, the State property is not a reference type, it is a struct.

Here is how you can set the Id property (to string value of “outlook”) at the bottom of the object tree in a single line.

Invite invite = new Invite();

ObjectWriter.Set(invite, "State_Invite_Recipient_Id", "outlook", delimiter: "_");

Spring,Request method 'POST' not supported

For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"

I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.

Java SimpleDateFormat for time zone with a colon separator?

tl;dr

OffsetDateTime.parse( "2010-03-01T00:00:00-08:00" )

Details

The answer by BalusC is correct, but now outdated as of Java 8.

java.time

The java.time framework is the successor to both Joda-Time library and the old troublesome date-time classes bundled with the earliest versions of Java (java.util.Date/.Calendar & java.text.SimpleDateFormat).

ISO 8601

Your input data string happens to comply with the ISO 8601 standard.

The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values. So no need to define a formatting pattern.

OffsetDateTime

The OffsetDateTime class represents a moment on the time line adjusted to some particular offset-from-UTC. In your input, the offset is 8 hours behind UTC, commonly used on much of the west coast of North America.

OffsetDateTime odt = OffsetDateTime.parse( "2010-03-01T00:00:00-08:00" );

You seem to want the date-only, in which case use the LocalDate class. But keep in mind you are discarding data, (a) time-of-day, and (b) the time zone. Really, a date has no meaning without the context of a time zone. For any given moment the date varies around the world. For example, just after midnight in Paris is still “yesterday” in Montréal. So while I suggest sticking with date-time values, you can easily convert to a LocalDate if you insist.

LocalDate localDate = odt.toLocalDate();

Time Zone

If you know the intended time zone, apply it. A time zone is an offset plus the rules to use for handling anomalies such as Daylight Saving Time (DST). Applying a ZoneId gets us a ZonedDateTime object.

ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = odt.atZoneSameInstant( zoneId );

Generating strings

To generate a string in ISO 8601 format, call toString.

String output = odt.toString();

If you need strings in other formats, search Stack Overflow for use of the java.util.format package.

Converting to java.util.Date

Best to avoid java.util.Date, but if you must, you can convert. Call the new methods added to the old classes such as java.util.Date.from where you pass an Instant. An Instant is a moment on the timeline in UTC. We can extract an Instant from our OffsetDateTime.

java.util.Date utilDate = java.util.Date( odt.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Callback functions in Java

I've recently started doing something like this:

public class Main {
    @FunctionalInterface
    public interface NotDotNetDelegate {
        int doSomething(int a, int b);
    }

    public static void main(String[] args) {
        // in java 8 (lambdas):
        System.out.println(functionThatTakesDelegate((a, b) -> {return a*b;} , 10, 20));

    }

    public static int functionThatTakesDelegate(NotDotNetDelegate del, int a, int b) {
        // ...
        return del.doSomething(a, b);
    }
}

Batch File; List files in directory, only filenames?

The full command is:

dir /b /a-d

Let me break it up;

Basically the /b is what you look for.

/a-d will exclude the directory names.


For more information see dir /? for other arguments that you can use with the dir command.

Adding rows dynamically with jQuery

This will get you close, the add button has been removed out of the table so you might want to consider this...

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
          $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
          return false;
        });
    });
</script>

HTML markup looks like this

  <a  id="add">+</a></td>
  <table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
  <tbody>
    <tr>
      <td>Name</td>
    </tr>
    <tr class="person">
      <td><input type="text" name="name" id="name" /></td>
    </tr>
    </tbody>
  </table>

EDIT To empty a value of a textbox after insert..

    $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
    $('#mytable tbody>tr:last #name').val('');
    return false;

EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this

$("#mytable tbody>tr:last").each(function() {this.reset();});           

I will leave the rest to you!

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)

I just removed the head portion in index.html file and it worked fine.This is the head tag in html file

How to add List<> to a List<> in asp.net

Use .AddRange to append any Enumrable collection to the list.

PHP Checking if the current date is before or after a set date

if(strtotime($db_date) > time()) {
  echo $db_date;
} else {
  echo 'go ahead';
}

Classpath including JAR within a JAR

Use the zipgroupfileset tag (uses same attributes as a fileset tag); it will unzip all files in the directory and add to your new archive file. More information: http://ant.apache.org/manual/Tasks/zip.html

This is a very useful way to get around the jar-in-a-jar problem -- I know because I have googled this exact StackOverflow question while trying to figure out what to do. If you want to package a jar or a folder of jars into your one built jar with Ant, then forget about all this classpath or third-party plugin stuff, all you gotta do is this (in Ant):

<jar destfile="your.jar" basedir="java/dir">
  ...
  <zipgroupfileset dir="dir/of/jars" />
</jar>

CSS3 Fade Effect

You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:

span {
    background: url(button.png) no-repeat 0 0;
}
a {
    width: 32px;
    height: 32px;
    text-align: left;
    background: rgb(255,255,255);

    -webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
    -moz-transition: background 300ms ease-in 200ms;
    -o-transition: background 300ms ease-in 200ms;
    transition: background 300ms ease-in 200ms;
    }
a:hover {
    background: rgba(255,255,255,0);
}

Parameterize an SQL IN clause

In SQL Server 2016+ you could use STRING_SPLIT function:

DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails';

SELECT * 
FROM Tags
WHERE Name IN (SELECT [value] FROM STRING_SPLIT(@names, ','))
ORDER BY [Count] DESC;

or:

DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails';

SELECT t.*
FROM Tags t
JOIN STRING_SPLIT(@names,',')
  ON t.Name = [value]
ORDER BY [Count] DESC;

LiveDemo

The accepted answer will of course work and it is one of the way to go, but it is anti-pattern.

E. Find rows by list of values

This is replacement for common anti-pattern such as creating a dynamic SQL string in application layer or Transact-SQL, or by using LIKE operator:

SELECT ProductId, Name, Tags
FROM Product
WHERE ',1,2,3,' LIKE '%,' + CAST(ProductId AS VARCHAR(20)) + ',%';

Addendum:

To improve the STRING_SPLIT table function row estimation, it is a good idea to materialize splitted values as temporary table/table variable:

DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails,sql';

CREATE TABLE #t(val NVARCHAR(120));
INSERT INTO #t(val) SELECT s.[value] FROM STRING_SPLIT(@names, ',') s;

SELECT *
FROM Tags tg
JOIN #t t
  ON t.val = tg.TagName
ORDER BY [Count] DESC;

SEDE - Live Demo

Related: How to Pass a List of Values Into a Stored Procedure


Original question has requirement SQL Server 2008. Because this question is often used as duplicate, I've added this answer as reference.

NVIDIA NVML Driver/library version mismatch

First I installed the Nvidia driver.

Next I installed cuda.

Ater that I got the "Driver/library version mismatch" ERROR but I could see the cuda version so I purged the Nvidia driver and reinstall it.

Then it worked correctly.

Asp Net Web API 2.1 get client IP address

I think this is the most clear solution, using an extension method:

public static class HttpRequestMessageExtensions
{
    private const string HttpContext = "MS_HttpContext";
    private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

    public static string GetClientIpAddress(this HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey(HttpContext))
        {
            dynamic ctx = request.Properties[HttpContext];
            if (ctx != null)
            {
                return ctx.Request.UserHostAddress;
            }
        }

        if (request.Properties.ContainsKey(RemoteEndpointMessage))
        {
            dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
            if (remoteEndpoint != null)
            {
                return remoteEndpoint.Address;
            }
        }

        return null;
    }
}

So just use it like:

var ipAddress = request.GetClientIpAddress();

We use this in our projects.

Source/Reference: Retrieving the client’s IP address in ASP.NET Web API

How can I run Tensorboard on a remote server?

You don't need to do anything fancy. Just run:

tensorboard --host 0.0.0.0 <other args here>

and connect with your server url and port. The --host 0.0.0.0 tells tensorflow to listen from connections on all IPv4 addresses on the local machine.

Choosing the default value of an Enum type without having to change values

An enum's default is whatever enumeration equates to zero. I don't believe this is changeable by attribute or other means.

(MSDN says: "The default value of an enum E is the value produced by the expression (E)0.")

How exactly does binary code get converted into letters?

Why not just do this take 010010001001001 split it into two bits 8 letter each (01001000, 01001001). Then issue the powers

01001000. 01001001.

The first 8 ignore the first three they determine if it's capital or not, the go right to left doing powers of 2 (2^1, 2^2 2^3 2^4 2^5). So then add all the ones up , there's only one, and it = 8, and te eight letter in the alphabet is h so our first bit is the letter h, try it on the other bit

How can I run another application within a panel of my C# program?

If you want to run notepad inside your app you would probably be better of with a text editor component. There's obviously a basic text box that comes with WinForms, but I suspect more advanced components that offer Notepad functionality (or better) can be found on the interweb.

How to unpack pkl file?

Handy one-liner

pkl() (
  python -c 'import pickle,sys;d=pickle.load(open(sys.argv[1],"rb"));print(d)' "$1"
)
pkl my.pkl

Will print __str__ for the pickled object.

The generic problem of visualizing an object is of course undefined, so if __str__ is not enough, you will need a custom script.

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

this works for me adb install -t myapk.apk

Convert an integer to a float number

Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.

In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64 equivalent of the int input. float32 datatype is also available in GoLang

Code:

package main
import "fmt"
func main() {
    var i int
    fmt.Println("Enter an Integer input: ")
    fmt.Scanf("%d", &i)
    f := float64(i)
    fmt.Printf("The float64 representation of %d is %f\n", i, f)
}

Solution:

>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000

How to compare two JSON have the same properties without order?

This code will verify the json independently of param object order.

_x000D_
_x000D_
var isEqualsJson = (obj1,obj2)=>{
    keys1 = Object.keys(obj1);
    keys2 = Object.keys(obj2);

    //return true when the two json has same length and all the properties has same value key by key
    return keys1.length === keys2.length && Object.keys(obj1).every(key=>obj1[key]==obj2[key]);
}

var obj1 = {a:1,b:2,c:3};
var obj2 = {a:1,b:2,c:3}; 

console.log("json is equals: "+ isEqualsJson(obj1,obj2));
alert("json is equals: "+ isEqualsJson(obj1,obj2));
_x000D_
_x000D_
_x000D_

JPA - Persisting a One to Many relationship

One way to do that is to set the cascade option on you "One" side of relationship:

class Employee {
   // 

   @OneToMany(cascade = {CascadeType.PERSIST})
   private Set<Vehicles> vehicles = new HashSet<Vehicles>();

   //
}

by this, when you call

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

it will save the vehicles too.

What is the "hasClass" function with plain JavaScript?

Simply use classList.contains():

if (document.body.classList.contains('thatClass')) {
    // do some stuff
}

Other uses of classList:

document.body.classList.add('thisClass');
// $('body').addClass('thisClass');

document.body.classList.remove('thatClass');
// $('body').removeClass('thatClass');

document.body.classList.toggle('anotherClass');
// $('body').toggleClass('anotherClass');

Browser Support:

  • Chrome 8.0
  • Firefox 3.6
  • IE 10
  • Opera 11.50
  • Safari 5.1

classList Browser Support

Get OS-level system information

Add OSHI dependency via maven:

<dependency>
    <groupId>com.github.dblock</groupId>
    <artifactId>oshi-core</artifactId>
    <version>2.2</version>
</dependency>

Get a battery capacity left in percentage:

SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
for (PowerSource pSource : hal.getPowerSources()) {
    System.out.println(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));
}

How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

I had to go and rename the model declaration file manually.

Edit:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(You still have to go through and manually rename your files.)

How to put a text beside the image?

I had a similar issue, where I had one div holding the image, and one div holding the text. The reason mine wasn't working, was that the div holding the image had display: inline-block while the div holding the text had display: inline.

I changed it to both be display: inline and it worked.

Here's a solution for a basic header section with a logo, title and tagline:

HTML

<div class="site-branding">
  <div class="site-branding-logo">
    <img src="add/Your/URI/Here" alt="what Is The Image About?" />
  </div>
</div>
<div class="site-branding-text">
  <h1 id="site-title">Site Title</h1>
  <h2 id="site-tagline">Site Tagline</h2>
</div>

CSS

div.site-branding { /* Position Logo and Text  */
  display: inline-block;
  vertical-align: middle;
}

div.site-branding-logo { /* Position logo within site-branding */
  display: inline;
  vertical-align: middle;
}

div.site-branding-text { /* Position text within site-branding */
    display: inline;
    width: 350px;
    margin: auto 0;
    vertical-align: middle;
}

div.site-branding-title { /* Position title within text */
    display: inline;
}

div.site-branding-tagline { /* Position tagline within text */
    display: block;
}

MySQL CONCAT returns NULL if any field contain NULL

SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
FROM devices

inverting image in Python with OpenCV

You almost did it. You were tricked by the fact that abs(imagem-255) will give a wrong result since your dtype is an unsigned integer. You have to do (255-imagem) in order to keep the integers unsigned:

def inverte(imagem, name):
    imagem = (255-imagem)
    cv2.imwrite(name, imagem)

You can also invert the image using the bitwise_not function of OpenCV:

imagem = cv2.bitwise_not(imagem)

Java command not found on Linux

I had these choices:

-----------------------------------------------
*  1           /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java
 + 2           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
   3           /home/ec2-user/local/java/jre1.7.0_25/bin/java

When I chose 3, it didn't work. When I chose 2, it did work.

jQuery date formatting

u can use this coding

$('[name="tgllahir"]').val($.datepicker.formatDate('dd-mm-yy', new Date(data.tgllahir)));

Spring Data: "delete by" is supported?

2 ways:-

1st one Custom Query

@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);

2nd one JPA Query by method

List<User> deleteByLastname(String lastname);

When you go with query by method (2nd way) it will first do a get call

select * from user where last_name = :firstName

Then it will load it in a List Then it will call delete id one by one

delete from user where id = 18
delete from user where id = 19

First fetch list of object, then for loop to delete id one by one

But, the 1st option (custom query),

It's just a single query It will delete wherever the value exists.

Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby

Simple bubble sort c#

No, your algorithm works but your Write operation is misplaced within the outer loop.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++) {
    for (int sort = 0; sort < arr.Length - 1; sort++) {
        if (arr[sort] > arr[sort + 1]) {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++)
    Console.Write(arr[i] + " ");

Console.ReadKey();

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->

return .Cell(i,1) <> Empty

Embedding VLC plugin on HTML page

test.html is will be helpful for how to use VLC WebAPI.

test.html is located in the directory where VLC was installed.

e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html

The following code is a quote from the test.html.

HTML:

<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
  <param name="MRL" value="" />
  <param name="ShowDisplay" value="True" />
  <param name="AutoLoop" value="False" />
  <param name="AutoPlay" value="False" />
  <param name="Volume" value="50" />
  <param name="toolbar" value="true" />
  <param name="StartTime" value="0" />
  <EMBED pluginspage="http://www.videolan.org"
    type="application/x-vlc-plugin"
    version="VideoLAN.VLCPlugin.2"
    width="640"
    height="360"
    toolbar="true"
    loop="false"
    text="Waiting for video"
    name="vlc">
  </EMBED>
</object>

JavaScript:

You can get vlc object from getVLC().
It works on IE 10 and Chrome.

function getVLC(name)
{
    if (window.document[name])
    {
        return window.document[name];
    }
    if (navigator.appName.indexOf("Microsoft Internet")==-1)
    {
        if (document.embeds && document.embeds[name])
            return document.embeds[name];
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    {
        return document.getElementById(name);
    }
}

var vlc = getVLC("vlc");

// do something.
// e.g. vlc.playlist.play();

Executing JavaScript without a browser?

JSDB, available for Linux, Windows, and Mac should fit the bill pretty well. It uses Mozilla's Spidermonkey Javascript engine and seems to be less of a hassle to install compared to node.js (at least last time I tried node.js a couple of years ago).

I found JSDB from this interesting list of Javascript shells: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Shells

Assign a variable inside a Block to a variable outside a Block

You need to use this line of code to resolve your problem:

__block Person *aPerson = nil;

For more details, please refer to this tutorial: Blocks and Variables

How do I efficiently iterate over each entry in a Java Map?

Use Java 8:

map.entrySet().forEach(entry -> System.out.println(entry.getValue()));

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

CSS/HTML: What is the correct way to make text italic?

I'm no expert but I'd say that if you really want to be semantic, you should use vocabularies (RDFa).

This should result in something like that:

<em property="italic" href="http://url/to/a/definition_of_italic"> Your text </em>

em is used for the presentation (humans will see it in italic) and the property and href attributes are linking to a definition of what italic is (for machines).

You should check if there's a vocabulary for that kind of thing, maybe properties already exist.

More info about RDFa here: http://www.alistapart.com/articles/introduction-to-rdfa/

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

I have tried to make note about these and have collected and written examples from a java perspective.

HTTP for Java Developers

Reverse Ajax - Old style

Async Handling on server side

Reverse Ajax - New style

Server Sent Events

Putting it here for any java developer who is looking into the same subject.

Calculating the position of points in a circle

Here is how I found out a point on a circle with javascript, calculating the angle (degree) from the top of the circle.

  const centreX = 50; // centre x of circle
  const centreY = 50; // centre y of circle
  const r = 20; // radius
  const angleDeg = 45; // degree in angle from top
  const radians = angleDeg * (Math.PI/180);
  const pointY = centreY - (Math.cos(radians) * r); // specific point y on the circle for the angle
  const pointX = centreX + (Math.sin(radians) * r); // specific point x on the circle for the angle

How to return a file (FileContentResult) in ASP.NET WebAPI

If you want to return IHttpActionResult you can do it like this:

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    var response = ResponseMessage(result);

    return response;
}

Html Agility Pack get all elements by class

You can use the following script:

var findclasses = _doc.DocumentNode.Descendants("div").Where(d => 
    d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("float")
);

lexers vs parsers

What parsers and lexers have in common:

  1. They read symbols of some alphabet from their input.

    • Hint: The alphabet doesn't necessarily have to be of letters. But it has to be of symbols which are atomic for the language understood by parser/lexer.
    • Symbols for the lexer: ASCII characters.
    • Symbols for the parser: the particular tokens, which are terminal symbols of their grammar.
  2. They analyse these symbols and try to match them with the grammar of the language they understood.

    • Here's where the real difference usually lies. See below for more.
    • Grammar understood by lexers: regular grammar (Chomsky's level 3).
    • Grammar understood by parsers: context-free grammar (Chomsky's level 2).
  3. They attach semantics (meaning) to the language pieces they find.

    • Lexers attach meaning by classifying lexemes (strings of symbols from the input) as the particular tokens. E.g. All these lexemes: *, ==, <=, ^ will be classified as "operator" token by the C/C++ lexer.
    • Parsers attach meaning by classifying strings of tokens from the input (sentences) as the particular nonterminals and building the parse tree. E.g. all these token strings: [number][operator][number], [id][operator][id], [id][operator][number][operator][number] will be classified as "expression" nonterminal by the C/C++ parser.
  4. They can attach some additional meaning (data) to the recognized elements.

    • When a lexer recognizes a character sequence constituting a proper number, it can convert it to its binary value and store with the "number" token.
    • Similarly, when a parser recognize an expression, it can compute its value and store with the "expression" node of the syntax tree.
  5. They all produce on their output a proper sentences of the language they recognize.

    • Lexers produce tokens, which are sentences of the regular language they recognize. Each token can have an inner syntax (though level 3, not level 2), but that doesn't matter for the output data and for the one which reads them.
    • Parsers produce syntax trees, which are representations of sentences of the context-free language they recognize. Usually it's only one big tree for the whole document/source file, because the whole document/source file is a proper sentence for them. But there aren't any reasons why parser couldn't produce a series of syntax trees on its output. E.g. it could be a parser which recognizes SGML tags sticked into plain-text. So it'll tokenize the SGML document into a series of tokens: [TXT][TAG][TAG][TXT][TAG][TXT]....

As you can see, parsers and tokenizers have much in common. One parser can be a tokenizer for other parser, which reads its input tokens as symbols from its own alphabet (tokens are simply symbols of some alphabet) in the same way as sentences from one language can be alphabetic symbols of some other, higher-level language. For example, if * and - are the symbols of the alphabet M (as "Morse code symbols"), then you can build a parser which recognizes strings of these dots and lines as letters encoded in the Morse code. The sentences in the language "Morse Code" could be tokens for some other parser, for which these tokens are atomic symbols of its language (e.g. "English Words" language). And these "English Words" could be tokens (symbols of the alphabet) for some higher-level parser which understands "English Sentences" language. And all these languages differ only in the complexity of the grammar. Nothing more.

So what's all about these "Chomsky's grammar levels"? Well, Noam Chomsky classified grammars into four levels depending on their complexity:

  • Level 3: Regular grammars

    They use regular expressions, that is, they can consist only of the symbols of alphabet (a,b), their concatenations (ab,aba,bbb etd.), or alternatives (e.g. a|b).
    They can be implemented as finite state automata (FSA), like NFA (Nondeterministic Finite Automaton) or better DFA (Deterministic Finite Automaton).
    Regular grammars can't handle with nested syntax, e.g. properly nested/matched parentheses (()()(()())), nested HTML/BBcode tags, nested blocks etc. It's because state automata to deal with it should have to have infinitely many states to handle infinitely many nesting levels.
  • Level 2: Context-free grammars

    They can have nested, recursive, self-similar branches in their syntax trees, so they can handle with nested structures well.
    They can be implemented as state automaton with stack. This stack is used to represent the nesting level of the syntax. In practice, they're usually implemented as a top-down, recursive-descent parser which uses machine's procedure call stack to track the nesting level, and use recursively called procedures/functions for every non-terminal symbol in their syntax.
    But they can't handle with a context-sensitive syntax. E.g. when you have an expression x+3 and in one context this x could be a name of a variable, and in other context it could be a name of a function etc.
  • Level 1: Context-sensitive grammars

  • Level 0: Unrestricted grammars
    Also called recursively enumerable grammars.

How to force input to only allow Alpha Letters?

Nice one-liner HTML only:

 <input type="text" id='nameInput' onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))'>

How to use System.Net.HttpClient to post a complex type?

Make a service call like this:

public async void SaveActivationCode(ActivationCodes objAC)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri(baseAddress);
    HttpResponseMessage response = await client.PutAsJsonAsync(serviceAddress + "/SaveActivationCode" + "?apiKey=445-65-1216", objAC);
} 

And Service method like this:

public HttpResponseMessage PutSaveActivationCode(ActivationCodes objAC)
{
}

PutAsJsonAsync takes care of Serialization and deserialization over the network

How do you run `apt-get` in a dockerfile behind a proxy?

A slight alternative to the answer provided by @Reza Farshi (which works better in my case) is to write the proxy settings out to /etc/apt/apt.conf using echo via the Dockerfile e.g.:

FROM ubuntu:16.04

RUN echo "Acquire::http::proxy \"$HTTP_PROXY\";\nAcquire::https::proxy \"$HTTPS_PROXY\";" > /etc/apt/apt.conf

# Test that we can now retrieve packages via 'apt-get'
RUN apt-get update

The advantage of this approach is that the proxy addresses can be passed in dynamically at image build time, rather than having to copy the settings file over from the host.

e.g.

docker build --build-arg HTTP_PROXY=http://<host>:<port> --build-arg HTTPS_PROXY=http://<host>:<port> .

as per docker build docs.

Draw on HTML5 Canvas using a mouse

Let me know if you have trouble implementing this. It uses processing.js and has features for changing colors and making the draw point larger and smaller.

<html>
<head>
<!--script librarires-->
<script type="text/javascript" src="processing.js"></script>
<script type="text/javascript" src="init.js"></script>

<!--styles -->
<style type="text/css" src="stylesheet.css">
</style> 
</head>
<body>
<!--toolbox -->
<div id="draggable toolbox"></div>
<script type="application/processing">
// new script
int prevx, prevy;
int newx, newy;
boolean cliked;
color c1 = #000000;
int largeur=2;
int ps = 20;
int px = 50;
int py = 50;

void setup() {
size(500,500);
frameRate(25);
background(50);

 prevx = mouseX;
 prevy = mouseY;
 cliked = false;
 }

void draw() {
 //couleur
 noStroke(0);
 fill(#FFFFFF);//blanc
rect(px, py, ps, ps);
 fill(#000000);
 rect(px, py+(ps), ps, ps);
 fill(#FF0000);
 rect(px, py+(ps*2), ps, ps);
 fill(#00FF00);
 rect(px, py+(ps*3), ps, ps);
 fill(#FFFF00);
 rect(px, py+(ps*4), ps, ps);
 fill(#0000FF);
 rect(px, py+(ps*5), ps, ps);
 //largeur
 fill(#FFFFFF);
 rect(px, py+(ps*7), ps, ps);
  fill(#FFFFFF);
 rect(px, py+(ps*8), ps, ps);
 stroke(#000000);
 line(px+2, py+(ps*7)+(ps/2), px+(ps-2), py+(ps*7)+(ps/2));
 line(px+(ps/2), py+(ps*7)+1, px+(ps/2), py+(ps*8)-1);
 line(px+2, py+(ps*8)+(ps/2), px+(ps-2), py+(ps*8)+(ps/2));

 if(cliked==false){
  prevx = mouseX;
 prevy = mouseY;  
 }
 if(mousePressed) { 
  cliked = true;
 newx = mouseX;
  newy = mouseY;
  strokeWeight(largeur);
  stroke(c1);
  line(prevx, prevy, newx, newy);
  prevx = newx;
 prevy = newy;
 }else{
  cliked= false;
  }
}
void mouseClicked() {
 if (mouseX>=px && mouseX<=(px+ps)){
  //couleur
  if (mouseY>=py && mouseY<=py+(ps*6)){ 
   c1 = get(mouseX, mouseY);
  }
   //largeur
  if (mouseY>=py+(ps*7) && mouseY<=py+(ps*8)){ 
   largeur += 2;
  }
 if (mouseY>=py+(ps*8) && mouseY<=py+(ps*9)){ 
   if (largeur>2){
    largeur -= 2;
   }
  }
 }
}
</script><canvas></canvas>
</body>
</html>

What does '<?=' mean in PHP?

Code like "a => b" means, for an associative array (some languages, like Perl, if I remember correctly, call those "hash"), that 'a' is a key, and 'b' a value.

You might want to take a look at the documentations of, at least:

Here, you are having an array, called $user_list, and you will iterate over it, getting, for each line, the key of the line in $user, and the corresponding value in $pass.

For instance, this code:

$user_list = array(
    'user1' => 'password1',
    'user2' => 'password2',
);

foreach ($user_list as $user => $pass)
{
    var_dump("user = $user and password = $pass");
}

Will get you this output:

string 'user = user1 and password = password1' (length=37)
string 'user = user2 and password = password2' (length=37)

(I'm using var_dump to generate a nice output, that facilitates debuging; to get a normal output, you'd use echo)


"Equal or greater" is the other way arround: "greater or equals", which is written, in PHP, like this; ">="
The Same thing for most languages derived from C: C++, JAVA, PHP, ...


As a piece of advice: If you are just starting with PHP, you should definitely spend some time (maybe a couple of hours, maybe even half a day or even a whole day) going through some parts of the manual :-)
It'd help you much!

ESRI : Failed to parse source map

This may sometimes be caused by Chrome extensions you've installed. For example, AdBlock.

Unfortunately the best solution I could find was to disable the offending extension.

IntelliJ: Never use wildcard imports

  1. File\Settings... (Ctrl+Alt+S)
  2. Project Settings > Editor > Code Style > Java > Imports tab
  3. Set Class count to use import with '*' to 999
  4. Set Names count to use static import with '*' to 999

After this, your configuration should look like: enter image description here

(On IntelliJ IDEA 13.x, 14.x, 15.x, 2016.x, 2017.x)

Error 1053 the service did not respond to the start or control request in a timely fashion

After spending some time on the issue, trying solutions that didn't work, I run into this blog. It suggests to wrap the service initialization code in a try/catch block, like this, and adding EventLog

using System;
using System.Diagnostics;
using System.ServiceProcess;

namespace WindowsService
{
    static class Program
    {
        static void Main()
        {
            try
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new Service1() 
                };
                ServiceBase.Run(ServicesToRun);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);
            }
        }
    }
}

Then, uninstall the old service, redeploy the service with these modifications. Start the service and check out the Event Viewer/Application logs. You'll see what the real problem is, which is the underlying reason for the timeout.

How to add a Try/Catch to SQL Stored Procedure

Create Proc[usp_mquestions]  
( 
 @title  nvarchar(500),   --0
 @tags  nvarchar(max),   --1
 @category  nvarchar(200),   --2
 @ispoll  char(1),   --3
 @descriptions  nvarchar(max),   --4
)              
 AS  
 BEGIN TRY




BEGIN
DECLARE @message varchar(1000); 
DECLARE @tempid bigint; 

IF((SELECT count(id) from  [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN               


if @id=0 
begin 
select @tempid =id from [xyz] where id=@id;

if @tempid is null 
BEGIN 
        INSERT INTO xyz
        (entrydate,updatedate)
        VALUES
        (GETDATE(),GETDATE())

        SET @tempid=@@IDENTITY;
 END 
END 
ELSE 
BEGIN 
set @tempid=@id 
END 
if @tempid>0 
BEGIN 

    -- Updation of table begin--


UPDATE  tab_questions
set title=@title, --0 
 tags=@tags, --1 
 category=@category, --2 
 ispoll=@ispoll, --3 
 descriptions=@descriptions, --4 
 status=@status, --5

WHERE id=@tempid ; --9 ;


IF @id=0 
BEGIN 
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END 
ELSE 
BEGIN 
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)

END 
END 
ELSE 
BEGIN 
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END 

END
END

END TRY
BEGIN CATCH
    SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;

Fastest way to find second (third...) highest/lowest value in vector or column

Use the partial argument of sort(). For the second highest value:

n <- length(x)
sort(x,partial=n-1)[n-1]

SQL Server : SUM() of multiple rows including where clauses

sounds like you want something like:

select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID

How to get nth jQuery element

Why not browse the (short) selectors page first?

Here it is: the :eq() operator. It is used just like get(), but it returns the jQuery object.

Or you can use .eq() function too.

Display alert message and redirect after click on accept

echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';
</script>";

and get rid of redirect line below.

You were mixing up two different worlds.

Calculating distance between two points, using latitude longitude?

Slightly upgraded answer from @David George:

public static double distance(double lat1, double lat2, double lon1,
                              double lon2, double el1, double el2) {

    final int R = 6371; // Radius of the earth

    double latDistance = Math.toRadians(lat2 - lat1);
    double lonDistance = Math.toRadians(lon2 - lon1);
    double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
            + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
            * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = R * c * 1000; // convert to meters

    double height = el1 - el2;

    distance = Math.pow(distance, 2) + Math.pow(height, 2);

    return Math.sqrt(distance);
}

public static double distanceBetweenLocations(Location l1, Location l2) {
    if(l1.hasAltitude() && l2.hasAltitude()) {
        return distance(l1.getLatitude(), l2.getLatitude(), l1.getLongitude(), l2.getLongitude(), l1.getAltitude(), l2.getAltitude());
    }
    return l1.distanceTo(l2);
}

distance function is the same, but I've created I small wrapper function, which takes 2 Location objects. Thanks to this, I only use distance function if both of locations actually have altitude, because sometimes they don't. And it can lead to strange results (if location doesn't know its altitude 0 will be returned). In this case, I fall back to classic distanceTo function.

How to bring back "Browser mode" in IE11?

In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good

How to add,set and get Header in request of HttpClient?

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

Can one class extend two classes?

In Groovy, you can use trait instead of class. As they act similar to abstract classes (in the way that you can specify abstract methods, but you can still implement others), you can do something like:

trait EmployeeTrait {
    int getId() {
         return 1000 //Default value
    }
    abstract String getName() //Required
}

trait CustomerTrait {
    String getCompany() {
        return "Internal" // Default value
    }
    abstract String getAddress()
}

class InternalCustomer implements EmployeeTrait, CustomerTrait {
    String getName() { ... }
    String getAddress() { ... }
}

def internalCustomer = new InternalCustomer()
println internalCustomer.id // 1000
println internalCustomer.company //Internal

Just to point out, its not exactly the same as extending two classes, but in some cases (like the above example), it can solve the situation. I strongly suggest to analyze your design before jumping into using traits, usually they are not required and you won't be able to nicely implement inheritance (for example, you can't use protected methods in traits). Follow the accepted answer's recommendation if possible.

What's the best way to share data between activities?

Do what google commands you to do! here: http://developer.android.com/resources/faq/framework.html#3

  • Primitive Data Types
  • Non-Persistent Objects
  • Singleton class - my favorite :D
  • A public static field/method
  • A HashMap of WeakReferences to Objects
  • Persistent Objects (Application Preferences, Files, contentProviders, SQLite DB)

Get HTML source of WebElement in Selenium WebDriver using Python

And in PHPUnit Selenium test it's like this:

$text = $this->byCssSelector('.some-class-nmae')->attribute('innerHTML');

Controlling a USB power supply (on/off) with Linux

According to the docs, there were several changes to the USB power management from kernels 2.6.32, which seem to settle in 2.6.38. Now you'll need to wait for the device to become idle, which is governed by the particular device driver. The driver needs to support it, otherwise the device will never reach this state. Unluckily, now the user has no chance to force this. However, if you're lucky and your device can become idle, then to turn this off you need to:

echo "0" > "/sys/bus/usb/devices/usbX/power/autosuspend"
echo "auto" > "/sys/bus/usb/devices/usbX/power/level"

or, for kernels around 2.6.38 and above:

echo "0" > "/sys/bus/usb/devices/usbX/power/autosuspend_delay_ms"
echo "auto" > "/sys/bus/usb/devices/usbX/power/control"

This literally means, go suspend at the moment the device becomes idle.

So unless your fan is something "intelligent" that can be seen as a device and controlled by a driver, you probably won't have much luck on current kernels.

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

remove borders around html input

It's simple

input {border:0;outline:0;}
input:focus {outline:none!important;}

load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))

Python: URLError: <urlopen error [Errno 10060]

The error code 10060 means it cannot connect to the remote peer. It might be because of the network problem or mostly your setting issues, such as proxy setting.

You could try to connect the same host with other tools(such as ncat) and/or with another PC within your same local network to find out where the problem is occuring.

For proxy issue, there are some material here:

Using an HTTP PROXY - Python

Why can't I get Python's urlopen() method to work on Windows?

Hope it helps!

asp.net validation to make sure textbox has integer values

<script language="javascript" type="text/javascript">
        function fixedlength(textboxID, keyEvent, maxlength) {
            //validation for digits upto 'maxlength' defined by caller function
            if (textboxID.value.length > maxlength) {
                textboxID.value = textboxID.value.substr(0, maxlength);
            }
            else if (textboxID.value.length < maxlength || textboxID.value.length == maxlength) {
                textboxID.value = textboxID.value.replace(/[^\d]+/g, '');
                return true;
            }
            else
                return false;
        }
 </script>

<asp:TextBox ID="txtNextVisit" runat="server" MaxLength="2" onblur="return fixedlength(this, event, 2);" onkeypress="return fixedlength(this, event, 2);" onkeyup="return fixedlength(this, event, 2);"></asp:TextBox> 

Counting array elements in Perl

sub uniq {
    return keys %{{ map { $_ => 1 } @_ }};
}
my @my_array = ("a","a","b","b","c");
#print join(" ", @my_array), "\n";
my $a = join(" ", uniq(@my_array));
my @b = split(/ /,$a);
my $count = $#b;

Serialize JavaScript object into JSON string

You can use a named function on the constructor.

MyClass1 = function foo(id, member) {
    this.id = id;
    this.member = member;
}

var myobject = new MyClass1("5678999", "text");

console.log( myobject.constructor );

//function foo(id, member) {
//    this.id = id;
//    this.member = member;
//}

You could use a regex to parse out 'foo' from myobject.constructor and use that to get the name.

Is it possible to change the location of packages for NuGet?

  1. Created a file called "nuget.config".
  2. Added that file to my solutions folder

this did NOT work for me:

<configuration>
  <config>
    <add key="repositoryPath" value="..\ExtLibs\Packages" />
  </config>
  ... 
</configuration>

this did WORK for me:

<?xml version="1.0" encoding="utf-8"?>
<settings>
  <repositoryPath>..\ExtLibs\Packages</repositoryPath>
</settings>

MessageBodyWriter not found for media type=application/json

To overcome this issue try the following. Worked for me.

Add following dependency in the pom.xml

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-json-jackson</artifactId>
  <version>2.25</version>
</dependency>

And make sure Model class contains no arg constructor

 public Student()
    {
    }

Understanding the Rails Authenticity Token

Minimal attack example that would be prevented: CSRF

On my website evil.com I convince you to submit the following form:

<form action="http://bank.com/transfer" method="post">
  <p><input type="hidden" name="to"      value="ciro"></p>
  <p><input type="hidden" name="ammount" value="100"></p>
  <p><button type="submit">CLICK TO GET PRIZE!!!</button></p>
</form>

If you are logged into your bank through session cookies, then the cookies would be sent and the transfer would be made without you even knowing it.

That is were the CSRF token comes into play:

  • with the GET response that that returned the form, Rails sends a very long random hidden parameter
  • when the browser makes the POST request, it will send the parameter along, and the server will only accept it if it matches

So the form on an authentic browser would look like:

<form action="http://bank.com/transfer" method="post">
  <p><input type="hidden" name="authenticity_token" value="j/DcoJ2VZvr7vdf8CHKsvjdlDbmiizaOb5B8DMALg6s=" ></p>
  <p><input type="hidden" name="to"                 value="ciro"></p>
  <p><input type="hidden" name="ammount"            value="100"></p>
  <p><button type="submit">Send 100$ to Ciro.</button></p>
</form>

Thus, my attack would fail, since it was not sending the authenticity_token parameter, and there is no way I could have guessed it since it is a huge random number.

This prevention technique is called Synchronizer Token Pattern.

Same Origin Policy

But what if the attacker made two requests with JavaScript, one to read the token, and the second one to make the transfer?

The synchronizer token pattern alone is not enough to prevent that!

This is where the Same Origin Policy comes to the rescue, as I have explained at: https://security.stackexchange.com/questions/8264/why-is-the-same-origin-policy-so-important/72569#72569

How Rails sends the tokens

Covered at: Rails: How Does csrf_meta_tag Work?

Basically:

  • HTML helpers like form_tag add a hidden field to the form for you if it's not a GET form

  • AJAX is dealt with automatically by jquery-ujs, which reads the token from the meta elements added to your header by csrf_meta_tags (present in the default template), and adds it to any request made.

    uJS also tries to update the token in forms in outdated cached fragments.

Other prevention approaches

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

How to get selected option using Selenium WebDriver with Java

On the following option:

WebElement option = select.getFirstSelectedOption();
option.getText();

If from the method getText() you get a blank, you can get the string from the value of the option using the method getAttribute:

WebElement option = select.getFirstSelectedOption();
option.getAttribute("value");

Why does corrcoef return a matrix?

You can use the following function to return only the correlation coefficient:

def pearson_r(x, y):
"""Compute Pearson correlation coefficient between two arrays."""

   # Compute correlation matrix
   corr_mat = np.corrcoef(x, y)

   # Return entry [0,1]
   return corr_mat[0,1]

How to redirect siteA to siteB with A or CNAME records

It's probably best/easiest to set up a 301 redirect. No DNS hacking required.

When do you use Git rebase instead of Git merge?

While merging is definitely the easiest and most common way to integrate changes, it's not the only one: Rebase is an alternative means of integration.

Understanding Merge a Little Better

When Git performs a merge, it looks for three commits:

  • (1) Common ancestor commit. If you follow the history of two branches in a project, they always have at least one commit in common: at this point in time, both branches had the same content and then evolved differently.
  • (2) + (3) Endpoints of each branch. The goal of an integration is to combine the current states of two branches. Therefore, their respective latest revisions are of special interest. Combining these three commits will result in the integration we're aiming for.

Fast-Forward or Merge Commit

In very simple cases, one of the two branches doesn't have any new commits since the branching happened - its latest commit is still the common ancestor.

Enter image description here

In this case, performing the integration is dead simple: Git can just add all the commits of the other branch on top of the common ancestor commit. In Git, this simplest form of integration is called a "fast-forward" merge. Both branches then share the exact same history.

Enter image description here

In a lot of cases, however, both branches moved forward individually.

Enter image description here

To make an integration, Git will have to create a new commit that contains the differences between them - the merge commit.

Enter image description here

Human Commits & Merge Commits

Normally, a commit is carefully created by a human being. It's a meaningful unit that wraps only related changes and annotates them with a comment.

A merge commit is a bit different: instead of being created by a developer, it gets created automatically by Git. And instead of wrapping a set of related changes, its purpose is to connect two branches, just like a knot. If you want to understand a merge operation later, you need to take a look at the history of both branches and the corresponding commit graph.

Integrating with Rebase

Some people prefer to go without such automatic merge commits. Instead, they want the project's history to look as if it had evolved in a single, straight line. No indication remains that it had been split into multiple branches at some point.

Enter image description here

Let's walk through a rebase operation step by step. The scenario is the same as in the previous examples: we want to integrate the changes from branch-B into branch-A, but now by using rebase.

Enter image description here

We will do this in three steps

  1. git rebase branch-A // Synchronises the history with branch-A
  2. git checkout branch-A // Change the current branch to branch-A
  3. git merge branch-B // Merge/take the changes from branch-B to branch-A

First, Git will "undo" all commits on branch-A that happened after the lines began to branch out (after the common ancestor commit). However, of course, it won't discard them: instead you can think of those commits as being "saved away temporarily".

Enter image description here

Next, it applies the commits from branch-B that we want to integrate. At this point, both branches look exactly the same.

Enter image description here

In the final step, the new commits on branch-A are now reapplied - but on a new position, on top of the integrated commits from branch-B (they are re-based).

The result looks like development had happened in a straight line. Instead of a merge commit that contains all the combined changes, the original commit structure was preserved.

Enter image description here

Finally, you get a clean branch branch-A with no unwanted and auto generated commits.

Note: Taken from the awesome post by git-tower. The disadvantages of rebase is also a good read in the same post.

How do you pass view parameters when navigating from an action in JSF2?

Check out these:

You're gonna need something like:

<h:link outcome="success">
  <f:param name="foo" value="bar"/>
</h:link>

...and...

<f:metadata>
  <f:viewParam name="foo" value="#{bean.foo}"/>
</f:metadata>

Judging from this page, something like this might be easier:

 <managed-bean>
   <managed-bean-name>blog</managed-bean-name>
   <managed-bean-class>com.acme.Blog</managed-bean-class>
   <managed-property>
      <property-name>entryId</property-name>
      <value>#{param['id']}</value>
   </managed-property>
 </managed-bean>

How to convert a Binary String to a base 10 integer in Java

public Integer binaryToInteger(String binary){
    char[] numbers = binary.toCharArray();
    Integer result = 0;
    int count = 0;
    for(int i=numbers.length-1;i>=0;i--){
         if(numbers[i]=='1')result+=(int)Math.pow(2, count);
         count++;
    }
    return result;
}

I guess I'm even more bored! Modified Hassan's answer to function correctly.

mysql query: SELECT DISTINCT column1, GROUP BY column2

Try the following:

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

Custom method names in ASP.NET Web API

Web APi 2 and later versions support a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.

For example:

[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }

Will perfect and you don't need any extra code for example in WebApiConfig.cs. Just you have to be sure web api routing is enabled or not in WebApiConfig.cs , if not you can activate like below:

        // Web API routes
        config.MapHttpAttributeRoutes();

You don't have to do something more or change something in WebApiConfig.cs. For more details you can have a look this article.

How to pass parameters or arguments into a gradle task

Its nothing more easy.

run command: ./gradlew clean -PjobId=9999

and

in gradle use: println(project.gradle.startParameter.projectProperties)

You will get clue.

How to Convert double to int in C?

main() {
    double a;
    a=3669.0;
    int b;
    b=a;
    printf("b is %d",b);
  
}

output is :b is 3669

when you write b=a; then its automatically converted in int

see on-line compiler result : 

http://ideone.com/60T5b


This is called Implicit Type Conversion Read more here https://www.geeksforgeeks.org/implicit-type-conversion-in-c-with-examples/

Center Div inside another (100% width) div

The below style to the inner div will center it.

margin: 0 auto;

How do I pass along variables with XMLHTTPRequest

Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.

You could write a simple utility function that handles building the query formatting for you.

function formatParams( params ){
  return "?" + Object
        .keys(params)
        .map(function(key){
          return key+"="+encodeURIComponent(params[key])
        })
        .join("&")
}

And you would use it this way to build a request.

var endpoint = "https://api.example.com/endpoint"
var params = {
  a: 1, 
  b: 2,
  c: 3
}

var url = endpoint + formatParams(params)
//=> "https://api.example.com/endpoint?a=1&b=2&c=3"

There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give http://api.jquery.com/jquery.param/ a try.

It is similar to the above example function, but handles recursively serializing nested objects and arrays.

Create hyperlink to another sheet

This is the code I use for creating an index sheet.

Sub CreateIndexSheet()
    Dim wSheet As Worksheet
    ActiveWorkbook.Sheets.Add(Before:=Worksheets(1)).Name = "Contents" 'Call whatever you like
    Range("A1").Select
    Application.ScreenUpdating = False 'Prevents seeing all the flashing as it updates the sheet
    For Each wSheet In Worksheets
        ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'" & wSheet.Name & "'" & "!A1", TextToDisplay:=wSheet.Name
        ActiveCell.Offset(1, 0).Select 'Moves down a row
    Next
    Range("A1").EntireColumn.AutoFit
    Range("A1").EntireRow.Delete 'Remove content sheet from content list
    Application.ScreenUpdating = True
End Sub

How Does Modulus Divison Work

I would like to add one more thing:

it's easy to calculate modulo when dividend is greater/larger than divisor

dividend = 5 divisor = 3

5 % 3 = 2

3)5(1
  3
-----
  2

but what if divisor is smaller than dividend

dividend = 3 divisor = 5

3 % 5 = 3 ?? how

This is because, since 5 cannot divide 3 directly, modulo will be what dividend is

Absolute and Flexbox in React Native

Ok, solved my problem, if anyone is passing by here is the answer:

Just had to add left: 0, and top: 0, to the styles, and yes, I'm tired.

position: 'absolute',
left:     0,
top:      0,

Using classes with the Arduino

There is an excellent tutorial on how to create a library for the Arduino platform. A library is basically a class, so it should show you how its all done.

On Arduino you can use classes, but there are a few restrictions:

  • No new and delete keywords
  • No exceptions
  • No libstdc++, hence no standard functions, templates or classes

You also need to make new files for your classes, you can't just declare them in your main sketch. You also will need to close the Arduino IDE when recompiling a library. That is why I use Eclipse as my Arduino IDE.

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Any way of using frames in HTML5?

Frames were not deprecated in HTML5, but were deprecated in XHTML 1.1 Strict and 2.0, but remained in XHTML Transitional and returned in HTML5. Also here is an interesting article on using CSS to mimic frames without frames. I just tested it in IE 8, FF 3, Opera 11, Safari 5, Chrome 8. I love frames, but they do have their problems, particularly with search engines, bookmarks and printing and with CSS you can create print or display only content. I'm hoping to upgrade Alex's XHTML/CSS frame without frames solution to HTML5/CSS3.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Class has no initializers Swift

In my case I have declared a Bool like this:

var isActivityOpen: Bool 

i.e. I declared it without unwrapping so, This is how I solved the (no initializer) error :

var isActivityOpen: Bool!

ng is not recognized as an internal or external command

PATH environment variable should be updated by adding following path,

C:\Users\xyzname\AppData\Roaming\npm\node_modules\@angular\cli\bin

Because ng file is in bin folder, once this is added for sure ng will be recognized

Datatable vs Dataset

One major difference is that DataSets can hold multiple tables and you can define relationships between those tables.

If you are only returning a single result set though I would think a DataTable would be more optimized. I would think there has to be some overhead (granted small) to offer the functionality a DataSet does and keep track of multiple DataTables.

What's the difference between compiled and interpreted language?

Java and JavaScript are a fairly bad example to demonstrate this difference, because both are interpreted languages. Java (interpreted) and C (or C++) (compiled) might have been a better example.

Why the striked-through text? As this answer correctly points out, interpreted/compiled is about a concrete implementation of a language, not about the language per se. While statements like "C is a compiled language" are generally true, there's nothing to stop someone from writing a C language interpreter. In fact, interpreters for C do exist.

Basically, compiled code can be executed directly by the computer's CPU. That is, the executable code is specified in the CPU's "native" language (assembly language).

The code of interpreted languages however must be translated at run-time from any format to CPU machine instructions. This translation is done by an interpreter.

Another way of putting it is that interpreted languages are code is translated to machine instructions step-by-step while the program is being executed, while compiled languages have code has been translated before program execution.

for each loop in Objective-C for accessing NSMutable dictionary

Fast enumeration was added in 10.5 and in the iPhone OS, and it's significantly faster, not just syntactic sugar. If you have to target the older runtime (i.e. 10.4 and backwards), you'll have to use the old method of enumerating:

NSDictionary *myDict = ... some keys and values ...
NSEnumerator *keyEnum = [myDict keyEnumerator];
id key;

while ((key = [keyEnum nextObject]))
{
    id value = [myDict objectForKey:key];
    ... do work with "value" ...
}

You don't release the enumerator object, and you can't reset it. If you want to start over, you have to ask for a new enumerator object from the dictionary.

PLS-00103: Encountered the symbol "CREATE"

Run package declaration and body separately.

Change the size of a JTextField inside a JBorderLayout

With a BorderLayout you need to use setPreferredSize instead of setSize

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

First, you need to add HttpHeaders with HttpClient

import { HttpClient,HttpHeaders  } from '@angular/common/http';

your constructor should be like this.

constructor(private http: HttpClient) { }

then you can use like this

   let header = new HttpHeaders({ "Authorization": "Bearer "+token});

   const requestOptions = {  headers: header};                                                                                                                                                                            

    return this.http.get<any>(url, requestOptions)
        .toPromise()
        .then(data=> {
            //...
            return data;
    });

C# Numeric Only TextBox Control

From C#3.5 I assume you're using WPF.

Just make a two-way data binding from an integer property to your text-box. WPF will show the validation error for you automatically.

For the email case, make a two-way data binding from a string property that does Regexp validation in the setter and throw an Exception upon validation error.

Look up Binding on MSDN.

How to keep indent for second line in ordered lists via CSS?

The following CSS did the trick:

ul{
    margin-left: 1em;
}

li{
    list-style-position: outside;
    padding-left: 0.5em;
}

What is better, adjacency lists or adjacency matrices for graph problems in C++?

It depends on what you're looking for.

With adjacency matrices you can answer fast to questions regarding if a specific edge between two vertices belongs to the graph, and you can also have quick insertions and deletions of edges. The downside is that you have to use excessive space, especially for graphs with many vertices, which is very inefficient especially if your graph is sparse.

On the other hand, with adjacency lists it is harder to check whether a given edge is in a graph, because you have to search through the appropriate list to find the edge, but they are more space efficient.

Generally though, adjacency lists are the right data structure for most applications of graphs.

How to secure phpMyAdmin

One of my concerns with phpMyAdmin was that by default, all MySQL users can access the db. If DB's root password is compromised, someone can wreck havoc on the db. I wanted to find a way to avoid that by restricting which MySQL user can login to phpMyAdmin.

I have found using AllowDeny configuration in PhpMyAdmin to be very useful. http://wiki.phpmyadmin.net/pma/Config#AllowDeny_.28rules.29

AllowDeny lets you configure access to phpMyAdmin in a similar way to Apache. If you set the 'order' to explicit, it will only grant access to users defined in 'rules' section. In the rules, section you restrict MySql users who can access use the phpMyAdmin.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit'
$cfg['Servers'][$i]['AllowDeny']['rules'] = array('pma-user from all')

Now you have limited access to the user named pma-user in MySQL, you can grant limited privilege to that user.

grant select on db_name.some_table to 'pma-user'@'app-server'

Change connection string & reload app.config at run time

Had to do this exact thing. This is the code that worked for me:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["Blah"].ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

how to set start page in webconfig file in asp.net c#

The same problem arrised for me when I installed Kaliko CMS Nuget Package. When I removed it, it started working fine again. So, your problem could be because of a recently installed Nuget Package. Uninstall it and your solution will work just fine.

Aesthetics must either be length one, or the same length as the dataProblems

I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:

ggplot(df, aes(x="", y = y, fill=grp))

because df was empty.

regular expression for anything but an empty string

Create "regular expression to detect empty string", and then inverse it. Invesion of regular language is the regular language. I think regular expression library in what you leverage - should support it, but if not you always can write your own library.

grep --invert-match

recyclerview No adapter attached; skipping layout

// It happens when you are not setting the adapter during the creation phase: call notifyDataSetChanged() when api response is getting Its Working

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);


        magazineAdapter = new MagazineAdapter(getContext(), null, this );
        newClipRecyclerView.setAdapter(magazineAdapter);
        magazineAdapter.notifyDataSetChanged();

       APICall();
}

public void APICall() {
    if(Response.isSuccessfull()){
    mRecyclerView.setAdapter(mAdapter);
   }
}
Just move setting the adapter into onCreate with an empty data and when you have the data call:

mAdapter.notifyDataSetChanged();

How to add parameters into a WebRequest?

Use stream to write content to webrequest

string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;  
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();  

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Use this snip : var IE = (navigator.userAgent.indexOf("Edge") > -1 || navigator.userAgent.indexOf("Trident/7.0") > -1) ? true : false;

Functional, Declarative, and Imperative Programming

imperative and declarative describe two opposing styles of programming. imperative is the traditional "step by step recipe" approach while declarative is more "this is what i want, now you work out how to do it".

these two approaches occur throughout programming - even with the same language and the same program. generally the declarative approach is considered preferable, because it frees the programmer from having to specify so many details, while also having less chance for bugs (if you describe the result you want, and some well-tested automatic process can work backwards from that to define the steps then you might hope that things are more reliable than having to specify each step by hand).

on the other hand, an imperative approach gives you more low level control - it's the "micromanager approach" to programming. and that can allow the programmer to exploit knowledge about the problem to give a more efficient answer. so it's not unusual for some parts of a program to be written in a more declarative style, but for the speed-critical parts to be more imperative.

as you might imagine, the language you use to write a program affects how declarative you can be - a language that has built-in "smarts" for working out what to do given a description of the result is going to allow a much more declarative approach than one where the programmer needs to first add that kind of intelligence with imperative code before being able to build a more declarative layer on top. so, for example, a language like prolog is considered very declarative because it has, built-in, a process that searches for answers.

so far, you'll notice that i haven't mentioned functional programming. that's because it's a term whose meaning isn't immediately related to the other two. at its most simple, functional programming means that you use functions. in particular, that you use a language that supports functions as "first class values" - that means that not only can you write functions, but you can write functions that write functions (that write functions that...), and pass functions to functions. in short - that functions are as flexible and common as things like strings and numbers.

it might seem odd, then, that functional, imperative and declarative are often mentioned together. the reason for this is a consequence of taking the idea of functional programming "to the extreme". a function, in it's purest sense, is something from maths - a kind of "black box" that takes some input and always gives the same output. and that kind of behaviour doesn't require storing changing variables. so if you design a programming language whose aim is to implement a very pure, mathematically influenced idea of functional programming, you end up rejecting, largely, the idea of values that can change (in a certain, limited, technical sense).

and if you do that - if you limit how variables can change - then almost by accident you end up forcing the programmer to write programs that are more declarative, because a large part of imperative programming is describing how variables change, and you can no longer do that! so it turns out that functional programming - particularly, programming in a functional language - tends to give more declarative code.

to summarise, then:

  • imperative and declarative are two opposing styles of programming (the same names are used for programming languages that encourage those styles)

  • functional programming is a style of programming where functions become very important and, as a consequence, changing values become less important. the limited ability to specify changes in values forces a more declarative style.

so "functional programming" is often described as "declarative".

How to style SVG with external CSS?

@leo here is the angularJS version, thanks again

G.directive ( 'imgInlineSvg', function () {

return {
    restrict : 'C',
    scope : true,
    link : function ( scope, elem, attrs ) {

        if ( attrs.src ) {

            $ ( attrs ).each ( function () {
                var imgID    = attrs.class;
                var imgClass = attrs.class;
                var imgURL   = attrs.src;

                $.get ( imgURL, function ( data ) {

                    var $svg = $ ( data ).find ( 'svg' );
                    if ( typeof imgID !== 'undefined' ) {
                        $svg = $svg.attr ( 'id', imgID );
                    }

                    if ( typeof imgClass !== 'undefined' ) {
                        $svg = $svg.attr ( 'class', imgClass + ' replaced-svg' );
                    }

                    $svg = $svg.removeAttr ( 'xmlns:a' );

                    elem.replaceWith ( $svg );

                } );

            } );
        }

    }

}

} );

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

First check - is the working directory the directory that the application is running in:

  • Right-click on your project and select Properties.
  • Click the Debug tab.
  • Confirm that the Working directory is either empty or equal to the bin\debug directory.

If this isn't the problem, then ask if Autodesk.Navisworks.Timeliner.dll is requiring another DLL which is not there. If Timeliner.dll is not a .NET assembly, you can determine the required imports using the command utility DUMPBIN.

dumpbin /imports Autodesk.Navisworks.Timeliner.dll

If it is a .NET assembly, there are a number of tools that can check dependencies.

Reflector has already been mentioned, and I use JustDecompile from Telerik.


Also see this question

What are the "spec.ts" files generated by Angular CLI for?

.spec.ts file is used for unit testing of your application.

If you don't to get it generated just use --spec=false while creating new Component. Like this

ng generate component --spec=false mycomponentName

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

JPG vs. JPEG image formats

No difference at all.

I personally prefer having 3 letters extensions, but you might prefer having the full name.
It's pure aestetics (personal taste), nothing else.
The format doesn't change.

You can rename the jpeg files into jpg (or vice versa) an nothing changes: they will open in your picture viewer.

By opening both a JPG and a JPEG file with an hex editor, you will notice that they share the very same heading information.

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

How to convert a plain object into an ES6 Map?

const myMap = new Map(
    Object
        .keys(myObj)
        .map(
            key => [key, myObj[key]]
        )
)

Key Presses in Python

import keyboard

keyboard.press_and_release('anykey')

How to create javascript delay function

You can create a delay using the following example

setInterval(function(){alert("Hello")},3000);

Replace 3000 with # of milliseconds

You can place the content of what you want executed inside the function.

Is there a simple way to remove multiple spaces in a string?

foo is your string:

" ".join(foo.split())

Be warned though this removes "all whitespace characters (space, tab, newline, return, formfeed)" (thanks to hhsaffar, see comments). I.e., "this is \t a test\n" will effectively end up as "this is a test".

Which TensorFlow and CUDA version combinations are compatible?

TL;DR) See this table: https://www.tensorflow.org/install/source#gpu

Generally:

Check the CUDA version:

cat /usr/local/cuda/version.txt

and cuDNN version:

grep CUDNN_MAJOR -A 2 /usr/local/cuda/include/cudnn.h

and install a combination as given below in the images or here.

The following images and the link provide an overview of the officially supported/tested combinations of CUDA and TensorFlow on Linux, macOS and Windows:

Minor configurations:

Since the given specifications below in some cases might be too broad, here is one specific configuration that works:

  • tensorflow-gpu==1.12.0
  • cuda==9.0
  • cuDNN==7.1.4

The corresponding cudnn can be downloaded here.

Tested build configurations

Please refer to https://www.tensorflow.org/install/source#gpu for a up-to-date compatibility chart (for official TF wheels).

(figures updated May 20, 2020)

Linux GPU

enter image description here

Linux CPU

enter image description here

macOS GPU

enter image description here

macOS CPU

enter image description here

Windows GPU

enter image description here

Windows CPU

enter image description here

Updated as of Dec 5 2020: For the updated information please refer Link for Linux and Link for Windows.

How do I write a compareTo method which compares objects?

You're almost all the way there.

Your first few lines, comparing the last name, are right on track. The compareTo() method on string will return a negative number for a string in alphabetical order before, and a positive number for one in alphabetical order after.

Now, you just need to do the same thing for your first name and score.

In other words, if Last Name 1 == Last Name 2, go on a check your first name next. If the first name is the same, check your score next. (Think about nesting your if/then blocks.)

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

If you're using SQL Management Studio, please goto connection properties and click on "Trust server certificated" If you're using SQL Management Studio, please goto connection properties and click on "Trust server certificated"

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

The best and simple way:

Convert(varchar, {EndTime} - {StartTime}, 108)

Just like Anri noted.

Add column with number of days between dates in DataFrame pandas

To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html

So,

df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
df['C'] = (df['B'] - df['A']).dt.days

which returns:

             A          B   C
one 2014-01-01 2014-02-28  58
two 2014-02-03 2014-03-01  26

Python dictionary get multiple values

As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:

first_val, second_val = (myDict.get(key) for key in [first_key, second_key])

An object reference is required to access a non-static member

Make your audioSounds and minTime variables as static variables, as you are using them in a static method (playSound).

Marking a method as static prevents the usage of non-static (instance) members in that method.

To understand more , please read this SO QA:

Static keyword in c#

Is there a way to override class variables in Java?

It indeed prints 'dad', since the field is not overridden but hidden. There are three approaches to make it print 'son':

Approach 1: override printMe

class Dad
{
    protected static String me = "dad";

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    protected static String me = "son";

    @override
    public void printMe()
    {
        System.out.println(me);
    }
}

public void doIt()
{
    new Son().printMe();
}

Approach 2: don't hide the field and initialize it in the constructor

class Dad
{
    protected static String me = "dad";

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    public Son()
    {
        me = "son";
    }
}

public void doIt()
{
    new Son().printMe();
}

Approach 3: use the static value to initialize a field in the constructor

class Dad
{
    private static String meInit = "Dad";

    protected String me;

    public Dad() 
    {
       me = meInit;
    }

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    private static String meInit = "son";

    public Son()
    {
        me = meInit;
    }

}

public void doIt()
{
    new Son().printMe();
}

Split string with delimiters in C

In the above example, there would be a way to return an array of null terminated strings (like you want) in place in the string. It would not make it possible to pass a literal string though, as it would have to be modified by the function:

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

char** str_split( char* str, char delim, int* numSplits )
{
    char** ret;
    int retLen;
    char* c;

    if ( ( str == NULL ) ||
        ( delim == '\0' ) )
    {
        /* Either of those will cause problems */
        ret = NULL;
        retLen = -1;
    }
    else
    {
        retLen = 0;
        c = str;

        /* Pre-calculate number of elements */
        do
        {
            if ( *c == delim )
            {
                retLen++;
            }

            c++;
        } while ( *c != '\0' );

        ret = malloc( ( retLen + 1 ) * sizeof( *ret ) );
        ret[retLen] = NULL;

        c = str;
        retLen = 1;
        ret[0] = str;

        do
        {
            if ( *c == delim )
            {
                ret[retLen++] = &c[1];
                *c = '\0';
            }

            c++;
        } while ( *c != '\0' );
    }

    if ( numSplits != NULL )
    {
        *numSplits = retLen;
    }

    return ret;
}

int main( int argc, char* argv[] )
{
    const char* str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";

    char* strCpy;
    char** split;
    int num;
    int i;

    strCpy = malloc( strlen( str ) * sizeof( *strCpy ) );
    strcpy( strCpy, str );

    split = str_split( strCpy, ',', &num );

    if ( split == NULL )
    {
        puts( "str_split returned NULL" );
    }
    else
    {
        printf( "%i Results: \n", num );

        for ( i = 0; i < num; i++ )
        {
            puts( split[i] );
        }
    }

    free( split );
    free( strCpy );

    return 0;
}

There is probably a neater way to do it, but you get the idea.

Select multiple columns in data.table by their numeric indices

It's a bit verbose, but i've gotten used to using the hidden .SD variable.

b<-data.table(a=1,b=2,c=3,d=4)
b[,.SD,.SDcols=c(1:2)]

It's a bit of a hassle, but you don't lose out on other data.table features (I don't think), so you should still be able to use other important functions like join tables etc.

Resolve conflicts using remote changes when pulling from Git remote

If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:

# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master

I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.

If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours merge strategy:

# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

How can I check whether a option already exist in select by JQuery

if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
  alert("option doesn't exist!");
}

Pandas: Return Hour from Datetime Column Directly

You can try this:

sales['time_hour'] = pd.to_datetime(sales['timestamp']).dt.hour

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

How to develop or migrate apps for iPhone 5 screen resolution?

There is a slight problem when testing on both iOS device and iOS Simulator. It appears that simulator (XCode 6.0.1) gives switched values for width and height in [[UIScreen mainScreen] bounds].size depending on a device orientation.

So this might be a problem when determinating the right physical screen size. This code helps also to distinct all 2014. iPhone model generations:

  • iPhone4s
  • iPhone5 (and iPhone5s)
  • iPhone6 (and iPhone6+)

It can also be easily changed to make the distinction between e.g. iPhone6 from iPhone6+.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    CGSize iOSDeviceScreenSize = [[UIScreen mainScreen] bounds].size;

    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone)
    {
        if (iOSDeviceScreenSize.width > 568 || // for iOS devices
            iOSDeviceScreenSize.height > 568) // for iOS simulator
        {   // iPhone 6 and iPhone 6+

            // Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone6
            storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone6" bundle:nil];

            NSLog(@"loaded iPhone6 Storyboard");
        }
        else if (iOSDeviceScreenSize.width == 568 || // for iOS devices
                 iOSDeviceScreenSize.height == 568) // for iOS simulator
        {   // iPhone 5 and iPod Touch 5th generation: 4 inch screen (diagonally measured)

            // Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone5
            storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone5" bundle:nil];

            NSLog(@"loaded iPhone5 Storyboard");
        }
        else
        {   // iPhone 3GS, 4, and 4S and iPod Touch 3rd and 4th generation: 3.5 inch screen (diagonally measured)

                // Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone4
            storyboard = [UIStoryboard story    boardWithName:@"MainStoryboard_iPhone" bundle:nil];

                NSLog(@"loaded iPhone4 Storyboard");
        }
    }
    else if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
    {   // The iOS device = iPad

        storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPadnew" bundle:nil];

        NSLog(@"loaded iPad Storyboard");
    }

    // rest my code
}

Bootstrap modal - close modal when "call to action" button is clicked

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

Why do package names often begin with "com"

  • com => domain
  • something => company name
  • something => Main package name

For example: com.paresh.mainpackage

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html

Save a file in json format using Notepad++

Just show file name extension from Windows Explorer, after applying the below steps, create a new file, and type your extension as .json

Open Folder Options by clicking the Start button Picture of the Start button, clicking Control Panel, clicking Appearance and Personalization, and then clicking Folder Options.

Click the View tab, and then, under Advanced settings, clear the Hide extensions for known file types check box, and then click OK

Reference

How to change the date format of a DateTimePicker in vb.net

Try this code it works:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
    MsgBox(CustomeDate.ToString)

    con.Open()

    dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)

    ds = New System.Data.DataSet
    dadap.Fill(ds)
    Dgview.DataSource = ds.Tables(0)
    con.Close()

Note : if u use dd for date representation it will return nothing while selecting 1 to 9 so use d for selection

'Date time format
'MMM     Three-letter month.
'ddd     Three-letter day of the week.
'd       Day of the month.
'HH      Two-digit hours on 24-hour scale.
'mm      Two-digit minutes.
'yyyy    Four-digit year.

The documentation contains a full list of the date formats.

html5 input for money/currency

I stumbled across this article looking for a similar answer. I read @vsync example Using javascript's Number.prototype.toLocaleString: and it appeared to work well. The only complaint I had was that if you had more than a single input type="currency" within your page it would only modify the first instance of it.

As he mentions in his comments it was only designed as an example for stackoverflow.

However, the example worked well for me and although I have little experience with JS I figured out how to modify it so that it will work with multiple input type="currency" on the page using the document.querySelectorAll rather than document.querySelector and adding a for loop.

I hope this can be useful for someone else. ( Credit for the bulk of the code is @vsync )

var currencyInput = document.querySelectorAll( 'input[type="currency"]' );

for ( var i = 0; i < currencyInput.length; i++ ) {

    var currency = 'GBP'
    onBlur( {
        target: currencyInput[ i ]
    } )

    currencyInput[ i ].addEventListener( 'focus', onFocus )
    currencyInput[ i ].addEventListener( 'blur', onBlur )

    function localStringToNumber( s ) {
        return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
    }

    function onFocus( e ) {
        var value = e.target.value;
        e.target.value = value ? localStringToNumber( value ) : ''
    }

    function onBlur( e ) {
        var value = e.target.value

        var options = {
            maximumFractionDigits: 2,
            currency: currency,
            style: "currency",
            currencyDisplay: "symbol"
        }

        e.target.value = ( value || value === 0 ) ?
            localStringToNumber( value ).toLocaleString( undefined, options ) :
            ''
    }
}

_x000D_
_x000D_
    var currencyInput = document.querySelectorAll( 'input[type="currency"]' );

    for ( var i = 0; i < currencyInput.length; i++ ) {

        var currency = 'GBP'
        onBlur( {
            target: currencyInput[ i ]
        } )

        currencyInput[ i ].addEventListener( 'focus', onFocus )
        currencyInput[ i ].addEventListener( 'blur', onBlur )

        function localStringToNumber( s ) {
            return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
        }

        function onFocus( e ) {
            var value = e.target.value;
            e.target.value = value ? localStringToNumber( value ) : ''
        }

        function onBlur( e ) {
            var value = e.target.value

            var options = {
                maximumFractionDigits: 2,
                currency: currency,
                style: "currency",
                currencyDisplay: "symbol"
            }

            e.target.value = ( value || value === 0 ) ?
                localStringToNumber( value ).toLocaleString( undefined, options ) :
                ''
        }
    }
_x000D_
.input_date {
    margin:1px 0px 50px 0px;
    font-family: 'Roboto', sans-serif;
    font-size: 18px;
    line-height: 1.5;
    color: #111;
    display: block;
    background: #ddd;
    height: 50px;
    border-radius: 5px;
    border: 2px solid #111111;
    padding: 0 20px 0 20px;
    width: 100px;
}
_x000D_
    <label for="cost_of_sale">Cost of Sale</label>
    <input class="input_date" type="currency" name="cost_of_sale" id="cost_of_sale" value="0.00">

    <label for="sales">Sales</label>
    <input class="input_date" type="currency" name="sales" id="sales" value="0.00">

     <label for="gm_pounds">GM Pounds</label>
     <input class="input_date" type="currency" name="gm_pounds" id="gm_pounds" value="0.00">
_x000D_
_x000D_
_x000D_

Responsive background image in div full width

When you use background-size: cover the background image will automatically be stretched to cover the entire container. Aspect ratio is maintained however, so you will always lose part of the image, unless the aspect ratio of the image and the element it is applied to are identical.

I see two ways you could solve this:

  • Do not maintain the aspect ratio of the image by setting background-size: 100% 100% This will also make the image cover the entire container, but the ratio will not be maintained. Disadvantage is that this distorts your image, and therefore may look very weird, depending on the image. With the image you are using in the fiddle, I think you could get away with it though.

  • You could also calculate and set the height of the element with javascript, based on its width, so it gets the same ratio as the image. This calculation would have to be done on load and on resize. It should be easy enough with a few lines of code (feel free to ask if you want an example). Disadvantage of this method is that your width may become very small (on mobile devices), and therfore the calculated height also, which may cause the content of the container to overflow. This could be solved by changing the size of the content as well or something, but it adds some complexity to the solution/

How do you check that a number is NaN in JavaScript?

So I see several responses to this,

But I just use:

function isNaN(x){
     return x == x && typeof x == 'number';
}

How to conditionally take action if FINDSTR fails to find a string

I presume you want to copy C:\OtherFolder\fileToCheck.bat to C:\MyFolder if the existing file in C:\MyFolder is either missing entirely, or if it is missing "stringToCheck".

FINDSTR sets ERRORLEVEL to 0 if the string is found, to 1 if it is not. It also sets errorlevel to 1 if the file is missing. It also prints out each line that matches. Since you are trying to use it as a condition, I presume you don't need or want to see any of the output. The 1st thing I would suggest is to redirect both the normal and error output to nul using >nul 2>&1.

Solution 1 (mostly the same as previous answers)

You can use IF ERRORRLEVEL N to check if the errorlevel is >= N. Or you can use IF NOT ERRORLEVEL N to check if errorlevel is < N. In your case you want the former.

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if errorlevel 1 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

Solution 2

You can test for a specific value of errorlevel by using %ERRORLEVEL%. You can probably check if the value is equal to 1, but it might be safer to check if the value is not equal to 0, since it is only set to 0 if the file exists and it contains the string.

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if not %errorlevel% == 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

or

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if %errorlevel% neq 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

Solution 3

There is a very compact syntax to conditionally execute a command based on the success or failure of the previous command: cmd1 && cmd2 || cmd3 which means execute cmd2 if cmd1 was successful (errorlevel=0), else execute cmd3 if cmd1 failed (errorlevel<>0). You can use && alone, or || alone. All the commands need to be on the same line. If you need to conditionally execute multiple commands you can use multiple lines by adding parentheses

cmd1 && (
   cmd2
   cmd3
) || (
   cmd4
   cmd5
)

So for your case, all you need is

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1 || xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

But beware - the || will respond to the return code of the last command executed. In my earlier pseudo code the || will obviously fire if cmd1 fails, but it will also fire if cmd1 succeeds but then cmd3 fails.

So if your success block ends with a command that may fail, then you should append a harmless command that is guaranteed to succeed. I like to use (CALL ), which is harmless, and always succeeds. It also is handy that it sets the ERRORLEVEL to 0. There is a corollary (CALL) that always fails and sets ERRORLEVEL to 1.

Difference between System.DateTime.Now and System.DateTime.Today

DateTime dt = new DateTime();// gives 01/01/0001 12:00:00 AM
DateTime dt = DateTime.Now;// gives today date with current time
DateTime dt = DateTime.Today;// gives today date and 12:00:00 AM time

How can I explicitly free memory in Python?

The del statement might be of use, but IIRC it isn't guaranteed to free the memory. The docs are here ... and a why it isn't released is here.

I have heard people on Linux and Unix-type systems forking a python process to do some work, getting results and then killing it.

This article has notes on the Python garbage collector, but I think lack of memory control is the downside to managed memory

Removing elements from array Ruby

a = [1,1,1,2,2,3]
a.slice!(0) # remove first index
a.slice!(-1) # remove last index
# a = [1,1,2,2] as desired

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none if the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available.

private boolean isNetworkAvailable() {
     ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
     return activeNetworkInfo != null; 
}

You will also need:

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Networks issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

getActiveNetworkInfo() shouldn't never give null. I don't know what they were thinking when they came up with that. It should give you an object always.

jQuery multiple events to trigger the same function

$("element").on("event1 event2 event..n", function() {
   //execution
});

This tutorial is about handling multiple events.

Converting a Pandas GroupBy output from Series to DataFrame

I want to slightly change the answer given by Wes, because version 0.16.2 requires as_index=False. If you don't set it, you get an empty dataframe.

Source:

Aggregation functions will not return the groups that you are aggregating over if they are named columns, when as_index=True, the default. The grouped columns will be the indices of the returned object.

Passing as_index=False will return the groups that you are aggregating over, if they are named columns.

Aggregating functions are ones that reduce the dimension of the returned objects, for example: mean, sum, size, count, std, var, sem, describe, first, last, nth, min, max. This is what happens when you do for example DataFrame.sum() and get back a Series.

nth can act as a reducer or a filter, see here.

import pandas as pd

df1 = pd.DataFrame({"Name":["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"],
                    "City":["Seattle","Seattle","Portland","Seattle","Seattle","Portland"]})
print df1
#
#       City     Name
#0   Seattle    Alice
#1   Seattle      Bob
#2  Portland  Mallory
#3   Seattle  Mallory
#4   Seattle      Bob
#5  Portland  Mallory
#
g1 = df1.groupby(["Name", "City"], as_index=False).count()
print g1
#
#                  City  Name
#Name    City
#Alice   Seattle      1     1
#Bob     Seattle      2     2
#Mallory Portland     2     2
#        Seattle      1     1
#

EDIT:

In version 0.17.1 and later you can use subset in count and reset_index with parameter name in size:

print df1.groupby(["Name", "City"], as_index=False ).count()
#IndexError: list index out of range

print df1.groupby(["Name", "City"]).count()
#Empty DataFrame
#Columns: []
#Index: [(Alice, Seattle), (Bob, Seattle), (Mallory, Portland), (Mallory, Seattle)]

print df1.groupby(["Name", "City"])[['Name','City']].count()
#                  Name  City
#Name    City                
#Alice   Seattle      1     1
#Bob     Seattle      2     2
#Mallory Portland     2     2
#        Seattle      1     1

print df1.groupby(["Name", "City"]).size().reset_index(name='count')
#      Name      City  count
#0    Alice   Seattle      1
#1      Bob   Seattle      2
#2  Mallory  Portland      2
#3  Mallory   Seattle      1

The difference between count and size is that size counts NaN values while count does not.

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

I just added custom headers to the Web.config and it worked like a charm.

On configuration - system.webServer:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>

I have the front end app and the backend on the same solution. For this to work, I need to set the web services project (Backend) as the default for this to work.

I was using ReST, haven't tried with anything else.

Fastest JavaScript summation

For your specific case, just use the reduce method of Arrays:

var sumArray = function() {
    // Use one adding function rather than create a new one each
    // time sumArray is called
    function add(a, b) {
        return a + b;
    }

    return function(arr) {
        return arr.reduce(add);
    };
}();

alert( sumArray([2, 3, 4]) );

Install Application programmatically on Android

UpdateNode provides an API for Android to install APK packages from inside another App.

You can just define your Update online and integrate the API into your App - that's it.
Currently the API is in Beta state, but you can already do some tests yourself.

Beside that, UpdateNode offers also displaying messages though the system - pretty useful if you want to tell something important to your users.

I am part of the client dev team and am using at least the message functionality for my own Android App.

See here a description how to integrate the API

Creating a UIImage from a UIColor to use as a background image for UIButton

Your code works fine. You can verify the RGB colors with Iconfactory's xScope. Just compare it to [UIColor whiteColor].

How to compare timestamp dates with date-only parameter in MySQL?

 WHERE cast(timestamp as date) = '2012-05-05'