Programs & Examples On #Rtmp

The Real-Time Messaging Protocol (RTMP) is used for streaming multimedia content across a TCP/IP network.

Install pip in docker

You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json with the dns key, as

{
    "dns": ["your_dns_address", "8.8.8.8"]
}

In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.

Before proceeding, save daemon.json and restart the docker service.

sudo service docker restart

Once fixed, retry to run the build command.

Solving sslv3 alert handshake failure when trying to use a client certificate

What SSL private key should be sent along with the client certificate?

None of them :)

One of the appealing things about client certificates is it does not do dumb things, like transmit a secret (like a password), in the plain text to a server (HTTP basic_auth). The password is still used to unlock the key for the client certificate, its just not used directly to during exchange or tp authenticate the client.

Instead, the client chooses a temporary, random key for that session. The client then signs the temporary, random key with his cert and sends it to the server (some hand waiving). If a bad guy intercepts anything, its random so it can't be used in the future. It can't even be used for a second run of the protocol with the server because the server will select a new, random value, too.


Fails with: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure

Use TLS 1.0 and above; and use Server Name Indication.

You have not provided any code, so its not clear to me how to tell you what to do. Instead, here's the OpenSSL command line to test it:

openssl s_client -connect www.example.com:443 -tls1 -servername www.example.com \
    -cert mycert.pem -key mykey.pem -CAfile <certificate-authority-for-service>.pem

You can also use -CAfile to avoid the “verify error:num=20”. See, for example, “verify error:num=20” when connecting to gateway.sandbox.push.apple.com.

Problems installing the devtools package

CentOS 7:

I tried solutions in this post

sudo yum -y install libcurl libcurl-devel
sudo yum -y install openssl-devel

but wasn't enough.

Checking R error in Console gave me the anwser. In my case it was lacking libxml-2.0 below (and Console printed an explanation with package name to different Linux versions and other possible R configs)

sudo yum -y install libxml2-devel

R not finding package even after package installation

Do .libPaths(), close every R runing, check in the first directory, remove the zoo package restart R and install zoo again. Of course you need to have sufficient rights.

How to dump raw RTSP stream to file?

If you are reencoding in your ffmpeg command line, that may be the reason why it is CPU intensive. You need to simply copy the streams to the single container. Since I do not have your command line I cannot suggest a specific improvement here. Your acodec and vcodec should be set to copy is all I can say.

EDIT: On seeing your command line and given you have already tried it, this is for the benefit of others who come across the same question. The command:

ffmpeg -i rtsp://@192.168.241.1:62156 -acodec copy -vcodec copy c:/abc.mp4

will not do transcoding and dump the file for you in an mp4. Of course this is assuming the streamed contents are compatible with an mp4 (which in all probability they are).

Using the rJava package on Win7 64 bit with R

I had some trouble determining the Java package that was installed when I ran into this problem, since the previous answers didn't exactly work for me. To sort it out, I typed:

Sys.setenv(JAVA_HOME="C:/Program Files/Java/

and then hit tab and the two suggested directories were "jre1.8.0_31/" and "jre7/"

Jre7 didn't solve my problem, but jre1.8.0_31/ did. Final answer was running (before library(rJava)):

Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_31/")

I'm using 64-bit Windows 8.1 Hope this helps someone else.

Update:

Check your version to determine what X should be (mine has changed several times since this post):

Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_x/")

HTML5 live streaming

Use ffmpeg + ffserver. It works!!! You can get a config file for ffserver from ffmpeg.org and accordingly set the values.

Difference between malloc and calloc?

Both malloc and calloc allocate memory, but calloc initialises all the bits to zero whereas malloc doesn't.

Calloc could be said to be equivalent to malloc + memset with 0 (where memset sets the specified bits of memory to zero).

So if initialization to zero is not necessary, then using malloc could be faster.

SQL Server query to find all permissions/access for all users in a database

From SQL Server 2005 on, you can use system views for that. For example, this query lists all users in a database, with their rights:

select  princ.name
,       princ.type_desc
,       perm.permission_name
,       perm.state_desc
,       perm.class_desc
,       object_name(perm.major_id)
from    sys.database_principals princ
left join
        sys.database_permissions perm
on      perm.grantee_principal_id = princ.principal_id

Be aware that a user can have rights through a role as well. For example, the db_data_reader role grants select rights on most objects.

How to convert a full date to a short date in javascript?

I was able to do that with :

var dateTest = new Date("04/04/2013");
dateTest.toLocaleString().substring(0,dateTest.toLocaleString().indexOf(' '))

the 04/04/2013 is just for testing, replace with your Date Object.

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

R command for setting working directory to source file location in Rstudio

The here package provides the here() function, which returns your project root directory based on some heuristics.

Not the perfect solution, since it doesn't find the location of the script, but it suffices for some purposes so I thought I'd put it here.

Currently running queries in SQL Server

here is what you need to install the SQL profiler http://msdn.microsoft.com/en-us/library/bb500441.aspx. However, i would suggest you to read through this one http://blog.sqlauthority.com/2009/08/03/sql-server-introduction-to-sql-server-2008-profiler-2/ if you are looking to do it on your Production Environment. There is another better way to look at the queries watch this one and see if it helps http://www.youtube.com/watch?v=vvziPI5OQyE

How do I select child elements of any depth using XPath?

Also, you can do it with css selectors:

form#myform input[type='submit']

space beween elements in css elector means searching input[type='submit'] that elements at any depth of parent form#myform element

What is the Ruby <=> (spaceship) operator?

I will explain with simple example

  1. [1,3,2] <=> [2,2,2]

    Ruby will start comparing each element of both array from left hand side. 1 for left array is smaller than 2 of right array. Hence left array is smaller than right array. Output will be -1.

  2. [2,3,2] <=> [2,2,2]

    As above it will first compare first element which are equal then it will compare second element, in this case second element of left array is greater hence output is 1.

Angles between two n-dimensional vectors in Python

Using numpy (highly recommended), you would do:

from numpy import (array, dot, arccos, clip)
from numpy.linalg import norm

u = array([1.,2,3,4])
v = ...
c = dot(u,v)/norm(u)/norm(v) # -> cosine of the angle
angle = arccos(clip(c, -1, 1)) # if you really want the angle

Laravel: PDOException: could not find driver

Solution 1:

1. php -v

Output: PHP 7.3.11-1+ubuntu16.04.1+deb.sury.org+1 (cli)

2. sudo apt-get install php7.3-mysql

Solution 2:

Check your DB credentials like DB Name, DB User, DB Password

How do I access previous promise results in a .then() chain?

Nesting (and) closures

Using closures for maintaining the scope of variables (in our case, the success callback function parameters) is the natural JavaScript solution. With promises, we can arbitrarily nest and flatten .then() callbacks - they are semantically equivalent, except for the scope of the inner one.

function getExample() {
    return promiseA(…).then(function(resultA) {
        // some processing
        return promiseB(…).then(function(resultB) {
            // more processing
            return // something using both resultA and resultB;
        });
    });
}

Of course, this is building an indentation pyramid. If indentation is getting too large, you still can apply the old tools to counter the pyramid of doom: modularize, use extra named functions, and flatten the promise chain as soon as you don't need a variable any more.
In theory, you can always avoid more than two levels of nesting (by making all closures explicit), in practise use as many as are reasonable.

function getExample() {
    // preprocessing
    return promiseA(…).then(makeAhandler(…));
}
function makeAhandler(…)
    return function(resultA) {
        // some processing
        return promiseB(…).then(makeBhandler(resultA, …));
    };
}
function makeBhandler(resultA, …) {
    return function(resultB) {
        // more processing
        return // anything that uses the variables in scope
    };
}

You can also use helper functions for this kind of partial application, like _.partial from Underscore/lodash or the native .bind() method, to further decrease indentation:

function getExample() {
    // preprocessing
    return promiseA(…).then(handlerA);
}
function handlerA(resultA) {
    // some processing
    return promiseB(…).then(handlerB.bind(null, resultA));
}
function handlerB(resultA, resultB) {
    // more processing
    return // anything that uses resultA and resultB
}

How to store file name in database, with other info while uploading image to server using PHP?

If you want to input more data into the form, you simply access the submitted data through $_POST.

If you have

<input type="text" name="firstname" />

you access it with

$firstname = $_POST["firstname"];

You could then update your query line to read

mysql_query("INSERT INTO dbProfiles (photo,firstname)
             VALUES('{$filename}','{$firstname}')");

Note: Always filter and sanitize your data.

Split string on the first white space occurrence

Just split the string into an array and glue the parts you need together. This approach is very flexible, it works in many situations and it is easy to reason about. Plus you only need one function call.

arr = str.split(' ');             // ["72", "tocirah", "sneab"]
strA = arr[0];                    // "72"
strB = arr[1] + ' ' + arr[2];     // "tocirah sneab"

Alternatively, if you want to cherry-pick what you need directly from the string you could do something like this:

strA = str.split(' ')[0];                    // "72";
strB = str.slice(strA.length + 1);           // "tocirah sneab"

Or like this:

strA = str.split(' ')[0];                    // "72";
strB = str.split(' ').splice(1).join(' ');   // "tocirah sneab"

However I suggest the first example.

Working demo: jsbin

How do I pipe a subprocess call to a text file?

If you want to write the output to a file you can use the stdout-argument of subprocess.call.

It takes None, subprocess.PIPE, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.

You need to open a file with something like open and pass the object or file descriptor integer to call:

f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=f)

I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

How to Lock the data in a cell in excel using vba

You can first choose which cells you don't want to be protected (to be user-editable) by setting the Locked status of them to False:

Worksheets("Sheet1").Range("B2:C3").Locked = False

Then, you can protect the sheet, and all the other cells will be protected. The code to do this, and still allow your VBA code to modify the cells is:

Worksheets("Sheet1").Protect UserInterfaceOnly:=True

or

Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)

CSS to stop text wrapping under image

For those who want some background info, here's a short article explaining why overflow: hidden works. It has to do with the so-called block formatting context. This is part of W3C's spec (ie is not a hack) and is basically the region occupied by an element with a block-type flow.

Every time it is applied, overflow: hidden creates a new block formatting context. But it's not the only property capable of triggering that behaviour. Quoting a presentation by Fiona Chan from Sydney Web Apps Group:

  • float: left / right
  • overflow: hidden / auto / scroll
  • display: table-cell and any table-related values / inline-block
  • position: absolute / fixed

git pull fails "unable to resolve reference" "unable to update local ref"

I was able to work with

git remote update --prune

Box shadow in IE7 and IE8

in ie8 you can try

-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0')";
 filter: progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0');

caveat: in ie8 you loose smooth fonts for some reason, they will look ragged

Abort a Git Merge

If you do "git status" while having a merge conflict, the first thing git shows you is how to abort the merge.

output of git status while having a merge conflict

How can I create my own comparator for a map?

Specify the type of the pointer to your comparison function as the 3rd type into the map, and provide the function pointer to the map constructor:
map<keyType, valueType, typeOfPointerToFunction> mapName(pointerToComparisonFunction);

Take a look at the example below for providing a comparison function to a map, with vector iterator as key and int as value.

#include "headers.h"

bool int_vector_iter_comp(const vector<int>::iterator iter1, const vector<int>::iterator iter2) {
    return *iter1 < *iter2;
}

int main() {
    // Without providing custom comparison function
    map<vector<int>::iterator, int> default_comparison;

    // Providing custom comparison function
    // Basic version
    map<vector<int>::iterator, int,
        bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2)>
        basic(int_vector_iter_comp);

    // use decltype
    map<vector<int>::iterator, int, decltype(int_vector_iter_comp)*> with_decltype(&int_vector_iter_comp);

    // Use type alias or using
    typedef bool my_predicate(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
    map<vector<int>::iterator, int, my_predicate*> with_typedef(&int_vector_iter_comp);

    using my_predicate_pointer_type = bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
    map<vector<int>::iterator, int, my_predicate_pointer_type> with_using(&int_vector_iter_comp);


    // Testing 
    vector<int> v = {1, 2, 3};

    default_comparison.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
    default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
    default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
    default_comparison.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));

    cout << "size: " << default_comparison.size() << endl;
    for (auto& p : default_comparison) {
        cout << *(p.first) << ": " << p.second << endl;
    }

    basic.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
    basic.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
    basic.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
    basic.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));

    cout << "size: " << basic.size() << endl;
    for (auto& p : basic) {
        cout << *(p.first) << ": " << p.second << endl;
    }

    with_decltype.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
    with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
    with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
    with_decltype.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));

    cout << "size: " << with_decltype.size() << endl;
    for (auto& p : with_decltype) {
        cout << *(p.first) << ": " << p.second << endl;
    }

    with_typedef.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
    with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
    with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
    with_typedef.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));

    cout << "size: " << with_typedef.size() << endl;
    for (auto& p : with_typedef) {
        cout << *(p.first) << ": " << p.second << endl;
    }
}

Regex - Does not contain certain Characters

Here you go:

^[^<>]*$

This will test for string that has no < and no >

If you want to test for a string that may have < and >, but must also have something other you should use just

[^<>] (or ^.*[^<>].*$)

Where [<>] means any of < or > and [^<>] means any that is not of < or >.

And of course the mandatory link.

difference between primary key and unique key

A primary key must be unique.

A unique key does not have to be the primary key - see candidate key.

That is, there may be more than one combination of columns on a table that can uniquely identify a row - only one of these can be selected as the primary key. The others, though unique are candidate keys.

Sequence Permission in Oracle

Just another bit. in some case i found no result on all_tab_privs! i found it indeed on dba_tab_privs. I think so that this last table is better to check for any grant available on an object (in case of impact analysis). The statement becomes:

    select * from dba_tab_privs where table_name = 'sequence_name';

What is the maximum number of characters that nvarchar(MAX) will hold?

Max. capacity is 2 gigabytes of space - so you're looking at just over 1 billion 2-byte characters that will fit into a NVARCHAR(MAX) field.

Using the other answer's more detailed numbers, you should be able to store

(2 ^ 31 - 1 - 2) / 2 = 1'073'741'822 double-byte characters

1 billion, 73 million, 741 thousand and 822 characters to be precise

in your NVARCHAR(MAX) column (unfortunately, that last half character is wasted...)

Update: as @MartinMulder pointed out: any variable length character column also has a 2 byte overhead for storing the actual length - so I needed to subtract two more bytes from the 2 ^ 31 - 1 length I had previously stipulated - thus you can store 1 Unicode character less than I had claimed before.

How to select a drop-down menu value with Selenium using Python?

  1. List item

public class ListBoxMultiple {

public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
    WebDriver driver=new ChromeDriver();
    driver.get("file:///C:/Users/Amitabh/Desktop/hotel2.html");//open the website
    driver.manage().window().maximize();


    WebElement hotel = driver.findElement(By.id("maarya"));//get the element

    Select sel=new Select(hotel);//for handling list box
    //isMultiple
    if(sel.isMultiple()){
        System.out.println("it is multi select list");
    }
    else{
        System.out.println("it is single select list");
    }
    //select option
    sel.selectByIndex(1);// you can select by index values
    sel.selectByValue("p");//you can select by value
    sel.selectByVisibleText("Fish");// you can also select by visible text of the options
    //deselect option but this is possible only in case of multiple lists
    Thread.sleep(1000);
    sel.deselectByIndex(1);
    sel.deselectAll();

    //getOptions
    List<WebElement> options = sel.getOptions();

    int count=options.size();
    System.out.println("Total options: "+count);

    for(WebElement opt:options){ // getting text of every elements
        String text=opt.getText();
        System.out.println(text);
        }

    //select all options
    for(int i=0;i<count;i++){
        sel.selectByIndex(i);
        Thread.sleep(1000);
    }

    driver.quit();

}

}

What is the time complexity of indexing, inserting and removing from common data structures?

I guess I will start you off with the time complexity of a linked list:

Indexing---->O(n)
Inserting / Deleting at end---->O(1) or O(n)
Inserting / Deleting in middle--->O(1) with iterator O(n) with out

The time complexity for the Inserting at the end depends if you have the location of the last node, if you do, it would be O(1) other wise you will have to search through the linked list and the time complexity would jump to O(n).

Can two applications listen to the same port?

When you create a TCP connection, you ask to connect to a specific TCP address, which is a combination of an IP address (v4 or v6, depending on the protocol you're using) and a port.

When a server listens for connections, it can inform the kernel that it would like to listen to a specific IP address and port, i.e., one TCP address, or on the same port on each of the host's IP addresses (usually specified with IP address 0.0.0.0), which is effectively listening on a lot of different "TCP addresses" (e.g., 192.168.1.10:8000, 127.0.0.1:8000, etc.)

No, you can't have two applications listening on the same "TCP address," because when a message comes in, how would the kernel know to which application to give the message?

However, you in most operating systems you can set up several IP addresses on a single interface (e.g., if you have 192.168.1.10 on an interface, you could also set up 192.168.1.11, if nobody else on the network is using it), and in those cases you could have separate applications listening on port 8000 on each of those two IP addresses.

How to use Bootstrap 4 in ASP.NET Core

Unfortunately, you're going to have a hard time using NuGet to install Bootstrap (or most other JavaScript/CSS frameworks) on a .NET Core project. If you look at the NuGet install it tells you it is incompatible:

enter image description here

if you must know where local packages dependencies are, they are now in your local profile directory. i.e. %userprofile%\.nuget\packages\bootstrap\4.0.0\content\Scripts.

However, I suggest switching to npm, or bower - like in Saineshwar's answer.

How to confirm RedHat Enterprise Linux version?

Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:

rpm -qia '*release*'

Fix CSS hover on iPhone/iPad/iPod

Old Post I know however I successfully used onlclick="" when populating a table with JSON data. Tried many other options / scripts etc before, nothing worked. Will attempt this approach elsewhere. Thanks @Dan Morris .. from 2013!

     function append_json(data) {
     var table=document.getElementById('gable');
     data.forEach(function(object) {
         var tr=document.createElement('tr');
         tr.innerHTML='<td onclick="">' + object.COUNTRY + '</td>' + '<td onclick="">' + object.PoD + '</td>' + '<td onclick="">' + object.BALANCE + '</td>' + '<td onclick="">' + object.DATE + '</td>';
         table.appendChild(tr);
     }
     );

Regex to get the words after matching string

The following should work for you:

[\n\r].*Object Name:\s*([^\n\r]*)

Working example

Your desired match will be in capture group 1.


[\n\r][ \t]*Object Name:[ \t]*([^\n\r]*)

Would be similar but not allow for things such as " blah Object Name: blah" and also make sure that not to capture the next line if there is no actual content after "Object Name:"

Cron and virtualenv

You should be able to do this by using the python in your virtual environment:

/home/my/virtual/bin/python /home/my/project/manage.py command arg

EDIT: If your django project isn't in the PYTHONPATH, then you'll need to switch to the right directory:

cd /home/my/project && /home/my/virtual/bin/python ...

You can also try to log the failure from cron:

cd /home/my/project && /home/my/virtual/bin/python /home/my/project/manage.py > /tmp/cronlog.txt 2>&1

Another thing to try is to make the same change in your manage.py script at the very top:

#!/home/my/virtual/bin/python

java.util.NoSuchElementException: No line found

with Scanner you need to check if there is a next line with hasNextLine()

so the loop becomes

while(sc.hasNextLine()){
    str=sc.nextLine();
    //...
}

it's readers that return null on EOF

ofcourse in this piece of code this is dependent on whether the input is properly formatted

MySQL: Enable LOAD DATA LOCAL INFILE

I solved this problem on MySQL 8.0.11 with the mysql terminal command:

SET GLOBAL local_infile = true;

I mean I logged in first with the usual:

mysql -u user -p*

After that you can see the status with the command:

SHOW GLOBAL VARIABLES LIKE 'local_infile';

It should be ON. I will not be writing about security issued with loading local files into database here.

What does enctype='multipart/form-data' mean?

The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

The enctype attribute can be used only if method="post".

No characters are encoded. This value is required when you are using forms that have a file upload control

From W3Schools

How do I perform an insert and return inserted identity with Dapper?

Not sure if it was because I'm working against SQL 2000 or not but I had to do this to get it to work.

string sql = "DECLARE @ID int; " +
             "INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff); " +
             "SET @ID = SCOPE_IDENTITY(); " +
             "SELECT @ID";

var id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();

Authentication failed because remote party has closed the transport stream

I ran into the same error message while using the ChargifyNET.dll to communicate with the Chargify API. Adding chargify.ProtocolType = SecurityProtocolType.Tls12; to the configuration solved the problem for me.

Here is the complete code snippet:

public ChargifyConnect GetChargifyConnect()
{
    var chargify = new ChargifyConnect();
    chargify.apiKey = ConfigurationManager.AppSettings["Chargify.apiKey"];
    chargify.Password = ConfigurationManager.AppSettings["Chargify.apiPassword"];
    chargify.URL = ConfigurationManager.AppSettings["Chargify.url"];

    // Without this an error will be thrown.
    chargify.ProtocolType = SecurityProtocolType.Tls12;

    return chargify;
}

PHP Email sending BCC

You were setting BCC but then overwriting the variable with the FROM

$to = "[email protected]";
     $subject .= "".$emailSubject."";
 $headers .= "Bcc: ".$emailList."\r\n";
 $headers .= "From: [email protected]\r\n" .
     "X-Mailer: php";
     $headers .= "MIME-Version: 1.0\r\n";
     $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 $message = '<html><body>';
 $message .= 'THE MESSAGE FROM THE FORM';

     if (mail($to, $subject, $message, $headers)) {
     $sent = "Your email was sent!";
     } else {
      $sent = ("Error sending email.");
     }

In Oracle SQL: How do you insert the current date + time into a table?

You may try with below query :

INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );

To view the result of it:

SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss') 
FROM errortable 
    WHERE table1id = 1083;

What does O(log n) mean exactly?

O(log n) is a bit misleading, more precisely it's O(log2 n), i.e. (logarithm with base 2).

The height of a balanced binary tree is O(log2 n), since every node has two (note the "two" as in log2 n) child nodes. So, a tree with n nodes has a height of log2 n.

Another example is binary search, which has a running time of O(log2 n) because at every step you divide the search space by 2.

How to link html pages in same or different folders?

Also, this will go up a directory and then back down to another subfolder.

<a href = "../subfolder/page.html">link</a>

To go up multiple directories you can do this.

<a href = "../../page.html">link</a>

To go the root, I use this

<a href = "~/page.html">link</a>

JavaScript OOP in NodeJS: how?

If you are working on your own, and you want the closest thing to OOP as you would find in Java or C# or C++, see the javascript library, CrxOop. CrxOop provides syntax somewhat familiar to Java developers.

Just be careful, Java's OOP is not the same as that found in Javascript. To get the same behavior as in Java, use CrxOop's classes, not CrxOop's structures, and make sure all your methods are virtual. An example of the syntax is,

crx_registerClass("ExampleClass", 
{ 
    "VERBOSE": 1, 

    "public var publicVar": 5, 
    "private var privateVar": 7, 

    "public virtual function publicVirtualFunction": function(x) 
    { 
        this.publicVar1 = x;
        console.log("publicVirtualFunction"); 
    }, 

    "private virtual function privatePureVirtualFunction": 0, 

    "protected virtual final function protectedVirtualFinalFunction": function() 
    { 
        console.log("protectedVirtualFinalFunction"); 
    }
}); 

crx_registerClass("ExampleSubClass", 
{ 
    VERBOSE: 1, 
    EXTENDS: "ExampleClass", 

    "public var publicVar": 2, 

    "private virtual function privatePureVirtualFunction": function(x) 
    { 
        this.PARENT.CONSTRUCT(pA);
        console.log("ExampleSubClass::privatePureVirtualFunction"); 
    } 
}); 

var gExampleSubClass = crx_new("ExampleSubClass", 4);

console.log(gExampleSubClass.publicVar);
console.log(gExampleSubClass.CAST("ExampleClass").publicVar);

The code is pure javascript, no transpiling. The example is taken from a number of examples from the official documentation.

Generating a list of pages (not posts) without the index file

I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:

<ul> {% for page in site.pages %}     {% if page.title != 'index' %}     <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li>     {% endif %} {% endfor %} </ul> 

Convert web page to image

You could use imagemagick and write a script that fires everytime you load a webpage.

How many files can I put in a directory?

I'm working on a similar problem right now. We have a hierarchichal directory structure and use image ids as filenames. For example, an image with id=1234567 is placed in

..../45/67/1234567_<...>.jpg

using last 4 digits to determine where the file goes.

With a few thousand images, you could use a one-level hierarchy. Our sysadmin suggested no more than couple of thousand files in any given directory (ext3) for efficiency / backup / whatever other reasons he had in mind.

How do I do an insert with DATETIME now inside of SQL server mgmt studioÜ

Just use GETDATE() or GETUTCDATE() (if you want to get the "universal" UTC time, instead of your local server's time-zone related time).

INSERT INTO [Business]
           ([IsDeleted]
           ,[FirstName]
           ,[LastName]
           ,[LastUpdated]
           ,[LastUpdatedBy])
     VALUES
           (0, 'Joe', 'Thomas', 
           GETDATE(),  <LastUpdatedBy, nvarchar(50),>)

ImportError: DLL load failed: The specified module could not be found

I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fixed the missing DLLs.

I find it better and easier than downloading and pasting DLLs.

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

A solve this adding in the option defaultURL the path my application

<forms loginUrl="/Users/Login" protection="All" timeout="2880" name="001WVCookie" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="/Home/Index" cookieless="UseCookies" enableCrossAppRedirects="false" />

Setting a max character length in CSS

With Chrome you can set the number of lines displayed with "-webkit-line-clamp" :

     display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;  /* Number of lines displayed before it truncate */
     overflow: hidden;

So for me it is to use in an extension so it is perfect, more information here: https://medium.com/mofed/css-line-clamp-the-good-the-bad-and-the-straight-up-broken-865413f16e5

How to get root directory in yii2

If you want to get the root directory of your yii2 project use, assuming that the name of your project is project_app you'll need to use:

echo Yii::getAlias('@app');

on windows you'd see "C:\dir\to\project_app"

on linux you'll get "/var/www/dir/to/your/project_app"

I was formally using:

echo Yii::getAlias('@webroot').'/..';

I hope this helps someone

how to create Socket connection in Android?

Socket connections in Android are the same as in Java: http://www.oracle.com/technetwork/java/socket-140484.html

Things you need to be aware of:

  1. If phone goes to sleep your app will no longer execute, so socket will eventually timeout. You can prevent this with wake lock. This will eat devices battery tremendously - I know I wouldn't use that app.
  2. If you do this constantly, even when your app is not active, then you need to use Service.
  3. Activities and Services can be killed off by OS at any time, especially if they are part of an inactive app.

Take a look at AlarmManager, if you need scheduled execution of your code.

Do you need to run your code and receive data even if user does not use the app any more (i.e. app is inactive)?

Execute a file with arguments in Python shell

execfile runs a Python file, but by loading it, not as a script. You can only pass in variable bindings, not arguments.

If you want to run a program from within Python, use subprocess.call. E.g.

import subprocess
subprocess.call(['./abc.py', arg1, arg2])

Remove tracking branches no longer on remote

Drawing heavily from a number of other answers here, I've ended up with the following (git 2.13 and above only, I believe), which should work on any UNIX-like shell:

git for-each-ref --shell --format='ref=%(if:equals=[gone])%(upstream:track)%(then)%(refname)%(end)' refs/heads | while read entry; do eval "$entry"; [ ! -z "$ref" ] && git update-ref -d "$ref" && echo "deleted $ref"; done

This notably uses for-each-ref instead of branch (as branch is a "porcelain" command designed for human-readable output, not machine-processing) and uses its --shell argument to get properly escaped output (this allows us to not worry about any character in the ref name).

What is the difference between a pandas Series and a single-column DataFrame?

Quoting the Pandas docs

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure.

So, the Series is the data structure for a single column of a DataFrame, not only conceptually, but literally, i.e. the data in a DataFrame is actually stored in memory as a collection of Series.

Analogously: We need both lists and matrices, because matrices are built with lists. Single row matricies, while equivalent to lists in functionality still cannot exist without the list(s) they're composed of.

They both have extremely similar APIs, but you'll find that DataFrame methods always cater to the possibility that you have more than one column. And, of course, you can always add another Series (or equivalent object) to a DataFrame, while adding a Series to another Series involves creating a DataFrame.

Performance of Java matrix math libraries?

We have used COLT for some pretty large serious financial calculations and have been very happy with it. In our heavily profiled code we have almost never had to replace a COLT implementation with one of our own.

In their own testing (obviously not independent) I think they claim within a factor of 2 of the Intel hand-optimised assembler routines. The trick to using it well is making sure that you understand their design philosophy, and avoid extraneous object allocation.

Is it necessary to use # for creating temp tables in SQL server?

Yes. You need to prefix the table name with "#" (hash) to create temporary tables.

If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.

"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.

Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005

If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.

They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.

DECLARE @ItemBack1 TABLE
(
 column1 int,
 column2 int,
 someInt int,
 someVarChar nvarchar(50)
);

INSERT INTO @ItemBack1
SELECT column1, 
       column2, 
       someInt, 
       someVarChar 
  FROM table2
 WHERE table2.ID = 7;

More Info on Table Variables: http://odetocode.com/articles/365.aspx

How to check if directory exists in %PATH%?

Just to elaborate on Heyvoon's (2015.06.08) response using Powershell, this simple Powershell script should give you detail on %path%

$env:Path -split ";" | % {"$(test-path $_);$_"}

generating this kind of output which you can independently verify

True;C:\WINDOWS
True;C:\WINDOWS\system32
True;C:\WINDOWS\System32\Wbem
False;C:windows\System32\windowsPowerShell\v1.0\
False;C:\Program Files (x86)\Java\jre7\bin

to reassemble for updating Path:

$x=$null;foreach ($t in ($env:Path -split ";") ) {if (test-path $t) {$x+=$t+";"}};$x

How to set focus on input field?

A simple one that works well with modals:

.directive('focusMeNow', ['$timeout', function ($timeout)
{
    return {
        restrict: 'A',

        link: function (scope, element, attrs)
        {


            $timeout(function ()
            {
                element[0].focus();
            });



        }
    };
}])

Example

<input ng-model="your.value" focus-me-now />

send mail from linux terminal in one line

echo "Subject: test" | /usr/sbin/sendmail [email protected]

This enables you to do it within one command line without having to echo a text file. This answer builds on top of @mti2935's answer. So credit goes there.

Where does Vagrant download its .box files to?

To change the Path, you can set a new Path to an Enviroment-Variable named: VAGRANT_HOME

export VAGRANT_HOME=my/new/path/goes/here/

Thats maybe nice if you want to have those vagrant-Images on another HDD.

More Information here in the Documentations: http://docs.vagrantup.com/v2/other/environmental-variables.html

Why is there an unexplainable gap between these inline-block div elements?

Found a solution not involving Flex, because Flex doesn't work in older Browsers. Example:

.container {
    display:block;
    position:relative;
    height:150px;
    width:1024px;
    margin:0 auto;
    padding:0px;
    border:0px;
    background:#ececec;
    margin-bottom:10px;
    text-align:justify;
    box-sizing:border-box;
    white-space:nowrap;
    font-size:0pt;
    letter-spacing:-1em;
}

.cols {
    display:inline-block;
    position:relative;
    width:32%;
    height:100%;
    margin:0 auto;
    margin-right:2%;
    border:0px;
    background:lightgreen;  
    box-sizing:border-box;
    padding:10px;
    font-size:10pt;
    letter-spacing:normal;
}

.cols:last-child {
    margin-right:0;
}

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

The following worked for me. Just add the following snippet:

android {
        compileSdkVersion 25
        buildToolsVersion '25.0.1'

defaultConfig {
        applicationId "yourpackage"
        minSdkVersion 10
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
dexOptions {
        javaMaxHeapSize "4g"
    }
}

How to POST JSON Data With PHP cURL?

Try like this:

$url = 'url_to_post';
// this is only part of the data you need to sen
$customer_data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
// As per your API, the customer data should be structured this way
$data = array("customer" => $customer_data);
// And then encoded as a json string
$data_string = json_encode($data);
$ch=curl_init($url);

curl_setopt_array($ch, array(
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data_string,
    CURLOPT_HEADER => true,
    CURLOPT_HTTPHEADER => array('Content-Type:application/json', 'Content-Length: ' . strlen($data_string)))
));

$result = curl_exec($ch);
curl_close($ch);

The key thing you've forgotten was to json_encode your data. But you also may find it convenient to use curl_setopt_array to set all curl options at once by passing an array.

C++ Redefinition Header Files (winsock2.h)

This problem is caused when including <windows.h> before <winsock2.h>. Try arrange your include list that <windows.h> is included after <winsock2.h> or define _WINSOCKAPI_ first:

#define _WINSOCKAPI_    // stops windows.h including winsock.h
#include <windows.h>
// ...
#include "MyClass.h"    // Which includes <winsock2.h>

See also this.

How do I prevent Eclipse from hanging on startup?

This may not be an exact solution for your issue, but in my case, I tracked the files that Eclipse was polling against with SysInternals Procmon, and found that Eclipse was constantly polling a fairly large snapshot file for one of my projects. Removed that, and everything started up fine (albeit with the workspace in the state it was at the previous launch).

The file removed was:

<workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\.markers.snap

VBA: Convert Text to Number

Using aLearningLady's answer above, you can make your selection range dynamic by looking for the last row with data in it instead of just selecting the entire column.

The below code worked for me.

Dim lastrow as Integer

lastrow = Cells(Rows.Count, 2).End(xlUp).Row

Range("C2:C" & lastrow).Select
With Selection
    .NumberFormat = "General"
    .Value = .Value
End With

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

How to use SSH to run a local shell script on a remote machine?

This is an extension to YarekT's answer to combine inline remote commands with passing ENV variables from the local machine to the remote host so you can parameterize your scripts on the remote side:

ssh user@host ARG1=$ARG1 ARG2=$ARG2 'bash -s' <<'ENDSSH'
  # commands to run on remote host
  echo $ARG1 $ARG2
ENDSSH

I found this exceptionally helpful by keeping it all in one script so it's very readable and maintainable.

Why this works. ssh supports the following syntax:

ssh user@host remote_command

In bash we can specify environment variables to define prior to running a command on a single line like so:

ENV_VAR_1='value1' ENV_VAR_2='value2' bash -c 'echo $ENV_VAR_1 $ENV_VAR_2'

That makes it easy to define variables prior to running a command. In this case echo is our command we're running. Everything before echo defines environment variables.

So we combine those two features and YarekT's answer to get:

ssh user@host ARG1=$ARG1 ARG2=$ARG2 'bash -s' <<'ENDSSH'...

In this case we are setting ARG1 and ARG2 to local values. Sending everything after user@host as the remote_command. When the remote machine executes the command ARG1 and ARG2 are set the local values, thanks to local command line evaluation, which defines environment variables on the remote server, then executes the bash -s command using those variables. Voila.

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

One of alternatives is MSYS2 , in another words "MinGW-w64"/Git Bash. You can simply ssh to Unix machines and run most of linux commands from it. Also install tmux!

To install tmux in MSYS2:

run command pacman -S tmux

To run tmux on Git Bash:

install MSYS2 and copy tmux.exe and msys-event-2-1-6.dll from MSYS2 folder C:\msys64\usr\bin to your Git Bash directory C:\Program Files\Git\usr\bin.

Tomcat starts but home page cannot open with url http://localhost:8080

1) Using Terminal (On Linux), go to the apache-tomcat-directory/bin folder.

2) Type ./catalina.sh start

3) To stop Tomcat, type ./catalina.sh stop from the bin folder. For some reason ./startup.sh doesn't work sometimes.

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

let dt = new Date('2013-03-10T02:00:00Z');
let dd = dt.getDate();
let mm = dt.getMonth() + 1;
let yyyy = dt.getFullYear();

if (dd<10) {
    dd = '0' + dd;
}
if (mm<10) {
    mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;

How to avoid the "divide by zero" error in SQL?

This is how I fixed it:

IIF(ValueA != 0, Total / ValueA, 0)

It can be wrapped in an update:

SET Pct = IIF(ValueA != 0, Total / ValueA, 0)

Or in a select:

SELECT IIF(ValueA != 0, Total / ValueA, 0) AS Pct FROM Tablename;

Thoughts?

iOS 7 status bar back to iOS 6 default style in iPhone app?

As using presentViewController:animated:completion: messed-up the window.rootViewController.view, I had to find a different approach to this issue. I finally got it to work with modals and rotations by subclassing the UIView of my rootViewController.

.h

@interface RootView : UIView

@end

.m

@implementation RootView

-(void)setFrame:(CGRect)frame
{
    if (self.superview && self.superview != self.window)
    {
        frame = self.superview.bounds;
        frame.origin.y += 20.f;
        frame.size.height -= 20.f;
    }
    else
    {
        frame = [UIScreen mainScreen].applicationFrame;
    }

    [super setFrame:frame];
}

- (void)layoutSubviews
{
    self.frame = self.frame;

    [super layoutSubviews];
}

@end

You now have a strong workaround for iOS7 animations.

Chrome sendrequest error: TypeError: Converting circular structure to JSON

I resolve this problem on NodeJS like this:

var util = require('util');

// Our circular object
var obj = {foo: {bar: null}, a:{a:{a:{a:{a:{a:{a:{hi: 'Yo!'}}}}}}}};
obj.foo.bar = obj;

// Generate almost valid JS object definition code (typeof string)
var str = util.inspect(b, {depth: null});

// Fix code to the valid state (in this example it is not required, but my object was huge and complex, and I needed this for my case)
str = str
    .replace(/<Buffer[ \w\.]+>/ig, '"buffer"')
    .replace(/\[Function]/ig, 'function(){}')
    .replace(/\[Circular]/ig, '"Circular"')
    .replace(/\{ \[Function: ([\w]+)]/ig, '{ $1: function $1 () {},')
    .replace(/\[Function: ([\w]+)]/ig, 'function $1(){}')
    .replace(/(\w+): ([\w :]+GMT\+[\w \(\)]+),/ig, '$1: new Date("$2"),')
    .replace(/(\S+): ,/ig, '$1: null,');

// Create function to eval stringifyed code
var foo = new Function('return ' + str + ';');

// And have fun
console.log(JSON.stringify(foo(), null, 4));

How does Java handle integer underflows and overflows and how would you check for it?

Java doesn't do anything with integer overflow for either int or long primitive types and ignores overflow with positive and negative integers.

This answer first describes the of integer overflow, gives an example of how it can happen, even with intermediate values in expression evaluation, and then gives links to resources that give detailed techniques for preventing and detecting integer overflow.

Integer arithmetic and expressions reslulting in unexpected or undetected overflow are a common programming error. Unexpected or undetected integer overflow is also a well-known exploitable security issue, especially as it affects array, stack and list objects.

Overflow can occur in either a positive or negative direction where the positive or negative value would be beyond the maximum or minimum values for the primitive type in question. Overflow can occur in an intermediate value during expression or operation evaluation and affect the outcome of an expression or operation where the final value would be expected to be within range.

Sometimes negative overflow is mistakenly called underflow. Underflow is what happens when a value would be closer to zero than the representation allows. Underflow occurs in integer arithmetic and is expected. Integer underflow happens when an integer evaluation would be between -1 and 0 or 0 and 1. What would be a fractional result truncates to 0. This is normal and expected with integer arithmetic and not considered an error. However, it can lead to code throwing an exception. One example is an "ArithmeticException: / by zero" exception if the result of integer underflow is used as a divisor in an expression.

Consider the following code:

int bigValue = Integer.MAX_VALUE;
int x = bigValue * 2 / 5;
int y = bigValue / x;

which results in x being assigned 0 and the subsequent evaluation of bigValue / x throws an exception, "ArithmeticException: / by zero" (i.e. divide by zero), instead of y being assigned the value 2.

The expected result for x would be 858,993,458 which is less than the maximum int value of 2,147,483,647. However, the intermediate result from evaluating Integer.MAX_Value * 2, would be 4,294,967,294, which exceeds the maximum int value and is -2 in accordance with 2s complement integer representations. The subsequent evaluation of -2 / 5 evaluates to 0 which gets assigned to x.

Rearranging the expression for computing x to an expression that, when evaluated, divides before multiplying, the following code:

int bigValue = Integer.MAX_VALUE;
int x = bigValue / 5 * 2;
int y = bigValue / x;

results in x being assigned 858,993,458 and y being assigned 2, which is expected.

The intermediate result from bigValue / 5 is 429,496,729 which does not exceed the maximum value for an int. Subsequent evaluation of 429,496,729 * 2 doesn't exceed the maximum value for an int and the expected result gets assigned to x. The evaluation for y then does not divide by zero. The evaluations for x and y work as expected.

Java integer values are stored as and behave in accordance with 2s complement signed integer representations. When a resulting value would be larger or smaller than the maximum or minimum integer values, a 2's complement integer value results instead. In situations not expressly designed to use 2s complement behavior, which is most ordinary integer arithmetic situations, the resulting 2s complement value will cause a programming logic or computation error as was shown in the example above. An excellent Wikipedia article describes 2s compliment binary integers here: Two's complement - Wikipedia

There are techniques for avoiding unintentional integer overflow. Techinques may be categorized as using pre-condition testing, upcasting and BigInteger.

Pre-condition testing comprises examining the values going into an arithmetic operation or expression to ensure that an overflow won't occur with those values. Programming and design will need to create testing that ensures input values won't cause overflow and then determine what to do if input values occur that will cause overflow.

Upcasting comprises using a larger primitive type to perform the arithmetic operation or expression and then determining if the resulting value is beyond the maximum or minimum values for an integer. Even with upcasting, it is still possible that the value or some intermediate value in an operation or expression will be beyond the maximum or minimum values for the upcast type and cause overflow, which will also not be detected and will cause unexpected and undesired results. Through analysis or pre-conditions, it may be possible to prevent overflow with upcasting when prevention without upcasting is not possible or practical. If the integers in question are already long primitive types, then upcasting is not possible with primitive types in Java.

The BigInteger technique comprises using BigInteger for the arithmetic operation or expression using library methods that use BigInteger. BigInteger does not overflow. It will use all available memory, if necessary. Its arithmetic methods are normally only slightly less efficient than integer operations. It is still possible that a result using BigInteger may be beyond the maximum or minimum values for an integer, however, overflow will not occur in the arithmetic leading to the result. Programming and design will still need to determine what to do if a BigInteger result is beyond the maximum or minimum values for the desired primitive result type, e.g., int or long.

The Carnegie Mellon Software Engineering Institute's CERT program and Oracle have created a set of standards for secure Java programming. Included in the standards are techniques for preventing and detecting integer overflow. The standard is published as a freely accessible online resource here: The CERT Oracle Secure Coding Standard for Java

The standard's section that describes and contains practical examples of coding techniques for preventing or detecting integer overflow is here: NUM00-J. Detect or prevent integer overflow

Book form and PDF form of The CERT Oracle Secure Coding Standard for Java are also available.

Get the current fragment object

This is the simplest solution and work for me.

1.) you add your fragment

ft.replace(R.id.container_layout, fragment_name, "fragment_tag").commit();

2.)

FragmentManager fragmentManager = getSupportFragmentManager();

Fragment currentFragment = fragmentManager.findFragmentById(R.id.container_layout);

if(currentFragment.getTag().equals("fragment_tag"))

{

 //Do something

}

else

{

//Do something

}

Calculating Time Difference

time.monotonic() (basically your computer's uptime in seconds) is guarranteed to not misbehave when your computer's clock is adjusted (such as when transitioning to/from daylight saving time).

>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> a = time.monotonic()
>>> time.sleep(1)
>>> b = time.monotonic()
>>> print(b-a)
1.001658110995777

Homebrew: Could not symlink, /usr/local/bin is not writable

This is because the current user is not permitted to write in that path. So, to change r/w (read/write) permissions you can either use 1. terminal, or 2. Graphical "Get Info" window.

1. Using Terminal

Google how to use chmod/chown (change mode/change owner) commands from terminal

2. Using graphical 'Get Info'

You can right click on the folder/file you want to change permissions of, then open Get Info which will show you a window like below at the bottom of which you can easily change r/w permissions: enter image description here

Remember to change the permission back to "read only" after your temporary work, if possible

Insert json file into mongodb

This solution is applicable for Windows machine.

  1. MongoDB needs data directory to store data. Default path is C:\data\db. In case you don't have the data directory, create one in your C: drive. (P.S.: data\db means there is a directory named 'db' inside the directory 'data')

  2. Place the json you want to import in this path: C:\data\db\ .

  3. Open the command prompt and type the following command

    mongoimport --db databaseName --collections collectionName --file fileName.json --type json --batchSize 1

Here,

  • databaseName : your database name
  • collectionName: your collection name
  • fileName: name of your json file which is in the path C:\data\db
  • batchSize can be any integer as per your wish

How to get the IP address of the server on which my C# application is running on?

Cleaner and an all in one solution :D

//This returns the first IP4 address or null
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);

C# binary literals

Adding to @StriplingWarrior's answer about bit flags in enums, there's an easy convention you can use in hexadecimal for counting upwards through the bit shifts. Use the sequence 1-2-4-8, move one column to the left, and repeat.

[Flags]
enum Scenery
{
  Trees   = 0x001, // 000000000001
  Grass   = 0x002, // 000000000010
  Flowers = 0x004, // 000000000100
  Cactus  = 0x008, // 000000001000
  Birds   = 0x010, // 000000010000
  Bushes  = 0x020, // 000000100000
  Shrubs  = 0x040, // 000001000000
  Trails  = 0x080, // 000010000000
  Ferns   = 0x100, // 000100000000
  Rocks   = 0x200, // 001000000000
  Animals = 0x400, // 010000000000
  Moss    = 0x800, // 100000000000
}

Scan down starting with the right column and notice the pattern 1-2-4-8 (shift) 1-2-4-8 (shift) ...


To answer the original question, I second @Sahuagin's suggestion to use hexadecimal literals. If you're working with binary numbers often enough for this to be a concern, it's worth your while to get the hang of hexadecimal.

If you need to see binary numbers in source code, I suggest adding comments with binary literals like I have above.

How to generate a unique hash code for string input in android...?

This is a class I use to create Message Digest hashes

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha1Hex {

    public String makeSHA1Hash(String input)
            throws NoSuchAlgorithmException, UnsupportedEncodingException
        {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.reset();
            byte[] buffer = input.getBytes("UTF-8");
            md.update(buffer);
            byte[] digest = md.digest();

            String hexStr = "";
            for (int i = 0; i < digest.length; i++) {
                hexStr +=  Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
            }
            return hexStr;
        }
}

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Is it possible to compile a program written in Python?

If you really want, you could always compile with Cython. This will generate C code, which you can then compile with any C compiler such as GCC.

Make footer stick to bottom of page correctly

This should help you.

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
.footer {
    height: 155px;
}

'printf' vs. 'cout' in C++

I'm surprised that everyone in this question claims that std::cout is way better than printf, even if the question just asked for differences. Now, there is a difference - std::cout is C++, and printf is C (however, you can use it in C++, just like almost anything else from C). Now, I'll be honest here; both printf and std::cout have their advantages.

Real differences

Extensibility

std::cout is extensible. I know that people will say that printf is extensible too, but such extension is not mentioned in the C standard (so you would have to use non-standard features - but not even common non-standard feature exists), and such extensions are one letter (so it's easy to conflict with an already-existing format).

Unlike printf, std::cout depends completely on operator overloading, so there is no issue with custom formats - all you do is define a subroutine taking std::ostream as the first argument and your type as second. As such, there are no namespace problems - as long you have a class (which isn't limited to one character), you can have working std::ostream overloading for it.

However, I doubt that many people would want to extend ostream (to be honest, I rarely saw such extensions, even if they are easy to make). However, it's here if you need it.

Syntax

As it could be easily noticed, both printf and std::cout use different syntax. printf uses standard function syntax using pattern string and variable-length argument lists. Actually, printf is a reason why C has them - printf formats are too complex to be usable without them. However, std::cout uses a different API - the operator << API that returns itself.

Generally, that means the C version will be shorter, but in most cases it won't matter. The difference is noticeable when you print many arguments. If you have to write something like Error 2: File not found., assuming error number, and its description is placeholder, the code would look like this. Both examples work identically (well, sort of, std::endl actually flushes the buffer).

printf("Error %d: %s.\n", id, errors[id]);
std::cout << "Error " << id << ": " << errors[id] << "." << std::endl;

While this doesn't appear too crazy (it's just two times longer), things get more crazy when you actually format arguments, instead of just printing them. For example, printing of something like 0x0424 is just crazy. This is caused by std::cout mixing state and actual values. I never saw a language where something like std::setfill would be a type (other than C++, of course). printf clearly separates arguments and actual type. I really would prefer to maintain the printf version of it (even if it looks kind of cryptic) compared to iostream version of it (as it contains too much noise).

printf("0x%04x\n", 0x424);
std::cout << "0x" << std::hex << std::setfill('0') << std::setw(4) << 0x424 << std::endl;

Translation

This is where the real advantage of printf lies. The printf format string is well... a string. That makes it really easy to translate, compared to operator << abuse of iostream. Assuming that the gettext() function translates, and you want to show Error 2: File not found., the code to get translation of the previously shown format string would look like this:

printf(gettext("Error %d: %s.\n"), id, errors[id]);

Now, let's assume that we translate to Fictionish, where the error number is after the description. The translated string would look like %2$s oru %1$d.\n. Now, how to do it in C++? Well, I have no idea. I guess you can make fake iostream which constructs printf that you can pass to gettext, or something, for purposes of translation. Of course, $ is not C standard, but it's so common that it's safe to use in my opinion.

Not having to remember/look-up specific integer type syntax

C has lots of integer types, and so does C++. std::cout handles all types for you, while printf requires specific syntax depending on an integer type (there are non-integer types, but the only non-integer type you will use in practice with printf is const char * (C string, can be obtained using to_c method of std::string)). For instance, to print size_t, you need to use %zd, while int64_t will require using %"PRId64". The tables are available at http://en.cppreference.com/w/cpp/io/c/fprintf and http://en.cppreference.com/w/cpp/types/integer.

You can't print the NUL byte, \0

Because printf uses C strings as opposed to C++ strings, it cannot print NUL byte without specific tricks. In certain cases it's possible to use %c with '\0' as an argument, although that's clearly a hack.

Differences nobody cares about

Performance

Update: It turns out that iostream is so slow that it's usually slower than your hard drive (if you redirect your program to file). Disabling synchronization with stdio may help, if you need to output lots of data. If the performance is a real concern (as opposed to writing several lines to STDOUT), just use printf.

Everyone thinks that they care about performance, but nobody bothers to measure it. My answer is that I/O is bottleneck anyway, no matter if you use printf or iostream. I think that printf could be faster from a quick look into assembly (compiled with clang using the -O3 compiler option). Assuming my error example, printf example does way fewer calls than the cout example. This is int main with printf:

main:                                   @ @main
@ BB#0:
        push    {lr}
        ldr     r0, .LCPI0_0
        ldr     r2, .LCPI0_1
        mov     r1, #2
        bl      printf
        mov     r0, #0
        pop     {lr}
        mov     pc, lr
        .align  2
@ BB#1:

You can easily notice that two strings, and 2 (number) are pushed as printf arguments. That's about it; there is nothing else. For comparison, this is iostream compiled to assembly. No, there is no inlining; every single operator << call means another call with another set of arguments.

main:                                   @ @main
@ BB#0:
        push    {r4, r5, lr}
        ldr     r4, .LCPI0_0
        ldr     r1, .LCPI0_1
        mov     r2, #6
        mov     r3, #0
        mov     r0, r4
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        mov     r0, r4
        mov     r1, #2
        bl      _ZNSolsEi
        ldr     r1, .LCPI0_2
        mov     r2, #2
        mov     r3, #0
        mov     r4, r0
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        ldr     r1, .LCPI0_3
        mov     r0, r4
        mov     r2, #14
        mov     r3, #0
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        ldr     r1, .LCPI0_4
        mov     r0, r4
        mov     r2, #1
        mov     r3, #0
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        ldr     r0, [r4]
        sub     r0, r0, #24
        ldr     r0, [r0]
        add     r0, r0, r4
        ldr     r5, [r0, #240]
        cmp     r5, #0
        beq     .LBB0_5
@ BB#1:                                 @ %_ZSt13__check_facetISt5ctypeIcEERKT_PS3_.exit
        ldrb    r0, [r5, #28]
        cmp     r0, #0
        beq     .LBB0_3
@ BB#2:
        ldrb    r0, [r5, #39]
        b       .LBB0_4
.LBB0_3:
        mov     r0, r5
        bl      _ZNKSt5ctypeIcE13_M_widen_initEv
        ldr     r0, [r5]
        mov     r1, #10
        ldr     r2, [r0, #24]
        mov     r0, r5
        mov     lr, pc
        mov     pc, r2
.LBB0_4:                                @ %_ZNKSt5ctypeIcE5widenEc.exit
        lsl     r0, r0, #24
        asr     r1, r0, #24
        mov     r0, r4
        bl      _ZNSo3putEc
        bl      _ZNSo5flushEv
        mov     r0, #0
        pop     {r4, r5, lr}
        mov     pc, lr
.LBB0_5:
        bl      _ZSt16__throw_bad_castv
        .align  2
@ BB#6:

However, to be honest, this means nothing, as I/O is the bottleneck anyway. I just wanted to show that iostream is not faster because it's "type safe". Most C implementations implement printf formats using computed goto, so the printf is as fast as it can be, even without compiler being aware of printf (not that they aren't - some compilers can optimize printf in certain cases - constant string ending with \n is usually optimized to puts).

Inheritance

I don't know why you would want to inherit ostream, but I don't care. It's possible with FILE too.

class MyFile : public FILE {}

Type safety

True, variable length argument lists have no safety, but that doesn't matter, as popular C compilers can detect problems with printf format string if you enable warnings. In fact, Clang can do that without enabling warnings.

$ cat safety.c

#include <stdio.h>

int main(void) {
    printf("String: %s\n", 42);
    return 0;
}

$ clang safety.c

safety.c:4:28: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
    printf("String: %s\n", 42);
                    ~~     ^~
                    %d
1 warning generated.
$ gcc -Wall safety.c
safety.c: In function ‘main’:
safety.c:4:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
     printf("String: %s\n", 42);
     ^

CORS with POSTMAN

While all of the answers here are a really good explanation of what cors is but the direct answer to your question would be because of the following differences postman and browser.

Browser: Sends OPTIONS call to check the server type and getting the headers before sending any new request to the API endpoint. Where it checks for Access-Control-Allow-Origin. Taking this into account Access-Control-Allow-Origin header just specifies which all CROSS ORIGINS are allowed, although by default browser will only allow the same origin.

Postman: Sends direct GET, POST, PUT, DELETE etc. request without checking what type of server is and getting the header Access-Control-Allow-Origin by using OPTIONS call to the server.

How to debug Angular JavaScript Code

Since the add-ons don't work anymore, the most helpful set of tools I've found is using Visual Studio/IE because you can set breakpoints in your JS and inspect your data that way. Of course Chrome and Firefox have much better dev tools in general. Also, good ol' console.log() has been super helpful!

querySelectorAll with multiple conditions

With pure JavaScript you can do this (such as SQL) and anything you need, basically:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<input type='button' value='F3' class="c2" id="btn_1">_x000D_
<input type='button' value='F3' class="c3" id="btn_2">_x000D_
<input type='button' value='F1' class="c2" id="btn_3">_x000D_
_x000D_
<input type='submit' value='F2' class="c1" id="btn_4">_x000D_
<input type='submit' value='F1' class="c3" id="btn_5">_x000D_
<input type='submit' value='F2' class="c1" id="btn_6">_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<script>_x000D_
    function myFunction() _x000D_
    {_x000D_
        var arrFiltered = document.querySelectorAll('input[value=F2][type=submit][class=c1]');_x000D_
_x000D_
            arrFiltered.forEach(function (el)_x000D_
            {                _x000D_
                var node = document.createElement("p");_x000D_
                _x000D_
                node.innerHTML = el.getAttribute('id');_x000D_
_x000D_
                window.document.body.appendChild(node);_x000D_
            });_x000D_
        }_x000D_
    </script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Angularjs: input[text] ngChange fires while the value is changing

I had exactly the same problem and this worked for me. Add ng-model-update and ng-keyup and you're good to go! Here is the docs

 <input type="text" name="userName"
         ng-model="user.name"
         ng-change="update()"
         ng-model-options="{ updateOn: 'blur' }"
         ng-keyup="cancel($event)" />

Powershell 2 copy-item which creates a folder if doesn't exist

Here's an example that worked for me. I had a list of about 500 specific files in a text file, contained in about 100 different folders, that I was supposed to copy over to a backup location in case those files were needed later. The text file contained full path and file name, one per line. In my case, I wanted to strip off the Drive letter and first sub-folder name from each file name. I wanted to copy all these files to a similar folder structure under another root destination folder I specified. I hope other users find this helpful.

# Copy list of files (full path + file name) in a txt file to a new destination, creating folder structure for each file before copy
$rootDestFolder = "F:\DestinationFolderName"
$sourceFiles = Get-Content C:\temp\filelist.txt
foreach($sourceFile in $sourceFiles){
    $filesplit = $sourceFile.split("\")
    $splitcount = $filesplit.count
    # This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
    $destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
    # Output List of source and dest 
    Write-Host ""
    Write-Host "===$sourceFile===" -ForegroundColor Green
    Write-Host "+++$destFile+++"
    # Create path and file, if they do not already exist
    $destPath = Split-Path $destFile
    If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
    If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile }
}

Best way to format multiple 'or' conditions in an if statement (Java)

With Java 8, you could use a primitive stream:

if (IntStream.of(12, 16, 19).anyMatch(i -> i == x))

but this may have a slight overhead (or not), depending on the number of comparisons.

How to convert a string to lower or upper case in Ruby

Like @endeR mentioned, if internationalization is a concern, the unicode_utils gem is more than adequate.

$ gem install unicode_utils
$ irb
> require 'unicode_utils'
=> true
> UnicodeUtils.downcase("FEN BILIMLERI", :tr)
=> "fen bilimleri"

String manipulations in Ruby 2.4 are now unicode-sensitive.

Parsing PDF files (especially with tables) with PDFBox

Extracting data from PDF is bound to be fraught with problems. Are the documents created through some kind of automatic process? If so, you might consider converting the PDFs to uncompressed PostScript (try pdf2ps) and seeing if the PostScript contains some sort of regular pattern which you can exploit.

jQuery: Scroll down page a set increment (in pixels) on click?

Just check this:

$(document).ready(function() {
    $(".scroll").click(function(event){
        $('html, body').animate({scrollTop: '+=150px'}, 800);
    });
});

It will make scroller scroll from current position when your element is clicked

And 150px is used to scroll for 150px downwards

Error while installing json gem 'mkmf.rb can't find header files for ruby'

You may need to install gcc after install ruby-devel

Measuring function execution time in R

As Andrie said, system.time() works fine. For short function I prefer to put replicate() in it:

system.time( replicate(10000, myfunction(with,arguments) ) )

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

Using a PagedList with a ViewModel ASP.Net MVC

For anyone who is trying to do it without modifying your ViewModels AND not loading all your records from the database.

Repository

    public List<Order> GetOrderPage(int page, int itemsPerPage, out int totalCount)
    {
        List<Order> orders = new List<Order>();
        using (DatabaseContext db = new DatabaseContext())
        {
            orders = (from o in db.Orders
                      orderby o.Date descending //use orderby, otherwise Skip will throw an error
                      select o)
                      .Skip(itemsPerPage * page).Take(itemsPerPage)
                      .ToList();
            totalCount = db.Orders.Count();//return the number of pages
        }
        return orders;//the query is now already executed, it is a subset of all the orders.
    }

Controller

    public ActionResult Index(int? page)
    {
        int pagenumber = (page ?? 1) -1; //I know what you're thinking, don't put it on 0 :)
        OrderManagement orderMan = new OrderManagement(HttpContext.ApplicationInstance.Context);
        int totalCount = 0;
        List<Order> orders = orderMan.GetOrderPage(pagenumber, 5, out totalCount);
        List<OrderViewModel> orderViews = new List<OrderViewModel>();
        foreach(Order order in orders)//convert your models to some view models.
        {
            orderViews.Add(orderMan.GenerateOrderViewModel(order));
        }
        //create staticPageList, defining your viewModel, current page, page size and total number of pages.
        IPagedList<OrderViewModel> pageOrders = new StaticPagedList<OrderViewModel>(orderViews, pagenumber + 1, 5, totalCount);
        return View(pageOrders);
    }

View

@using PagedList.Mvc;
@using PagedList; 

@model IPagedList<Babywatcher.Core.Models.OrderViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="container-fluid">
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    @if (Model.Count > 0)
    {


        <table class="table">
          <tr>
            <th>
                @Html.DisplayNameFor(model => model.First().orderId)
            </th>
            <!--rest of your stuff-->
        </table>

    }
    else
    {
        <p>No Orders yet.</p>
    }
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>

Bonus

Do above first, then perhaps use this!

Since this question is about (view) models, I'm going to give away a little solution for you that will not only be useful for paging, but for the rest of your application if you want to keep your entities separate, only used in the repository, and have the rest of the application deal with models (which can be used as view models).

Repository

In your order repository (in my case), add a static method to convert a model:

public static OrderModel ConvertToModel(Order entity)
{
    if (entity == null) return null;
    OrderModel model = new OrderModel
    {
        ContactId = entity.contactId,
        OrderId = entity.orderId,
    }
    return model;
}

Below your repository class, add this:

public static partial class Ex
{
    public static IEnumerable<OrderModel> SelectOrderModel(this IEnumerable<Order> source)
    {
        bool includeRelations = source.GetType() != typeof(DbQuery<Order>);
        return source.Select(x => new OrderModel
        {
            OrderId = x.orderId,
            //example use ConvertToModel of some other repository
            BillingAddress = includeRelations ? AddressRepository.ConvertToModel(x.BillingAddress) : null,
            //example use another extension of some other repository
            Shipments = includeRelations && x.Shipments != null ? x.Shipments.SelectShipmentModel() : null
        });
    }
}

And then in your GetOrderPage method:

    public IEnumerable<OrderModel> GetOrderPage(int page, int itemsPerPage, string searchString, string sortOrder, int? partnerId,
        out int totalCount)
    {
        IQueryable<Order> query = DbContext.Orders; //get queryable from db
        .....//do your filtering, sorting, paging (do not use .ToList() yet)

        return queryOrders.SelectOrderModel().AsEnumerable();
        //or, if you want to include relations
        return queryOrders.Include(x => x.BillingAddress).ToList().SelectOrderModel();
        //notice difference, first ToList(), then SelectOrderModel().
    }

Let me explain:

The static ConvertToModel method can be accessed by any other repository, as used above, I use ConvertToModel from some AddressRepository.

The extension class/method lets you convert an entity to a model. This can be IQueryable or any other list, collection.

Now here comes the magic: If you have executed the query BEFORE calling SelectOrderModel() extension, includeRelations inside the extension will be true because the source is NOT a database query type (not an linq-to-sql IQueryable). When this is true, the extension can call other methods/extensions throughout your application for converting models.

Now on the other side: You can first execute the extension and then continue doing LINQ filtering. The filtering will happen in the database eventually, because you did not do a .ToList() yet, the extension is just an layer of dealing with your queries. Linq-to-sql will eventually know what filtering to apply in the Database. The inlcudeRelations will be false so that it doesn't call other c# methods that SQL doesn't understand.

It looks complicated at first, extensions might be something new, but it's really useful. Eventually when you have set this up for all repositories, simply an .Include() extra will load the relations.

PHP: Get key from array?

$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');

foreach($foo as $key => $item) {
  echo $item.' is begin with ('.$key.')';
}

Java: JSON -> Protobuf & back conversion

Well, there is no shortcut to do it as per my findings, but somehow you
an achieve it in few simple steps

First you have to declare a bean of type 'ProtobufJsonFormatHttpMessageConverter'

@Bean  
@Primary  
public ProtobufJsonFormatHttpMessageConverter protobufHttpMessageConverter() {  
  return new ProtobufJsonFormatHttpMessageConverter(JsonFormat.parser(), JsonFormat.printer());  
}  

Then you can just write an Utility class like ResponseBuilder, because it can parse the request by default but without these changes it can not produce Json response. and then you can write few methods to convert the response types to its related object type.

public static <T> T build(Message message, Class<T> type) {
  Printer printer = JsonFormat.printer();
  Gson gson = new Gson();
  try {
    return gson.fromJson(printer.print(message), type);
  } catch (JsonSyntaxException | InvalidProtocolBufferException e) {
    throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "Response   conversion Error", e);
  }
}

Then you can call this method from your controller class as last line like -

return ResponseBuilder.build(<returned_service_object>, <Type>);

Hope this will help you to implement protobuf in json format.

ImportError: No module named 'django.core.urlresolvers'

In my case the problem was that I had outdated django-stronghold installed (0.2.9). And even though in the code I had:

from django.urls import reverse

I still encountered the error. After I upgraded the version to django-stronghold==0.4.0 the problem disappeard.

How do I do multiple CASE WHEN conditions using SQL Server 2008?

This can be an efficient way of performing different tests on a single statement

select
case colour_txt 
  when 'red' then 5 
  when 'green' then 4 
  when 'orange' then 3
else 0 
end as Pass_Flag

this only works on equality comparisons!

How to use sed to extract substring

Explaining how you can use cut:

cat yourxmlfile | cut -d'"' -f2

It will 'cut' all the lines in the file based on " delimiter, and will take the 2nd field , which is what you wanted.

How can I check if char* variable points to empty string?

Check the pointer for NULL and then using strlen to see if it returns 0.
NULL check is important because passing NULL pointer to strlen invokes an Undefined Behavior.

Can a relative sitemap url be used in a robots.txt?

Good technical & logical question my dear friend. No in robots.txt file you can't go with relative URL of the sitemap; you need to go with the complete URL of the sitemap.

It's better to go with "sitemap: https://www.example.com/sitemap_index.xml"

In the above URL after the colon gives space. I also like to support Deepak.

How to apply style classes to td classes?

You can use :nth-child(N) CSS selector like :

table td:first-child {}  //1
table td:nth-child(2) {} //2
table td:nth-child(3) {} //3
table td:last-child {}   //4

Adding Jar files to IntellijIdea classpath

If, as I just encountered, you happen to have a jar file listed in the Project Structures->Libraries that is not in your classpath, the correct answer can be found by following the link given by @CrazyCoder above: Look here http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html

This says that to add the jar file as a module dependency within the Project Structure dialog:

  1. Open Project Structure
  2. Select Modules, then click on the module for which you want the dependency
  3. Choose the Dependencies tab
  4. Click the '+' at the bottom of the page and choose the appropriate way to connect to the library file. If the jar file is already listed in Libraries, then select 'Library'.

Getting URL parameter in java and extract a specific text from that URL

I solved the problem like this

public static String getUrlParameterValue(String url, String paramName) {
String value = "";
List<NameValuePair> result = null;

try {
    result = URLEncodedUtils.parse(new URI(url), UTF_8);
    value = result.stream().filter(pair -> pair.getName().equals(paramName)).findFirst().get().getValue();
    System.out.println("-------------->  \n" + paramName + " : " + value + "\n");
} catch (URISyntaxException e) {
    e.printStackTrace();
} 
return value;

}

CSS3 Box Shadow on Top, Left, and Right Only

Adding a separate answer because it is radically different.

You could use rgba and set the alpha channel low (to get transparency) to make your drop shadow less noticeable.

Try something like this (play with the .5)

-webkit-box-shadow: 0px -4px 7px rbga(230, 230, 230, .5);
-moz-box-shadow: 0px -4px 7px rbga(230, 230, 230, .5);
box-shadow: 0px -4px 7px rbga(230, 230, 230, .5);

Hope this helps!

How to print a certain line of a file with PowerShell?

To reduce memory consumption and to speed up the search you may use -ReadCount option of Get-Content cmdlet (https://technet.microsoft.com/ru-ru/library/hh849787.aspx).

This may save hours when you working with large files.

Here is an example:

$n = 60699010
$src = 'hugefile.csv'
$batch = 100
$timer = [Diagnostics.Stopwatch]::StartNew()

$count = 0
Get-Content $src -ReadCount $batch -TotalCount $n | %  { 
    $count += $_.Length
    if ($count -ge $n ) {
        $_[($n - $count + $_.Length - 1)]
    }
}

$timer.Stop()
$timer.Elapsed

This prints $n'th line and elapsed time.

surface plots in matplotlib

In Matlab I did something similar using the delaunay function on the x, y coords only (not the z), then plotting with trimesh or trisurf, using z as the height.

SciPy has the Delaunay class, which is based on the same underlying QHull library that the Matlab's delaunay function is, so you should get identical results.

From there, it should be a few lines of code to convert this Plotting 3D Polygons in python-matplotlib example into what you wish to achieve, as Delaunay gives you the specification of each triangular polygon.

SELECT CASE WHEN THEN (SELECT)

You Could try the other format for the case statement

CASE WHEN Product.type_id = 10
THEN
(
  Select Statement
)
ELSE
(
  Other select statement

)  
END
FROM Product 
WHERE Product.product_id = $pid

See http://msdn.microsoft.com/en-us/library/ms181765.aspx for more information.

Context.startForegroundService() did not then call Service.startForeground()

Since everybody visiting here is suffering the same thing, I want to share my solution that nobody else has tried before (in this question anyways). I can assure you that it is working, even on a stopped breakpoint which confirms this method.

The issue is to call Service.startForeground(id, notification) from the service itself, right? Android Framework unfortunately does not guarantee to call Service.startForeground(id, notification) within Service.onCreate() in 5 seconds but throws the exception anyway, so I've come up with this way.

  1. Bind the service to a context with a binder from the service before calling Context.startForegroundService()
  2. If the bind is successful, call Context.startForegroundService() from the service connection and immediately call Service.startForeground() inside the service connection.
  3. IMPORTANT NOTE: Call the Context.bindService() method inside a try-catch because in some occasions the call can throw an exception, in which case you need to rely on calling Context.startForegroundService() directly and hope it will not fail. An example can be a broadcast receiver context, however getting application context does not throw an exception in that case, but using the context directly does.

This even works when I'm waiting on a breakpoint after binding the service and before triggering the "startForeground" call. Waiting between 3-4 seconds do not trigger the exception while after 5 seconds it throws the exception. (If the device cannot execute two lines of code in 5 seconds, then it's time to throw that in the trash.)

So, start with creating a service connection.

// Create the service connection.
ServiceConnection connection = new ServiceConnection()
{
    @Override
    public void onServiceConnected(ComponentName name, IBinder service)
    {
        // The binder of the service that returns the instance that is created.
        MyService.LocalBinder binder = (MyService.LocalBinder) service;

        // The getter method to acquire the service.
        MyService myService = binder.getService();

        // getServiceIntent(context) returns the relative service intent 
        context.startForegroundService(getServiceIntent(context));

        // This is the key: Without waiting Android Framework to call this method
        // inside Service.onCreate(), immediately call here to post the notification.
        myService.startForeground(myNotificationId, MyService.getNotification());

        // Release the connection to prevent leaks.
        context.unbindService(this);
    }

    @Override
    public void onBindingDied(ComponentName name)
    {
        Log.w(TAG, "Binding has dead.");
    }

    @Override
    public void onNullBinding(ComponentName name)
    {
        Log.w(TAG, "Bind was null.");
    }

    @Override
    public void onServiceDisconnected(ComponentName name)
    {
        Log.w(TAG, "Service is disconnected..");
    }
};

Inside your service, create a binder that returns the instance of your service.

public class MyService extends Service
{
    public class LocalBinder extends Binder
    {
        public MyService getService()
        {
            return MyService.this;
        }
    }

    // Create the instance on the service.
    private final LocalBinder binder = new LocalBinder();

    // Return this instance from onBind method.
    // You may also return new LocalBinder() which is
    // basically the same thing.
    @Nullable
    @Override
    public IBinder onBind(Intent intent)
    {
        return binder;
    }
}

Then, try to bind the service from that context. If it succeeds, it will call ServiceConnection.onServiceConnected() method from the service connection that you're using. Then, handle the logic in the code that's shown above. An example code would look like this:

// Try to bind the service
try
{
     context.bindService(getServiceIntent(context), connection,
                    Context.BIND_AUTO_CREATE);
}
catch (RuntimeException ignored)
{
     // This is probably a broadcast receiver context even though we are calling getApplicationContext().
     // Just call startForegroundService instead since we cannot bind a service to a
     // broadcast receiver context. The service also have to call startForeground in
     // this case.
     context.startForegroundService(getServiceIntent(context));
}

It seems to be working on the applications that I develop, so it should work when you try as well.

Remove a git commit which has not been pushed

I have experienced the same situation I did the below as this much easier. By passing commit-Id you can reach to the particular commit you want to go:

git reset --hard {commit-id}

As you want to remove your last commit so you need to pass the commit-Id where you need to move your pointer:

git reset --hard db0c078d5286b837532ff5e276dcf91885df2296

How to use z-index in svg elements?

Specification

In the SVG specification version 1.1 the rendering order is based on the document order:

first element -> "painted" first

Reference to the SVG 1.1. Specification

3.3 Rendering Order

Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document fragment getting "painted" first. Subsequent elements are painted on top of previously painted elements.


Solution (cleaner-faster)

You should put the green circle as the latest object to be drawn. So swap the two elements.

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" viewBox="30 70 160 120"> _x000D_
   <!-- First draw the orange circle -->_x000D_
   <circle fill="orange" cx="100" cy="95" r="20"/> _x000D_
_x000D_
   <!-- Then draw the green circle over the current canvas -->_x000D_
   <circle fill="green" cx="100" cy="105" r="20"/> _x000D_
</svg>
_x000D_
_x000D_
_x000D_

Here the fork of your jsFiddle.

Solution (alternative)

The tag use with the attribute xlink:href and as value the id of the element. Keep in mind that might not be the best solution even if the result seems fine. Having a bit of time, here the link of the specification SVG 1.1 "use" Element.

Purpose:

To avoid requiring authors to modify the referenced document to add an ID to the root element.

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" viewBox="30 70 160 120">_x000D_
    <!-- First draw the green circle -->_x000D_
    <circle id="one" fill="green" cx="100" cy="105" r="20" />_x000D_
    _x000D_
    <!-- Then draw the orange circle over the current canvas -->_x000D_
    <circle id="two" fill="orange" cx="100" cy="95" r="20" />_x000D_
    _x000D_
    <!-- Finally draw again the green circle over the current canvas -->_x000D_
    <use xlink:href="#one"/>_x000D_
</svg>
_x000D_
_x000D_
_x000D_


Notes on SVG 2

SVG 2 Specification is the next major release and still supports the above features.

3.4. Rendering order

Elements in SVG are positioned in three dimensions. In addition to their position on the x and y axis of the SVG viewport, SVG elements are also positioned on the z axis. The position on the z-axis defines the order that they are painted.

Along the z axis, elements are grouped into stacking contexts.

3.4.1. Establishing a stacking context in SVG

...

Stacking contexts are conceptual tools used to describe the order in which elements must be painted one on top of the other when the document is rendered, ...

XML Schema How to Restrict Attribute by Enumeration

The numerical value seems to be missing from your price definition. Try the following:

<xs:simpleType name="curr">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds" />
    <xs:enumeration value="euros" />
    <xs:enumeration value="dollars" />
  </xs:restriction>
</xs:simpleType>



<xs:element name="price">
        <xs:complexType>
            <xs:extension base="xs:decimal">
              <xs:attribute name="currency" type="curr"/>
            </xs:extension>
        </xs:complexType>
</xs:element>

In R, how to find the standard error of the mean?

A version of John's answer above that removes the pesky NA's:

stderr <- function(x, na.rm=FALSE) {
  if (na.rm) x <- na.omit(x)
  sqrt(var(x)/length(x))
}

invalid use of non-static member function

You shall pass a this pointer to tell the function which object to work on because it relies on that as opposed to a static member function.

Using async/await with a forEach loop

Currently the Array.forEach prototype property doesn't support async operations, but we can create our own poly-fill to meet our needs.

// Example of asyncForEach Array poly-fill for NodeJs
// file: asyncForEach.js
// Define asynForEach function 
async function asyncForEach(iteratorFunction){
  let indexer = 0
  for(let data of this){
    await iteratorFunction(data, indexer)
    indexer++
  }
}
// Append it as an Array prototype property
Array.prototype.asyncForEach = asyncForEach
module.exports = {Array}

And that's it! You now have an async forEach method available on any arrays that are defined after these to operations.

Let's test it...

// Nodejs style
// file: someOtherFile.js

const readline = require('readline')
Array = require('./asyncForEach').Array
const log = console.log

// Create a stream interface
function createReader(options={prompt: '>'}){
  return readline.createInterface({
    input: process.stdin
    ,output: process.stdout
    ,prompt: options.prompt !== undefined ? options.prompt : '>'
  })
}
// Create a cli stream reader
async function getUserIn(question, options={prompt:'>'}){
  log(question)
  let reader = createReader(options)
  return new Promise((res)=>{
    reader.on('line', (answer)=>{
      process.stdout.cursorTo(0, 0)
      process.stdout.clearScreenDown()
      reader.close()
      res(answer)
    })
  })
}

let questions = [
  `What's your name`
  ,`What's your favorite programming language`
  ,`What's your favorite async function`
]
let responses = {}

async function getResponses(){
// Notice we have to prepend await before calling the async Array function
// in order for it to function as expected
  await questions.asyncForEach(async function(question, index){
    let answer = await getUserIn(question)
    responses[question] = answer
  })
}

async function main(){
  await getResponses()
  log(responses)
}
main()
// Should prompt user for an answer to each question and then 
// log each question and answer as an object to the terminal

We could do the same for some of the other array functions like map...

async function asyncMap(iteratorFunction){
  let newMap = []
  let indexer = 0
  for(let data of this){
    newMap[indexer] = await iteratorFunction(data, indexer, this)
    indexer++
  }
  return newMap
}

Array.prototype.asyncMap = asyncMap

... and so on :)

Some things to note:

  • Your iteratorFunction must be an async function or promise
  • Any arrays created before Array.prototype.<yourAsyncFunc> = <yourAsyncFunc> will not have this feature available

How do I collapse sections of code in Visual Studio Code for Windows?

As of version 1.3.1 (2016-07-17), Block Collapse is much more convenient.

Any line followed by an indented line will have a '-' character to allow collapse. If the block is collapsed, it will then be replaced by a '+' character that will open the collapsed block.

The (Ctrl + Shift + Alt + ]) will still affect all blocks, closing one level. Each repeated use closed one more level. The (Ctrl + Shift + Alt + [) works in the opposite way.

Hooray, block collapse finally works usefully.

How to use font-awesome icons from node-modules

You could add it between your <head></head> tag like so:

<head>
  <link href="./node_modules/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css">
</head>

Or whatever your path to your node_modules is.

Edit (2017-06-26) - Disclaimer: THERE ARE BETTER ANSWERS. PLEASE DO NOT USE THIS METHOD. At the time of this original answer, good tools weren't as prevalent. With current build tools such as webpack or browserify, it probably doesn't make sense to use this answer. I can delete it, but I think it's important to highlight the various options one has and the possible dos and do nots.

TypeError: '<=' not supported between instances of 'str' and 'int'

When you use the input function it automatically turns it into a string. You need to go:

vote = int(input('Enter the name of the player you wish to vote for'))

which turns the input into a int type value

How do I copy the contents of one stream to another?

Unfortunately, there is no really simple solution. You can try something like that:

Stream s1, s2;
byte[] buffer = new byte[4096];
int bytesRead = 0;
while (bytesRead = s1.Read(buffer, 0, buffer.Length) > 0) s2.Write(buffer, 0, bytesRead);
s1.Close(); s2.Close();

But the problem with that that different implementation of the Stream class might behave differently if there is nothing to read. A stream reading a file from a local harddrive will probably block until the read operaition has read enough data from the disk to fill the buffer and only return less data if it reaches the end of file. On the other hand, a stream reading from the network might return less data even though there are more data left to be received.

Always check the documentation of the specific stream class you are using before using a generic solution.

Difference between two dates in MySQL

This code calculate difference between two dates in yyyy MM dd format.

declare @StartDate datetime 
declare @EndDate datetime

declare @years int
declare @months int 
declare @days int

--NOTE: date of birth must be smaller than As on date, 
--else it could produce wrong results
set @StartDate = '2013-12-30' --birthdate
set @EndDate  = Getdate()            --current datetime

--calculate years
select @years = datediff(year,@StartDate,@EndDate)

--calculate months if it's value is negative then it 
--indicates after __ months; __ years will be complete
--To resolve this, we have taken a flag @MonthOverflow...
declare @monthOverflow int
select @monthOverflow = case when datediff(month,@StartDate,@EndDate) - 
  ( datediff(year,@StartDate,@EndDate) * 12) <0 then -1 else 1 end
--decrease year by 1 if months are Overflowed
select @Years = case when @monthOverflow < 0 then @years-1 else @years end
select @months =  datediff(month,@StartDate,@EndDate) - (@years * 12) 

--as we do for month overflow criteria for days and hours 
--& minutes logic will followed same way
declare @LastdayOfMonth int
select @LastdayOfMonth =  datepart(d,DATEADD
    (s,-1,DATEADD(mm, DATEDIFF(m,0,@EndDate)+1,0)))

select @days = case when @monthOverflow<0 and 
    DAY(@StartDate)> DAY(@EndDate) 
then @LastdayOfMonth + 
  (datepart(d,@EndDate) - datepart(d,@StartDate) ) - 1  
      else datepart(d,@EndDate) - datepart(d,@StartDate) end 


select
 @Months=case when @days < 0 or DAY(@StartDate)> DAY(@EndDate) then @Months-1 else @Months end

Declare @lastdayAsOnDate int;
set @lastdayAsOnDate = datepart(d,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@EndDate),0)));
Declare @lastdayBirthdate int;
set @lastdayBirthdate =  datepart(d,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@StartDate)+1,0)));

if (@Days < 0) 
(
    select @Days = case when( @lastdayBirthdate > @lastdayAsOnDate) then
        @lastdayBirthdate + @Days
    else
        @lastdayAsOnDate + @Days
    end
)
print  convert(varchar,@years)   + ' year(s),   '  +
       convert(varchar,@months)  + ' month(s),   ' +
       convert(varchar,@days)    + ' day(s)   '   

How to cancel/abort jQuery AJAX request?

You should also check for readyState 0. Because when you use xhr.abort() this function set readyState to 0 in this object, and your if check will be always true - readyState !=4

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4 && xhr.readyState != 0){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
); 

jQuery checkbox event handling

Using the new 'on' method in jQuery (1.7): http://api.jquery.com/on/

    $('#myform').on('change', 'input[type=checkbox]', function(e) {
        console.log(this.name+' '+this.value+' '+this.checked);

    });
  • the event handler will live on
  • will capture if the checkbox was changed by keyboard, not just click

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

A bit similar to @bpile answer, my case was a my.cnf entry setting collation-server = utf8_general_ci. After I realized that (and after trying everything above), I forcefully switched my database to utf8_general_ci instead of utf8_unicode_ci and that was it:

ALTER DATABASE `db` CHARACTER SET utf8 COLLATE utf8_general_ci;

Instantly detect client disconnection from server socket

Can't you just use Select?

Use select on a connected socket. If the select returns with your socket as Ready but the subsequent Receive returns 0 bytes that means the client disconnected the connection. AFAIK, that is the fastest way to determine if the client disconnected.

I do not know C# so just ignore if my solution does not fit in C# (C# does provide select though) or if I had misunderstood the context.

Counting the number of occurences of characters in a string

Try this:

import java.util.Scanner;

    /* Logic: Consider first character in the string and start counting occurrence of        
              this character in the entire string. Now add this character to a empty
              string "temp" to keep track of the already counted characters.
              Next start counting from next character and start counting the character        
              only if it is not present in the "temp" string( which means only if it is
              not counted already)
public class Counting_Occurences {

    public static void main(String[] args) {


        Scanner input=new Scanner(System.in);
        System.out.println("Enter String");
        String str=input.nextLine();

        int count=0;
        String temp=""; // An empty string to keep track of counted
                                    // characters


        for(int i=0;i<str.length();i++)
        {

            char c=str.charAt(i);  // take one character (c) in string

            for(int j=i;j<str.length();j++)
            {

                char k=str.charAt(j);  
    // take one character (c) and compare with each character (k) in the string
            // also check that character (c) is not already counted.
            // if condition passes then increment the count.
                if(c==k && temp.indexOf(c)==-1)                                                                          
                {

                    count=count+1;

                }

            }

             if(temp.indexOf(c)==-1)  // if it is not already counted
             {


            temp=temp+c; // append the character to the temp indicating
                                         // that you have already counted it.

System.out.println("Character   " + c + "   occurs   " + count + "    times");
             }  
            // reset the counter for next iteration 
              count=0;

        }


    }


}

DB query builder toArray() laravel 4

Easiest way is using laravel toArray function itself:

    $result = array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $result);

Animate element to auto height with jQuery

I put together something that does exactly what I was looking for and looks great. Using the scrollHeight of an element gets you the height of when it was loaded in the DOM.

_x000D_
_x000D_
 var clickers = document.querySelectorAll('.clicker');_x000D_
    clickers.forEach(clicker => {_x000D_
        clicker.addEventListener('click', function (e) {_x000D_
            var node = e.target.parentNode.childNodes[5];_x000D_
            if (node.style.height == "0px" || node.style.height == "") {_x000D_
                $(node).animate({ height: node.scrollHeight });_x000D_
            }_x000D_
            else {_x000D_
                $(node).animate({ height: 0 });_x000D_
            }_x000D_
        });_x000D_
    });
_x000D_
.answer{_x000D_
        font-size:15px;_x000D_
        color:blue;_x000D_
        height:0px;_x000D_
        overflow:hidden;_x000D_
       _x000D_
    }
_x000D_
 <div class="row" style="padding-top:20px;">_x000D_
                <div class="row" style="border-color:black;border-style:solid;border-radius:4px;border-width:4px;">_x000D_
                    <h1>This is an animation tester?</h1>_x000D_
                    <span class="clicker">click me</span>_x000D_
                    <p class="answer">_x000D_
                        I will be using this to display FAQ's on a website and figure you would like this.  The javascript will allow this to work on all of the FAQ divs made by my razor code.  the Scrollheight is the height of the answer element on the DOM load.  Happy Coding :)_x000D_
                         Lorem ipsum dolor sit amet, mea an quis vidit autem. No mea vide inani efficiantur, mollis admodum accusata id has, eam dolore nemore eu. Mutat partiendo ea usu, pri duis vulputate eu. Vis mazim noluisse oportere id. Cum porro labore in, est accumsan euripidis scripserit ei. Albucius scaevola elaboraret usu eu. Ad sed vivendo persecuti, harum movet instructior eam ei._x000D_
                    </p>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

tell pip to install the dependencies of packages listed in a requirement file

As @Ming mentioned:

pip install -r file.txt

Here's a simple line to force update all dependencies:

while read -r package; do pip install --upgrade --force-reinstall $package;done < pipfreeze.txt

Interfaces with static fields in java for sharing 'constants'

I do not have enough reputation to give a comment to Pleerock, therefor do I have to create an answer. I am sorry for that, but he put some good effort in it and I would like to answer him.

Pleerock, you created the perfect example to show why those constants should be independent from interfaces and independent from inheritance. For the client of the application is it not important that there is a technical difference between those implementation of cars. They are the same for the client, just cars. So, the client wants to look at them from that perspective, which is an interface like I_Somecar. Throughout the application will the client use only one perspective and not different ones for each different car brand.

If a client wants to compare cars prior to buying he can have a method like this:

public List<Decision> compareCars(List<I_Somecar> pCars);

An interface is a contract about behaviour and shows different objects from one perspective. The way you design it, will every car brand have its own line of inheritance. Although it is in reality quite correct, because cars can be that different that it can be like comparing completely different type of objects, in the end there is choice between different cars. And that is the perspective of the interface all brands have to share. The choice of constants should not make this impossible. Please, consider the answer of Zarkonnen.

In JavaScript can I make a "click" event fire programmatically for a file input element?

I found that if input(file) is outside form, then firing click event invokes file dialog.

Reset textbox value in javascript

To set value

 $('#searchField').val('your_value');

to retrieve value

$('#searchField').val();

What is the best way to implement constants in Java?

One of the way I do it is by creating a 'Global' class with the constant values and do a static import in the classes that need access to the constant.

How to run Spyder in virtual environment?

I follow one of the advice above and indeed it works. In summary while you download Anaconda on Ubuntu using the advice given above can help you to 'create' environments. The default when you download Spyder in my case is: (base) smith@ubuntu ~$. After you create the environment, i.e. fenics and activate it with $ conda activate fenics the prompt change to (fenics) smith@ubuntu ~$. Then you launch Spyder from this prompt, i.e $ spyder and your system open the Spyder IDE, and you can write fenics code on it. Remember every time you open a terminal your system open the default prompt. You have to activate your environment where your package is and the prompt change to it i.e. (fenics).

Posting parameters to a url using the POST method without using a form

Using jQuery.post

$.post(
  "http://theurl.com",
  { key1: "value1", key2: "value2" },
  function(data) {
    alert("Response: " + data);
  }
);

Disable browsers vertical and horizontal scrollbars

function reloadScrollBars() {
    document.documentElement.style.overflow = 'auto';  // firefox, chrome
    document.body.scroll = "yes"; // ie only
}

function unloadScrollBars() {
    document.documentElement.style.overflow = 'hidden';  // firefox, chrome
    document.body.scroll = "no"; // ie only
}

Spring 3 MVC resources and tag <mvc:resources />

You can keep rsouces directory in Directory NetBeans: Web Pages Eclipse: webapps

File: dispatcher-servlet.xml

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan base-package="controller" />

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <mvc:resources location="/resources/theme_name/" mapping="/resources/**"  cache-period="10000"/>
    <mvc:annotation-driven/>

</beans>

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
        <url-pattern>*.css</url-pattern>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

In JSP File

<link href="<c:url value="/resources/css/default.css"/>" rel="stylesheet" type="text/css"/>

What is the difference between #import and #include in Objective-C?

I know this thread is old... but in "modern times".. there is a far superior "include strategy" via clang's @import modules - that is oft-overlooked..

Modules improve access to the API of software libraries by replacing the textual preprocessor inclusion model with a more robust, more efficient semantic model. From the user’s perspective, the code looks only slightly different, because one uses an import declaration rather than a #include preprocessor directive:

@import Darwin; // Like including all of /usr/include. @see /usr/include/module.map

or

@import Foundation;  //  Like #import <Foundation/Foundation.h>
@import ObjectiveC;  //  Like #import <objc/runtime.h>

However, this module import behaves quite differently from the corresponding #include: when the compiler sees the module import above, it loads a binary representation of the module and makes its API available to the application directly. Preprocessor definitions that precede the import declaration have no impact on the API provided... because the module itself was compiled as a separate, standalone module. Additionally, any linker flags required to use the module will automatically be provided when the module is imported. This semantic import model addresses many of the problems of the preprocessor inclusion model.

To enable modules, pass the command-line flag -fmodules aka CLANG_ENABLE_MODULES in Xcode- at compile time. As mentioned above.. this strategy obviates ANY and ALL LDFLAGS. As in, you can REMOVE any "OTHER_LDFLAGS" settings, as well as any "Linking" phases..

enter image description here

I find compile / launch times to "feel" much snappier (or possibly, there's just less of a lag while "linking"?).. and also, provides a great opportunity to purge the now extraneous Project-Prefix.pch file, and corresponding build settings, GCC_INCREASE_PRECOMPILED_HEADER_SHARING, GCC_PRECOMPILE_PREFIX_HEADER, and GCC_PREFIX_HEADER, etc.

Also, while not well-documented… You can create module.maps for your own frameworks and include them in the same convenient fashion. You can take a look at my ObjC-Clang-Modules github repo for some examples of how to implement such miracles.

How to show MessageBox on asp.net?

There is pretty concise and easy way:

Response.Write("<script>alert('Your text');</script>");

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

just pass the date time to this func. it would print out in time ago format for you

date_default_timezone_set('your-time-zone');
function convert($datetime){
  $time=strtotime($datetime);
  $diff=time()-$time;
  $diff/=60;
  $var1=floor($diff);
  $var=$var1<=1 ? 'min' : 'mins';
  if($diff>=60){
    $diff/=60;
    $var1=floor($diff);
    $var=$var1<=1 ? 'hr' : 'hrs';
    if($diff>=24){$diff/=24;$var1=floor($diff);$var=$var1<=1 ? 'day' : 'days';
    if($diff>=30.4375){$diff/=30.4375;$var1=floor($diff);$var=$var1<=1 ? 'month' : 'months';
    if($diff>=12){$diff/=12;$var1=floor($diff);$var=$var1<=1 ? 'year' : 'years';}}}}
    echo $var1,' ',$var,' ago';
  }

SQL query for today's date minus two months

TSQL, Alternative using variable declaration. (it might improve Query's readability)

DECLARE @gapPeriod DATETIME = DATEADD(MONTH,-2,GETDATE()); --Period:Last 2 months.

SELECT 
        *
    FROM 
        FB as A
    WHERE
        A.Dte <= @gapPeriod;                               --only older records.

Trim last character from a string

The another example of trimming last character from a string:

string outputText = inputText.Remove(inputText.Length - 1, 1);

You can put it into an extension method and prevent it from null string, etc.

How to match a substring in a string, ignoring case

import re
if re.search('(?i)Mandy Pande:', line):
    ...

How to change FontSize By JavaScript?

Please never do this in real projects:

_x000D_
_x000D_
document.getElementById("span").innerHTML = "String".fontsize(25);
_x000D_
<span id="span"></span>
_x000D_
_x000D_
_x000D_

Connection Java-MySql : Public Key Retrieval is not allowed

If you are getting the following error while connecting the mysql (either local or mysql container running the mysql):

java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed

Solution: Add the following line in your database service:

command: --default-authentication-plugin=mysql_native_password

Creating an Array from a Range in VBA

Adding to @Vityata 's answer, below is the function I use to convert a row / column vector in a 1D array:

Function convertVecToArr(ByVal rng As Range) As Variant
'convert two dimension array into a one dimension array
    
    Dim arr() As Variant, slicedArr() As Variant
    arr = rng.value   'arr = rng works too (https://bettersolutions.com/excel/cells-ranges/vba-working-with-arrays.htm)
    
    If UBound(arr, 1) > UBound(arr, 2) Then
        slicedArr = Application.WorksheetFunction.Transpose(arr)
    Else
        slicedArr = Application.WorksheetFunction.index(arr, 1, 0)  'If you set row_num or column_num to 0 (zero), Index returns the array of values for the entire column or row, respectively._
                                                                   'To use values returned as an array, enter the Index function as an array formula in a horizontal range of cells for a row,_
                                                                   'and in a vertical range of cells for a column.
                                                                   'https://usefulgyaan.wordpress.com/2013/06/12/vba-trick-of-the-week-slicing-an-array-without-loop-application-index/
    End If
convertVecToArr = slicedArr
End Function

What is JavaScript garbage collection?

Eric Lippert wrote a detailed blog post about this subject a while back (additionally comparing it to VBScript). More accurately, he wrote about JScript, which is Microsoft's own implementation of ECMAScript, although very similar to JavaScript. I would imagine that you can assume the vast majority of behaviour would be the same for the JavaScript engine of Internet Explorer. Of course, the implementation will vary from browser to browser, though I suspect you could take a number of the common principles and apply them to other browsers.

Quoted from that page:

JScript uses a nongenerational mark-and-sweep garbage collector. It works like this:

  • Every variable which is "in scope" is called a "scavenger". A scavenger may refer to a number, an object, a string, whatever. We maintain a list of scavengers -- variables are moved on to the scav list when they come into scope and off the scav list when they go out of scope.

  • Every now and then the garbage collector runs. First it puts a "mark" on every object, variable, string, etc – all the memory tracked by the GC. (JScript uses the VARIANT data structure internally and there are plenty of extra unused bits in that structure, so we just set one of them.)

  • Second, it clears the mark on the scavengers and the transitive closure of scavenger references. So if a scavenger object references a nonscavenger object then we clear the bits on the nonscavenger, and on everything that it refers to. (I am using the word "closure" in a different sense than in my earlier post.)

  • At this point we know that all the memory still marked is allocated memory which cannot be reached by any path from any in-scope variable. All of those objects are instructed to tear themselves down, which destroys any circular references.

The main purpose of garbage collection is to allow the programmer not to worry about memory management of the objects they create and use, though of course there's no avoiding it sometimes - it is always beneficial to have at least a rough idea of how garbage collection works.

Historical note: an earlier revision of the answer had an incorrect reference to the delete operator. In JavaScript the delete operator removes a property from an object, and is wholly different to delete in C/C++.

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

How to create empty constructor for data class in Kotlin Android

If you give default values to all the fields - empty constructor is generated automatically by Kotlin.

data class User(var id: Long = -1,
                var uniqueIdentifier: String? = null)

and you can simply call:

val user = User()

Redis - Connect to Remote Server

Orabig is correct.

You can bind 10.0.2.15 in Ubuntu (VirtualBox) then do a port forwarding from host to guest Ubuntu.

in /etc/redis/redis.conf

bind 10.0.2.15

then, restart redis:

sudo systemctl restart redis

It shall work!

Likelihood of collision using most significant bits of a UUID in Java

You are better off just generating a random long value, then all the bits are random. In Java 6, new Random() uses the System.nanoTime() plus a counter as a seed.

There are different levels of uniqueness.

If you need uniqueness across many machines, you could have a central database table for allocating unique ids, or even batches of unique ids.

If you just need to have uniqueness in one app you can just have a counter (or a counter which starts from the currentTimeMillis()*1000 or nanoTime() depending on your requirements)

How to echo xml file in php

If anyone is targeting yahoo rss feed may benefit from this snippet

<?php
    $rssUrl="http://news.yahoo.com/rss/topstories";
    //====================================================
    $xml=simplexml_load_file($rssUrl) or die("Error: Cannot create object");
    //====================================================
    $featureRss =  array_slice(json_decode(json_encode((array) $xml ),  true ), 0 );
 /*Just to see what is in it 
use this function PrettyPrintArray() 
instead of var_dump($featureRss);*/

    function PrettyPrintArray($rssData, $level) {
    foreach($rssData as $key => $Items) {
    for($i = 0; $i < $level; $i++)
    echo("&nbsp;");
    /*if content more than one*/
    if(!is_array($Items)){
    //$Items=htmlentities($Items); 
    $Items=htmlspecialchars($Items);
    echo("Item " .$key . " => " . $Items . "<br/><br/>");
    }
    else 
    {
    echo($key . " => <br/><br/>");
    PrettyPrintArray($Items, $level+1);
    }
    }
    }
    PrettyPrintArray($featureRss, 0);
?>

You may want to run it in your browser first to see what is there and before looping and style it up pretty simple

To grab the first item description

<?php
    echo($featureRss['channel']['item'][0]['description']);
?>

You can see a demo here

Return only string message from Spring MVC 3 Controller

For outputing String as text/plain use:

@RequestMapping(value="/foo", method=RequestMethod.GET, produces="text/plain")
@ResponseBody
public String foo() {
    return "bar";
}

How to sort a List of objects by their date (java collections, List<Object>)

In Java 8, it's now as simple as:

movieItems.sort(Comparator.comparing(Movie::getDate));

java.lang.OutOfMemoryError: Java heap space in Maven

To temporarily work around this problem, I found the following to be the quickest way:

export JAVA_TOOL_OPTIONS="-Xmx1024m -Xms1024m"

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

ReflectionException: Class ClassName does not exist - Laravel

Check file/folder permissions

I struggled with this error today, and no amount of cache, config, autoload clears did anything to help. To add to the confusion, the error was thrown if initiated by a web request, but accessing the class in tinker worked fine.

After checking for typo's, syntax errors, and incorrect namespaces, I ended up discovering it was a file permission issue. The folder and file containing my class did not have appropriate permissions so it was throwing this error. The incorrect permission level I had was 771 (folder) and 660 (file), by changing it to 775 and 664 I was able to get it working.

My understanding of the different behaviors is that when running from the command line it was reading the file as my user (which had all the permissions it needed), but when initiated from the web it uses the "other" permission group which could do nothing.

How to use BigInteger?

BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.

bash: pip: command not found

It might be the root permission. I tried exit root login, use

sudo su -l root
pip <command>

that works for me

How to format a date using ng-model?

I've created a simple directive to enable standard input[type="date"] form elements to work correctly with AngularJS ~1.2.16.

Look here: https://github.com/betsol/angular-input-date

And here's the demo: http://jsfiddle.net/F2LcY/1/

How to convert SecureString to System.String?

Final working solution according to sclarke81 solution and John Flaherty fixes is:

    public static class Utils
    {
        /// <remarks>
        /// This method creates an empty managed string and pins it so that the garbage collector
        /// cannot move it around and create copies. An unmanaged copy of the the secure string is
        /// then created and copied into the managed string. The action is then called using the
        /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
        /// contents. The managed string is unpinned so that the garbage collector can resume normal
        /// behaviour and the unmanaged string is freed.
        /// </remarks>
        public static T UseDecryptedSecureString<T>(this SecureString secureString, Func<string, T> action)
        {
            int length = secureString.Length;
            IntPtr sourceStringPointer = IntPtr.Zero;

            // Create an empty string of the correct size and pin it so that the GC can't move it around.
            string insecureString = new string('\0', length);
            var insecureStringHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);

            IntPtr insecureStringPointer = insecureStringHandler.AddrOfPinnedObject();

            try
            {
                // Create an unmanaged copy of the secure string.
                sourceStringPointer = Marshal.SecureStringToBSTR(secureString);

                // Use the pointers to copy from the unmanaged to managed string.
                for (int i = 0; i < secureString.Length; i++)
                {
                    short unicodeChar = Marshal.ReadInt16(sourceStringPointer, i * 2);
                    Marshal.WriteInt16(insecureStringPointer, i * 2, unicodeChar);
                }

                return action(insecureString);
            }
            finally
            {
                // Zero the managed string so that the string is erased. Then unpin it to allow the
                // GC to take over.
                Marshal.Copy(new byte[length * 2], 0, insecureStringPointer, length * 2);
                insecureStringHandler.Free();

                // Zero and free the unmanaged string.
                Marshal.ZeroFreeBSTR(sourceStringPointer);
            }
        }

        /// <summary>
        /// Allows a decrypted secure string to be used whilst minimising the exposure of the
        /// unencrypted string.
        /// </summary>
        /// <param name="secureString">The string to decrypt.</param>
        /// <param name="action">
        /// Func delegate which will receive the decrypted password as a string object
        /// </param>
        /// <returns>Result of Func delegate</returns>
        /// <remarks>
        /// This method creates an empty managed string and pins it so that the garbage collector
        /// cannot move it around and create copies. An unmanaged copy of the the secure string is
        /// then created and copied into the managed string. The action is then called using the
        /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
        /// contents. The managed string is unpinned so that the garbage collector can resume normal
        /// behaviour and the unmanaged string is freed.
        /// </remarks>
        public static void UseDecryptedSecureString(this SecureString secureString, Action<string> action)
        {
            UseDecryptedSecureString(secureString, (s) =>
            {
                action(s);
                return 0;
            });
        }
    }

How to export data with Oracle SQL Developer?

In version 3, they changed "export" to "unload". It still functions more or less the same.

Enable Hibernate logging

Spring Boot, v2.3.0.RELEASE

Recommended (In application.properties):

logging.level.org.hibernate.SQL=DEBUG //logs all SQL DML statements
logging.level.org.hibernate.type=TRACE //logs all JDBC parameters 

parameters

Note:
The above will not give you a pretty-print though.
You can add it as a configuration:

properties.put("hibernate.format_sql", "true");

or as per below.

Works but NOT recommended

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Reason: It's better to let the logging framework manage/optimize the output for you + it doesn't give you the prepared statement parameters.

Cheers

Breaking out of a for loop in Java

If for some reason you don't want to use the break instruction (if you think it will disrupt your reading flow next time you will read your programm, for example), you can try the following :

boolean test = true;
for (int i = 0; i < 1220 && test; i++) {
    System.out.println(i);
    if (i == 20) {
        test = false;
    }
 }

The second arg of a for loop is a boolean test. If the result of the test is true, the loop will stop. You can use more than just an simple math test if you like. Otherwise, a simple break will also do the trick, as others said :

for (int i = 0; i < 1220 ; i++) {
    System.out.println(i);
    if (i == 20) {
        break;
    }
 }

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

Export HTML table to pdf using jspdf

Use get(0) instead of html(). In other words, replace

doc.fromHTML($('#htmlTableId').html(), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

with

doc.fromHTML($('#htmlTableId').get(0), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

How to set selected value of jquery select2?

In Select2 V.4

use $('selector').select2().val(value_to_select).trigger('change');

I think it should work

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

Type converting slices of interfaces

The thing you are missing is that T and interface{} which holds a value of T have different representations in memory so can't be trivially converted.

A variable of type T is just its value in memory. There is no associated type information (in Go every variable has a single type known at compile time not at run time). It is represented in memory like this:

  • value

An interface{} holding a variable of type T is represented in memory like this

  • pointer to type T
  • value

So coming back to your original question: why go does't implicitly convert []T to []interface{}?

Converting []T to []interface{} would involve creating a new slice of interface {} values which is a non-trivial operation since the in-memory layout is completely different.

Xcode 9 Swift Language Version (SWIFT_VERSION)

maybe you need to download toolchain. This error occurs when you don't have right version of swift compiler.

Proper way to return JSON using node or Express

That response is a string too, if you want to send the response prettified, for some awkward reason, you could use something like JSON.stringify(anObject, null, 3)

It's important that you set the Content-Type header to application/json, too.

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);

// > {"a":1}

Prettified:

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }, null, 3));
});
app.listen(3000);

// >  {
// >     "a": 1
// >  }

I'm not exactly sure why you want to terminate it with a newline, but you could just do JSON.stringify(...) + '\n' to achieve that.

Express

In express you can do this by changing the options instead.

'json replacer' JSON replacer callback, null by default

'json spaces' JSON response spaces for formatting, defaults to 2 in development, 0 in production

Not actually recommended to set to 40

app.set('json spaces', 40);

Then you could just respond with some json.

res.json({ a: 1 });

It'll use the 'json spaces' configuration to prettify it.

Monitor network activity in Android Phones

Without root, you can use debug proxies like Charlesproxy&Co.

How to convert a boolean array to an int array

A funny way to do this is

>>> np.array([True, False, False]) + 0 
np.array([1, 0, 0])

How to check if a Constraint exists in Sql server?

You can use the one above with one caveat:

IF EXISTS(
    SELECT 1 FROM sys.foreign_keys 
    WHERE parent_object_id = OBJECT_ID(N'dbo.TableName') 
        AND name = 'CONSTRAINTNAME'
)
BEGIN 
    ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME 
END 

Need to use the name = [Constraint name] since a table may have multiple foreign keys and still not have the foreign key being checked for

How to apply a CSS filter to a background image

$fondo: url(/grid/assets/img/backimage.png);    
{ padding: 0; margin: 0; } 
body { 
    ::before{
        content:"" ; height: 1008px; width: 100%; display: flex; position: absolute; 
        background-image: $fondo ; background-repeat: no-repeat ; background-position: 
        center; background-size: cover; filter: blur(1.6rem);
    }
}

Neither BindingResult nor plain target object for bean name available as request attribute

In the controller, you need to add the login object as an attribute of the model:

model.addAttribute("login", new Login());

Like this:

@RequestMapping(value = "/", method = RequestMethod.GET) 
public String displayLogin(Model model) { 
    model.addAttribute("login", new Login()); 
    return "login"; 
}

WCF change endpoint address at runtime

This is a simple example of what I used for a recent test. You need to make sure that your security settings are the same on the server and client.

var myBinding = new BasicHttpBinding();
myBinding.Security.Mode = BasicHttpSecurityMode.None;
var myEndpointAddress = new EndpointAddress("http://servername:8732/TestService/");
client = new ClientTest(myBinding, myEndpointAddress);
client.someCall();

How to get file extension from string in C++

Assuming you have access to STL:

std::string filename("filename.conf");
std::string::size_type idx;

idx = filename.rfind('.');

if(idx != std::string::npos)
{
    std::string extension = filename.substr(idx+1);
}
else
{
    // No extension found
}

Edit: This is a cross platform solution since you didn't mention the platform. If you're specifically on Windows, you'll want to leverage the Windows specific functions mentioned by others in the thread.

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

The first: Please make sure your port '12345' is opening and then when you using a different network. You have to use the IP address in LAN. Don't use the 'localhost' or '127.0.0.1'. The solution here is: In server

host = '192.168.1.12' #Ip address in LAN network

In client

host = '27.32.123.32' # external IP Address

Hope it works for you

SQL Server NOLOCK and joins

I was pretty sure that you need to specify the NOLOCK for each JOIN in the query. But my experience was limited to SQL Server 2005.

When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:

[SQL Server 2008 R2]

All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

[SQL Server 2005]

In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

Additionally, point to note - and this applies to both 2005 and 2008:

The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the OPTION (EXPAND VIEWS) query hint.

How can I do an asc and desc sort using underscore.js?

You can use .sortBy, it will always return an ascending list:

_.sortBy([2, 3, 1], function(num) {
    return num;
}); // [1, 2, 3]

But you can use the .reverse method to get it descending:

var array = _.sortBy([2, 3, 1], function(num) {
    return num;
});

console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]

Or when dealing with numbers add a negative sign to the return to descend the list:

_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
    return -num;
}); // [3, 2, 1, 0, -1, -2, -3]

Under the hood .sortBy uses the built in .sort([handler]):

// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]

// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
    // a = current item in array
    // b = next item in array
    return b - a;
});

Scroll Automatically to the Bottom of the Page

you can do this too with animation, its very simple

$('html, body').animate({
   scrollTop: $('footer').offset().top
   //scrollTop: $('#your-id').offset().top
   //scrollTop: $('.your-class').offset().top
}, 'slow');

hope helps, thank you

How can I ssh directly to a particular directory?

going one step further with the -t idea. I keep a set of scripts calling the one below to go to specific places in my frequently visited hosts. I keep them all in ~/bin and keep that directory in my path.

#!/bin/bash

# does ssh session switching to particular directory
# $1, hostname from config file 
# $2, directory to move to after login
# can save this as say 'con' then
# make another script calling this one, e.g.
# con myhost repos/i2c

ssh -t $1 "cd $2; exec \$SHELL --login"

Remove all html tags from php string

use this regex: /<[^<]+?>/g

$val = preg_replace('/<[^<]+?>/g', ' ', $row_get_Business['business_description']);

$businessDesc = substr(val,0,110);

from your example should stay: Ref no: 30001

IE9 jQuery AJAX with CORS returns "Access is denied"

Complete instructions on how to do this using the "jQuery-ajaxTransport-XDomainRequest" plugin can be found here: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest#instructions

This plugin is actively supported, and handles HTML, JSON and XML. The file is also hosted on CDNJS, so you can directly drop the script into your page with no additional setup: http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

Create a new database with MySQL Workbench

  1. Launch MySQL Workbench.
  2. On the left pane of the welcome window, choose a database to connect to under "Open Connection to Start Querying".
  3. The query window will open. On its left pane, there is a section titled "Object Browser", which shows the list of databases. (Side note: The terms "schema" and "database" are synonymous in this program.)
  4. Right-click on one of the existing databases and click "Create Schema...". This will launch a wizard that will help you create a database.

If you'd prefer to do it in SQL, enter this query into the query window:

CREATE SCHEMA Test

Press CTRL + Enter to submit it, and you should see confirmation in the output pane underneath the query window. You'll have to right-click on an existing schema in the Object panel and click "Refresh All" to see it show up, though.