Programs & Examples On #Unity application block

Add context path to Spring Boot application

The correct properties are

server.servlet.path

to configure the path of the DispatcherServlet

and

server.servlet.context-path

to configure the path of the applications context below that.

Custom Card Shape Flutter SDK

An Alternative Solution to the above

Card(
  shape: RoundedRectangleBorder(
     borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
  color: Colors.white,
  child: ...
)

You can use BorderRadius.only() to customize the corners you wish to manage.

SVN: Is there a way to mark a file as "do not commit"?

You can configure the "ignore-on-commit" changelist directly with TortoiseSVN. No need to configure any other changelist including all the others files

1) Click "SVN Commit..." (we will not commit, just a way to find a graphical menu for the changelist) 2) On the list Right click on the file you want to exclude. 3) Menu: move to changelist > ignore-on-commit

The next time you do a SVN Commit... The files will appear unchecked at the end of the list, under the category ignore-on-commit.

Tested with : TortoiseSVN 1.8.7, Build 25475 - 64 Bit , 2014/05/05 20:52:12, Subversion 1.8.9, -release

Asynchronously load images with jQuery

$(<img />).attr('src','http://somedomain.com/image.jpg');

Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.

How to end a session in ExpressJS

Never mind, it's req.session.destroy();

this.getClass().getClassLoader().getResource("...") and NullPointerException

When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.

Where is localhost folder located in Mac or Mac OS X?

For posterity

I never use PHP so I completely forgot where apache was installed on my mac as it was running on port 8080 mocking me, installed in a non-standard path. After giving up on the internet, I tried this...

httpd -t -D DUMP_INCLUDES

Because httpd was running it produced the httpd.config path and then the clouds parted and the sun shown brightly on my face. Victory! as within it lies the path to localhost.

ServerRoot "/your/path"

program cant start because php5.dll is missing

Download php5.dll (http://windows.php.net/download/) and copy it to apache/bin folder. That solved it for me (Win 7 64 bit apache 32 bit)

EDIT: Start with the non-thread safe version.

Sending message through WhatsApp

I found the following solution, first you'll need the whatsapp id:

Matching with reports from some other threads here and in other forums the login name I found was some sort of: international area code without the 0's or + in the beginning + phone number without the first 0 + @s.whatsapp.net

For example if you live in the Netherlands and having the phone number 0612325032 it would be [email protected] -> +31 for the Netherlands without the 0's or + and the phone number without the 0.

public void sendWhatsAppMessageTo(String whatsappid) {

Cursor c = getSherlockActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
        new String[] { ContactsContract.Contacts.Data._ID }, ContactsContract.Data.DATA1 + "=?",
        new String[] { whatsappid }, null);
c.moveToFirst();

Intent whatsapp = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
c.close();

 if (whatsapp != null) {

startActivity(whatsapp);      

} else {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
//download for example after dialog
                Uri uri = Uri.parse("market://details?id=com.whatsapp");
                Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
    }

}

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

Something like

select *
  from foo
 where regexp_like( col1, '[^[:alpha:]]' ) ;

should work

SQL> create table foo( col1 varchar2(100) );

Table created.

SQL> insert into foo values( 'abc' );

1 row created.

SQL> insert into foo values( 'abc123' );

1 row created.

SQL> insert into foo values( 'def' );

1 row created.

SQL> select *
  2    from foo
  3   where regexp_like( col1, '[^[:alpha:]]' ) ;

COL1
--------------------------------------------------------------------------------
abc123

How can I find the dimensions of a matrix in Python?

If you are using NumPy arrays, shape can be used. For example

  >>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
  >>> a
  array([[[ 1,  2,  3],
         [ 1,  2,  3]],

         [[12,  3,  4],
         [ 2,  1,  3]]])
 >>> a.shape
 (2, 2, 3)

Adding to an ArrayList Java

Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)

Recommended reading. Lists in the Java Tutorial

Check for a substring in a string in Oracle without LIKE

Databases are heavily optimized for common usage scenarios (and LIKE is one of those).

You won't find a faster way of doing your search if you want to stay on the DB-level.

How to change the default GCC compiler in Ubuntu?

Now, there is gcc-4.9 available for Ubuntu/precise.

Create a group of compiler alternatives where the distro compiler has a higher priority:

root$ VER=4.6 ; PRIO=60
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

root$ VER=4.9 ; PRIO=40
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

NOTE: g++ version is changed automatically with a gcc version switch. cpp-bin has to be done separately as there exists a "cpp" master alternative.

List available compiler alternatives:

root$ update-alternatives --list gcc
root$ update-alternatives --list cpp-bin

To select manually version 4.9 of gcc, g++ and cpp, do:

root$ update-alternatives --config gcc
root$ update-alternatives --config cpp-bin

Check compiler versions:

root$ for i in gcc g++ cpp ; do $i --version ; done

Restore distro compiler settings (here: back to v4.6):

root$ update-alternatives --auto gcc
root$ update-alternatives --auto cpp-bin

Circle line-segment collision detection algorithm?

This Java Function returns a DVec2 Object. It takes a DVec2 for the center of the circle, the radius of the circle, and a Line.

public static DVec2 CircLine(DVec2 C, double r, Line line)
{
    DVec2 A = line.p1;
    DVec2 B = line.p2;
    DVec2 P;
    DVec2 AC = new DVec2( C );
    AC.sub(A);
    DVec2 AB = new DVec2( B );
    AB.sub(A);
    double ab2 = AB.dot(AB);
    double acab = AC.dot(AB);
    double t = acab / ab2;

    if (t < 0.0) 
        t = 0.0;
    else if (t > 1.0) 
        t = 1.0;

    //P = A + t * AB;
    P = new DVec2( AB );
    P.mul( t );
    P.add( A );

    DVec2 H = new DVec2( P );
    H.sub( C );
    double h2 = H.dot(H);
    double r2 = r * r;

    if(h2 > r2) 
        return null;
    else
        return P;
}

Types in MySQL: BigInt(20) vs Int(20)

As far as I know, there is only one small difference is when you are trying to insert value which is out of range.

In examples I'll use 401421228216, which is 101110101110110100100011101100010111000 (length 39 characters)

  • If you have INT(20) for system this means allocate in memory minimum 20 bits. But if you'll insert value that bigger than 2^20, it will be stored successfully, only if it's less then INT(32) -> 2147483647 (or 2 * INT(32) -> 4294967295 for UNSIGNED)

Example:

mysql> describe `test`;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| id    | int(20) unsigned | YES  |     | NULL    |       |
+-------+------------------+------+-----+---------+-------+
1 row in set (0,00 sec)

mysql> INSERT INTO `test` (`id`) VALUES (401421228216);
ERROR 1264 (22003): Out of range value for column 'id' at row 1

mysql> SET sql_mode = '';
Query OK, 0 rows affected, 1 warning (0,00 sec)

mysql> INSERT INTO `test` (`id`) VALUES (401421228216);
Query OK, 1 row affected, 1 warning (0,06 sec)

mysql> SELECT * FROM `test`;
+------------+
| id         |
+------------+
| 4294967295 |
+------------+
1 row in set (0,00 sec)
  • If you have BIGINT(20) for system this means allocate in memory minimum 20 bits. But if you'll insert value that bigger than 2^20, it will be stored successfully, if it's less then BIGINT(64) -> 9223372036854775807 (or 2 * BIGINT(64) -> 18446744073709551615 for UNSIGNED)

Example:

mysql> describe `test`;
+-------+---------------------+------+-----+---------+-------+
| Field | Type                | Null | Key | Default | Extra |
+-------+---------------------+------+-----+---------+-------+
| id    | bigint(20) unsigned | YES  |     | NULL    |       |
+-------+---------------------+------+-----+---------+-------+
1 row in set (0,00 sec)

mysql> INSERT INTO `test` (`id`) VALUES (401421228216);
Query OK, 1 row affected (0,04 sec)

mysql> SELECT * FROM `test`;
+--------------+
| id           |
+--------------+
| 401421228216 |
+--------------+
1 row in set (0,00 sec)

Get google map link with latitude/longitude

The suggested answer no longer works after 2014. Now you have to use Google Maps Embed API for loading into iframe.

Here is the link for the question and solution.

If you are using Angular like me you won't be able to load the google maps in iframe because of XSS security issue. For that you need to sanitise the URL with Pipe from angular.

Here is the link to do so.

All the suggestions are tested and works 100% as of today.

How to remove non UTF-8 characters from text file

Your method must read byte by byte and fully understand and appreciate the byte wise construction of characters. The simplest method is to use an editor which will read anything but only output UTF-8 characters. Textpad is one choice.

How to initialize std::vector from C-style array?

You use the word initialize so it's unclear if this is one-time assignment or can happen multiple times.

If you just need a one time initialization, you can put it in the constructor and use the two iterator vector constructor:

Foo::Foo(double* w, int len) : w_(w, w + len) { }

Otherwise use assign as previously suggested:

void set_data(double* w, int len)
{
    w_.assign(w, w + len);
}

System.Net.WebException: The operation has timed out

Close/dispose your WebResponse object.

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

Here's what Oracle's documentation has to say:

By default the heap dump is created in a file called java_pid.hprof in the working directory of the VM, as in the example above. You can specify an alternative file name or directory with the -XX:HeapDumpPath= option. For example -XX:HeapDumpPath=/disk2/dumps will cause the heap dump to be generated in the /disk2/dumps directory.

Regex to match only uppercase "words" with some exceptions

To some extent, this is going to vary by the "flavour" of RegEx you're using. The following is based on .NET RegEx, which uses \b for word boundaries. In the last example, it also uses negative lookaround (?<!) and (?!) as well as non-capturing parentheses (?:)

Basically, though, if the terms always contain at least one uppercase letter followed by at least one number, you can use

\b[A-Z]+[0-9]+\b

For all-uppercase and numbers (total must be 2 or more):

\b[A-Z0-9]{2,}\b

For all-uppercase and numbers, but starting with at least one letter:

\b[A-Z][A-Z0-9]+\b

The granddaddy, to return items that have any combination of uppercase letters and numbers, but which are not single letters at the beginning of a line and which are not part of a line that is all uppercase:

(?:(?<!^)[A-Z]\b|(?<!^[A-Z0-9 ]*)\b[A-Z0-9]+\b(?![A-Z0-9 ]$))

breakdown:

The regex starts with (?:. The ?: signifies that -- although what follows is in parentheses, I'm not interested in capturing the result. This is called "non-capturing parentheses." Here, I'm using the paretheses because I'm using alternation (see below).

Inside the non-capturing parens, I have two separate clauses separated by the pipe symbol |. This is alternation -- like an "or". The regex can match the first expression or the second. The two cases here are "is this the first word of the line" or "everything else," because we have the special requirement of excluding one-letter words at the beginning of the line.

Now, let's look at each expression in the alternation.

The first expression is: (?<!^)[A-Z]\b. The main clause here is [A-Z]\b, which is any one capital letter followed by a word boundary, which could be punctuation, whitespace, linebreak, etc. The part before that is (?<!^), which is a "negative lookbehind." This is a zero-width assertion, which means it doesn't "consume" characters as part of a match -- not really important to understand that here. The syntax for negative lookbehind in .NET is (?<!x), where x is the expression that must not exist before our main clause. Here that expression is simply ^, or start-of-line, so this side of the alternation translates as "any word consisting of a single, uppercase letter that is not at the beginning of the line."

Okay, so we're matching one-letter, uppercase words that are not at the beginning of the line. We still need to match words consisting of all numbers and uppercase letters.

That is handled by a relatively small portion of the second expression in the alternation: \b[A-Z0-9]+\b. The \bs represent word boundaries, and the [A-Z0-9]+ matches one or more numbers and capital letters together.

The rest of the expression consists of other lookarounds. (?<!^[A-Z0-9 ]*) is another negative lookbehind, where the expression is ^[A-Z0-9 ]*. This means what precedes must not be all capital letters and numbers.

The second lookaround is (?![A-Z0-9 ]$), which is a negative lookahead. This means what follows must not be all capital letters and numbers.

So, altogether, we are capturing words of all capital letters and numbers, and excluding one-letter, uppercase characters from the start of the line and everything from lines that are all uppercase.

There is at least one weakness here in that the lookarounds in the second alternation expression act independently, so a sentence like "A P1 should connect to the J9" will match J9, but not P1, because everything before P1 is capitalized.

It is possible to get around this issue, but it would almost triple the length of the regex. Trying to do so much in a single regex is seldom, if ever, justfied. You'll be better off breaking up the work either into multiple regexes or a combination of regex and standard string processing commands in your programming language of choice.

Elegant way to read file into byte[] array in Java

A long time ago:

Call any of these

byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

From

http://commons.apache.org/io/

If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

Today (Java 7+ or Android API Level 26+)

Luckily, we now have a couple of convenience methods in the nio packages. For instance:

byte[] java.nio.file.Files.readAllBytes(Path path)

Javadoc here

How to block users from closing a window in Javascript?

If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.

How do I revert an SVN commit?

While the suggestions given already may work for some people, it does not work for my case. When performing the merge, users at rev 1443 who update to rev 1445, still sync all files changed in 1444 even though they are equal to 1443 from the merge. I needed end users to not see the update at all.

If you want to completely hide the commit it is possible by creating a new branch at correct revision and then swapping the branches. The only thing is you need to remove and re add all locks.

copy -r 1443 file:///<your_branch> file:///<your_branch_at_correct_rev>
svn move file:///<your_branch> file:///<backup_branch>
svn move file:///<your_branch_at_correct_rev> file:///<your_branch>

This worked for me, perhaps it will be helpful to someone else out there =)

String.Replace ignoring case

You can also try the Regex class.

var regex = new Regex( "camel", RegexOptions.IgnoreCase ); var newSentence = regex.Replace( sentence, "horse" );

Simple Java Client/Server Program

My try to do client socket program

server reads file and print it to console and copies it to output file

Server Program:

package SocketProgramming.copy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerRecieveFile {
    public static void main(String[] args) throws IOException {
        // TODO Auto-enerated method stub
        int filesize = 1022386;
        int bytesRead;
        int currentTot;
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        ServerSocket serverSocket = new ServerSocket(15123);
        while (true) {
            Socket socket = serverSocket.accept();
            byte[] bytearray = new byte[filesize];
            InputStream is = socket.getInputStream();
            File copyFileName = new File("C:/Users/Username/Desktop/Output_file.txt");
            FileOutputStream fos = new FileOutputStream(copyFileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(bytearray, 0, bytearray.length);
            currentTot = bytesRead;
            do {
                bytesRead = is.read(bytearray, currentTot,
                        (bytearray.length - currentTot));
                if (bytesRead >= 0)
                    currentTot += bytesRead;
            } while (bytesRead > -1);
            bos.write(bytearray, 0, currentTot);
            bos.flush();
            bos.close();
            socket.close();
        }
    }
}

Client program:

package SocketProgramming.copy;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSendFile {
    public static void main(String[] args) throws UnknownHostException,
            IOException {
        // final String FILE_NAME="C:/Users/Username/Desktop/Input_file.txt";
        final String FILE_NAME = "C:/Users/Username/Desktop/Input_file.txt";
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        Socket socket = new Socket(InetAddress.getLocalHost(), 15123);
        System.out.println("Accepted connection : " + socket);
        File transferFile = new File(FILE_NAME);
        byte[] bytearray = new byte[(int) transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read(bytearray, 0, bytearray.length);
        OutputStream os = socket.getOutputStream();
        System.out.println("Sending Files...");

        os.write(bytearray, 0, bytearray.length);

        BufferedReader r = new BufferedReader(new FileReader(FILE_NAME));
        String as = "", line = null;
        while ((line = r.readLine()) != null) {
            as += line + "\n";
            // as += line;

        }
        System.out.print("Input File contains following data: " + as);
        os.flush();
        fin.close();
        bin.close();
        os.close();
        socket.close();

        System.out.println("File transfer complete");
    }
}

How does Facebook Sharer select Images and other metadata when sharing my URL?

As of 2013, if you're using facebook.com/sharer.php (PHP) you can simply make any button/link like:

<a class="btn" target="_blank" href="http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo urlencode(YOUR_TITLE);?>&amp;p[summary]=<?php echo urlencode(YOUR_PAGE_DESCRIPTION) ?>&amp;p[url]=<?php echo urlencode(YOUR_PAGE_URL); ?>&amp;p[images][0]=<?php echo urlencode(YOUR_LINK_THUMBNAIL); ?>">share on facebook</a>

Link query parameters:

p[title] = Define a page title
p[summary] = An URL description, most likely describing the contents of the page
p[url] = The absolute URL for the page you're sharing 
p[images][0] = The URL of the thumbnail image to be used as post thumbnail on facebook

It's plain simple: you do not need any js or other settings. Is just an HTML raw link. Style the A tag in any way you want to.

How do I activate a virtualenv inside PyCharm's terminal?

I have a solution that worked on my Windows 7 machine.

I believe PyCharm's terminal is a result of it running cmd.exe, which will load the Windows PATH variable, and use the version of Python that it finds first within that PATH. To edit this variable, right click My Computer --> Properties --> Advanced System Settings --> Advanced tab --> Environment Variables... button. Within the System variables section, select and edit the PATH variable.

Here is the relevant part of my PATH before editing:

C:\Python27\;
C:\Python27\Lib\site-packages\pip\;
C:\Python27\Scripts;
C:\Python27\Lib\site-packages\django\bin;

...and after editing PATH (only 3 lines now):

C:[project_path]\virtualenv-Py2.7_Dj1.7\Lib\site-packages\pip;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Scripts;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Lib\site-packages\django\bin;

To test this, open a new windows terminal (Start --> type in cmd and hit Enter) and see if it's using your virtual environment. If that works, restart PyCharm and then test it out in PyCharm's terminal.

Python os.path.join on Windows

Consent with @georg-

I would say then why we need lame os.path.join- better to use str.join or unicode.join e.g.

sys.path.append('{0}'.join(os.path.dirname(__file__).split(os.path.sep)[0:-1]).format(os.path.sep))

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Detecting iOS / Android Operating system

Solution 1: User Agent Sniffing

For Android and iPhone:

if( /Android|webOS|iPhone|iPad|iPod|Opera Mini/i.test(navigator.userAgent) ) {
 // run your code here
}

If you wanna detect all mobile devices including blackberry and Windows phone then you can use this comprehensive version:

var deviceIsMobile = false; //At the beginning we set this flag as false. If we can detect the device is a mobile device in the next line, then we set it as true.


if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) 
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) {
   deviceIsMobile = true;
}

if(deviceIsMobile){
    // run your code here
}

Cons: User agent strings are changing and getting updated as new phones and brands are coming day by day. So you need to keep this list updated if you wanna support all mobile devices.

Solution 2: mobile detect JS library

You can use the mobile detect JS library to do this.

Cons: These JavaScript-based device detection features may ONLY work for the newest generation of smartphones, such as the iPhone, Android and Palm WebOS devices. These device detection features may NOT work for older smartphones which had poor support for JavaScript, including older BlackBerry, PalmOS, and Windows Mobile devices.

How do I exit from the text window in Git?

Since you are learning Git, know that this has little to do with git but with the text editor configured for use. In vim, you can press i to start entering text and save by pressing esc and :wq and enter, this will commit with the message you typed. In your current state, to just come out without committing, you can do :q instead of the :wq as mentioned above.

Alternatively, you can just do git commit -m '<message>' instead of having git open the editor to type the message.

Note that you can also change the editor and use something you are comfortable with ( like notepad) - How can I set up an editor to work with Git on Windows?

How to setup virtual environment for Python in VS Code?

Have you activated your environment? Also you could try this: vscode select venv

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

If your dbname, username, password, etc strings lengths exceed values outlined at https://dev.mysql.com/doc/refman/5.7/en/grant-tables.html#grant-tables-scope-column-properties , you might also fail to log in, as this was in my case.

How to run a single RSpec test?

For model, it will run case on line number 5 only

bundle exec rspec spec/models/user_spec.rb:5

For controller : it will run case on line number 5 only

bundle exec rspec spec/controllers/users_controller_spec.rb:5

For signal model or controller remove line number from above

To run case on all models

bundle exec rspec spec/models

To run case on all controller

bundle exec rspec spec/controllers

To run all cases

 bundle exec rspec 

ASP.Net MVC How to pass data from view to controller

In case you don't want/need to post:

@Html.ActionLink("link caption", "actionName", new { Model.Page })  // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);

[HttpGet]
public ActionResult actionName(int reportID)
{

Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)

Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.

Adding ASP.NET MVC5 Identity Authentication to an existing project

I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.

Overview

IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.

For more information, e.g.

  • support for MembershipReboot and ASP.NET Identity based user stores
  • support for additional Katana authentication middleware (e.g. Google, Twitter, Facebook etc)
  • support for EntityFramework based persistence of configuration
  • support for WS-Federation
  • extensibility

check out the documentation and the demo.

How do I get unique elements in this array?

You can just use the method uniq. Assuming your array is ary, call:

ary.uniq{|x| x.user_id}

and this will return a set with unique user_ids.

How to pass query parameters with a routerLink

<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/   \______________/\_________/ \_________/ \__/
 |           |            |            |        |
scheme    authority      path        query   fragment

For more info - https://angular.io/guide/router#query-parameters-and-fragments

Get Multiple Values in SQL Server Cursor

This should work:

DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  

       --Do stuff with scalar values

       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

Creating a triangle with for loops

private static void printStar(int x) {
    int i, j;
    for (int y = 0; y < x; y++) { // number of row of '*'

        for (i = y; i < x - 1; i++)
            // number of space each row
            System.out.print(' ');

        for (j = 0; j < y * 2 + 1; j++)
            // number of '*' each row
            System.out.print('*');

        System.out.println();
    }
}

Split string with JavaScript

var wrapper = $(document.body);

strings = [
    "19 51 2.108997",
    "20 47 2.1089"
];

$.each(strings, function(key, value) {
    var tmp = value.split(" ");
    $.each([
        tmp[0] + " " + tmp[1],
        tmp[2]
    ], function(key, value) {
        $("<span>" + value + "</span>").appendTo(wrapper);
    }); 
});

Why do I have ORA-00904 even when the column is present?

It could be a case-sensitivity issue. Normally tables and columns are not case sensitive, but they will be if you use quotation marks. For example:

create table bad_design("goodLuckSelectingThisColumn" number);

How to connect from windows command prompt to mysql command line

syntax to open mysql on window terminal as:

mysql -u -p

e.g. mysql -uroot -proot

where: -u followed by username of your database , which you provided at the time of installatin and -p followed by password

Assumption: Assuming that mysql bin already included in path environment variable. if not included in path you can go till mysql bin folder and then run above command. if you want to know how to set path environment variable

Add numpy array as column to Pandas data frame

You can add and retrieve a numpy array from dataframe using this:

import numpy as np
import pandas as pd

df = pd.DataFrame({'b':range(10)}) # target dataframe
a = np.random.normal(size=(10,2)) # numpy array
df['a']=a.tolist() # save array
np.array(df['a'].tolist()) # retrieve array

This builds on the previous answer that confused me because of the sparse part and this works well for a non-sparse numpy arrray.

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

Prevent overwriting a file using cmd if exist

As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.

I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (

The correct version, with the space before the bracket, would be

If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
 start "\\filer\repo\lab\software\myapp\setup.exe"
 pause
) 

Getting raw SQL query string from PDO prepared statements

You can extend PDOStatement class to capture the bounded variables and store them for later use. Then 2 methods may be added, one for variable sanitizing ( debugBindedVariables ) and another to print the query with those variables ( debugQuery ):

class DebugPDOStatement extends \PDOStatement{
  private $bound_variables=array();
  protected $pdo;

  protected function __construct($pdo) {
    $this->pdo = $pdo;
  }

  public function bindValue($parameter, $value, $data_type=\PDO::PARAM_STR){
    $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>$value);
    return parent::bindValue($parameter, $value, $data_type);
  }

  public function bindParam($parameter, &$variable, $data_type=\PDO::PARAM_STR, $length=NULL , $driver_options=NULL){
    $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>&$variable);
    return parent::bindParam($parameter, $variable, $data_type, $length, $driver_options);
  }

  public function debugBindedVariables(){
    $vars=array();

    foreach($this->bound_variables as $key=>$val){
      $vars[$key] = $val->value;

      if($vars[$key]===NULL)
        continue;

      switch($val->type){
        case \PDO::PARAM_STR: $type = 'string'; break;
        case \PDO::PARAM_BOOL: $type = 'boolean'; break;
        case \PDO::PARAM_INT: $type = 'integer'; break;
        case \PDO::PARAM_NULL: $type = 'null'; break;
        default: $type = FALSE;
      }

      if($type !== FALSE)
        settype($vars[$key], $type);
    }

    if(is_numeric(key($vars)))
      ksort($vars);

    return $vars;
  }

  public function debugQuery(){
    $queryString = $this->queryString;

    $vars=$this->debugBindedVariables();
    $params_are_numeric=is_numeric(key($vars));

    foreach($vars as $key=>&$var){
      switch(gettype($var)){
        case 'string': $var = "'{$var}'"; break;
        case 'integer': $var = "{$var}"; break;
        case 'boolean': $var = $var ? 'TRUE' : 'FALSE'; break;
        case 'NULL': $var = 'NULL';
        default:
      }
    }

    if($params_are_numeric){
      $queryString = preg_replace_callback( '/\?/', function($match) use( &$vars) { return array_shift($vars); }, $queryString);
    }else{
      $queryString = strtr($queryString, $vars);
    }

    echo $queryString.PHP_EOL;
  }
}


class DebugPDO extends \PDO{
  public function __construct($dsn, $username="", $password="", $driver_options=array()) {
    $driver_options[\PDO::ATTR_STATEMENT_CLASS] = array('DebugPDOStatement', array($this));
    $driver_options[\PDO::ATTR_PERSISTENT] = FALSE;
    parent::__construct($dsn,$username,$password, $driver_options);
  }
}

And then you can use this inherited class for debugging purpouses.

$dbh = new DebugPDO('mysql:host=localhost;dbname=test;','user','pass');

$var='user_test';
$sql=$dbh->prepare("SELECT user FROM users WHERE user = :test");
$sql->bindValue(':test', $var, PDO::PARAM_STR);
$sql->execute();

$sql->debugQuery();
print_r($sql->debugBindedVariables());

Resulting in

SELECT user FROM users WHERE user = 'user_test'

Array ( [:test] => user_test )

In Angular, how do you determine the active route?

Here's a complete example for adding active route styling in Angular version 2.0.0-rc.1 which takes into account null root paths (e.g. path: '/')

app.component.ts -> Routes

import { Component, OnInit } from '@angular/core';
import { Routes, Router, ROUTER_DIRECTIVES } from '@angular/router';
import { LoginPage, AddCandidatePage } from './export';
import {UserService} from './SERVICES/user.service';

@Component({
  moduleId: 'app/',
  selector: 'my-app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  providers: [UserService],
  directives: [ROUTER_DIRECTIVES]
})

@Routes([
  { path: '/', component: AddCandidatePage },
  { path: 'Login', component: LoginPage }
])
export class AppComponent  { //implements OnInit

  constructor(private router: Router){}

  routeIsActive(routePath: string) {
     let currentRoute = this.router.urlTree.firstChild(this.router.urlTree.root);
     // e.g. 'Login' or null if route is '/'
     let segment = currentRoute == null ? '/' : currentRoute.segment;
     return  segment == routePath;
  }
}

app.component.html

<ul>
  <li [class.active]="routeIsActive('Login')"><a [routerLink]="['Login']" >Login</a></li>
  <li [class.active]="routeIsActive('/')"><a [routerLink]="['/']" >AddCandidate</a></li>
</ul>
<route-outlet></router-outlet>

What is a wrapper class?

Just what it sounds like: a class that "wraps" the functionality of another class or API in a simpler or merely different API.

See: Adapter pattern, Facade pattern

How to make custom error pages work in ASP.NET MVC 4

You can get errors working correctly without hacking global.cs, messing with HandleErrorAttribute, doing Response.TrySkipIisCustomErrors, hooking up Application_Error, or whatever:

In system.web (just the usual, on/off)

<customErrors mode="On">
  <error redirect="/error/401" statusCode="401" />
  <error redirect="/error/500" statusCode="500" />
</customErrors>

and in system.webServer

<httpErrors existingResponse="PassThrough" />

Now things should behave as expected, and you can use your ErrorController to display whatever you need.

Cmake is not able to find Python-libraries

Some last version of Ubuntu installs Python 3.4 by default and the CMake version from Ubuntu (2.8) only searches up to Python 3.3.

Try to add set(Python_ADDITIONAL_VERSIONS 3.4) before the find_package statement.

Remember to clean CMakeCache.txt too.

How many socket connections can a web server handle?

It looks like the answer is at least 12 million if you have a beefy server, your server software is optimized for it, you have enough clients. If you test from one client to one server, the number of port numbers on the client will be one of the obvious resource limits (Each TCP connection is defined by the unique combination of IP and port number at the source and destination).

(You need to run multiple clients as otherwise you hit the 64K limit on port numbers first)

When it comes down to it, this is a classic example of the witticism that "the difference between theory and practise is much larger in practise than in theory" - in practise achieving the higher numbers seems to be a cycle of a. propose specific configuration/architecture/code changes, b. test it till you hit a limit, c. Have I finished? If not then d. work out what was the limiting factor, e. go back to step a (rinse and repeat).

Here is an example with 2 million TCP connections onto a beefy box (128GB RAM and 40 cores) running Phoenix http://www.phoenixframework.org/blog/the-road-to-2-million-websocket-connections - they ended up needing 50 or so reasonably significant servers just to provide the client load (their initial smaller clients maxed out to early, eg "maxed our 4core/15gb box @ 450k clients").

Here is another reference for go this time at 10 million: http://goroutines.com/10m.

This appears to be java based and 12 million connections: https://mrotaru.wordpress.com/2013/06/20/12-million-concurrent-connections-with-migratorydata-websocket-server/

height: calc(100%) not working correctly in CSS

If you are styling calc in a GWT project, its parser might not parse calc for you as it did not for me... the solution is to wrap it in a css literal like this:

height: literal("-moz-calc(100% - (20px + 30px))");
height: literal("-webkit-calc(100% - (20px + 30px))");
height: literal("calc(100% - (20px + 30px))");

Converting Integer to Long

In case of a List of type Long, Adding L to end of each Integer value

List<Long> list = new ArrayList<Long>();
list  = Arrays.asList(1L, 2L, 3L, 4L);

How to implement 2D vector array?

If you know the (maximum) number of rows and columns beforehand, you can use resize() to initialize a vector of vectors and then modify (and access) elements with operator[]. Example:

int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;

std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));

// Read from matrix.
int value = matrix[1][2];

// Save to matrix.
matrix[3][1] = 5;

Another possibility is to use just one vector and split the id in several variables, access like vector[(row * columns) + column].

Swift days between two NSDates

Swift 5.2.4 solution:

import UIKit

let calendar = Calendar.current

let start = "2010-09-01"
let end = "2010-09-05"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let firstDate = dateFormatter.date(from: start)!
let secondDate = dateFormatter.date(from: end)!

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)

let components = calendar.dateComponents([Calendar.Component.day], from: date1, to: date2)

components.day  // This will return the number of day(s) between dates

Creating an abstract class in Objective-C

A simple example of creating an abstract class

// Declare a protocol
@protocol AbcProtocol <NSObject>

-(void)fnOne;
-(void)fnTwo;

@optional

-(void)fnThree;

@end

// Abstract class
@interface AbstractAbc : NSObject<AbcProtocol>

@end

@implementation AbstractAbc

-(id)init{
    self = [super init];
    if (self) {
    }
    return self;
}

-(void)fnOne{
// Code
}

-(void)fnTwo{
// Code
}

@end

// Implementation class
@interface ImpAbc : AbstractAbc

@end

@implementation ImpAbc

-(id)init{
    self = [super init];
    if (self) {
    }
    return self;
}

// You may override it    
-(void)fnOne{
// Code
}
// You may override it
-(void)fnTwo{
// Code
}

-(void)fnThree{
// Code
}

@end

Error: free(): invalid next size (fast):

I encountered a similar error. It was a noob mistake done in a hurry. Integer array without declaring size int a[] then trying to access it. C++ compiler should've caught such an error easily if it were in main. However since this particular int array was declared inside an object, it was being created at the same time as my object (many objects were being created) and the compiler was throwing a free(): invalid next size(normal) error. I thought of 2 explanations for this (please enlighten me if anyone knows more): 1.) This resulted in some random memory being assigned to it but since this wasn't accessible it was freeing up all the other heap memory just trying to find this int. 2.) The memory required by it was practically infinite for a program and to assign this it was freeing up all other memory.

A simple:

    int* a;
    class foo{ 
    foo(){
       for(i=0;i<n;i++)
           a=new int[i];
     }

Solved the problem. But it did take a lot of time trying to debug this because the compiler could not "really" find the error.

Getting the WordPress Post ID of current post

Try:

$post = $wp_query->post;

Then pass the function:

$post->ID

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

How can I use an ES6 import in Node.js?

Using the .mjs extension (as suggested in the accepted answer) in order to enable ECMAScript modules works. However, with Node.js v12, you can also enable this feature globally in your package.json file.

The official documentation states:

import statements of .js and extensionless files are treated as ES modules if the nearest parent package.json contains "type": "module".

{
  "type": "module",
  "main": "./src/index.js"
}

(Of course you still have to provide the flag --experimental-modules when starting your application.)

How do I check if a number is positive or negative in C#?

Native programmer's version. Behaviour is correct for little-endian systems.

bool IsPositive(int number)
{
   bool result = false;
   IntPtr memory = IntPtr.Zero;
   try
   {
       memory = Marshal.AllocHGlobal(4);
       if (memory == IntPtr.Zero)
           throw new OutOfMemoryException();

       Marshal.WriteInt32(memory, number);

       result = (Marshal.ReadByte(memory, 3) & 0x80) == 0;
   }
   finally
   {
       if (memory != IntPtr.Zero)
           Marshal.FreeHGlobal(memory);
   }
   return result;
}

Do not ever use this.

how to make a new line in a jupyter markdown cell

Just add <br> where you would like to make the new line.

$S$: a set of shops
<br>
$I$: a set of items M wants to get

Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html

Note that newlines using <br> does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br> as a space.

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse to convert a string into a JavaScript object. You cannot use JSON.parse to convert a JavaScript object into a JavaScript object.

//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';

//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log the following...

console.log("'"+[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]+"'");
//Logs:
'[object Object],[object Object]'

You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.

Why does this happen? Because you are starting with a string "'", then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'".

Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.

See this fiddle: http://jsfiddle.net/NrnK5/

Java "lambda expressions not supported at this language level"

If you are getting Not supported at Language 5, check this: ( For me it was in the Modules section)

Lanaguge Level 5 not supported

How to set specific window (frame) size in java swing?

Try this, but you can adjust frame size with bounds and edit title.

package co.form.Try;

import javax.swing.JFrame;

public class Form {

    public static void main(String[] args) {
        JFrame obj =new JFrame();
        obj.setBounds(10,10,700,600); 
        obj.setTitle("Application Form");
        obj.setResizable(false);                
        obj.setVisible(true);       
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

QByteArray to QString

Use QString::fromUtf16((ushort *)Data.data()), as shown in the following code example:

#include <QCoreApplication>
#include <QDebug>

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

    // QByteArray to QString
    // =====================

    const char c_test[10] = {'t', '\0', 'e', '\0', 's', '\0', 't', '\0', '\0', '\0'};
    QByteArray qba_test(QByteArray::fromRawData(c_test, 10));
    qDebug().nospace().noquote() << "qba_test[" << qba_test << "]"; // Should see: qba_test[t

    QString qstr_test = QString::fromUtf16((ushort *)qba_test.data());
    qDebug().nospace().noquote() << "qstr_test[" << qstr_test << "]"; // Should see: qstr_test[test]

    return a.exec();
}

This is an alternative solution to the one using QTextCodec. The code has been tested using Qt 5.4.

I lose my data when the container exits

You might want to look at docker volumes if you you want to persist the data in your container. Visit https://docs.docker.com/engine/tutorials/dockervolumes/. The docker documentation is a very good place to start

How can I select an element by name with jQuery?

You can use the jQuery attribute selector:

$('td[name ="tcol1"]')   // matches exactly 'tcol1'
$('td[name^="tcol"]' )   // matches those that begin with 'tcol'
$('td[name$="tcol"]' )   // matches those that end with 'tcol'
$('td[name*="tcol"]' )   // matches those that contain 'tcol'

How to set 24-hours format for date on java?

for 12-hours format:

SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("hh:mm", Locale.UK);

for 24-hours format:

SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("HH:mm", Locale.UK);

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

How to change font-size of a tag using inline css?

You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style attribute. Apparently, it has to be one using the !important specifier, which generally indicates poor logic and structure in styling.

Primarily, modify the style.css file so that it does not use !important. Failing this, add !important to the rule in style attribute. But you should aim at reducing the use of !important, not increasing it.

How to prevent a jQuery Ajax request from caching in Internet Explorer?

If you set unique parameters, then the cache does not work, for example:

$.ajax({
    url : "my_url",
    data : {
        'uniq_param' : (new Date()).getTime(),
        //other data
    }});

Getting the count of unique values in a column in bash

Here is a way to do it in the shell:

FIELD=2
cut -f $FIELD * | sort| uniq -c |sort -nr

This is the sort of thing bash is great at.

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

Why should I use an IDE?

I come at this question from the opposite direction. I was brought up in programming with very few pitstops in Makefile+Emacs land. From my very earliest compiler on DOS, Microsoft Quick C, I had an IDE to automate things. I spent many years working in Visual C++ 6.0, and as I graduated into Enterprise Java, I worked with Borland JBuilder and then settled on Eclipse, which has become very productive for me.

Throughout my initial self-teaching, college, and now professional career, I have come to learn that any major software development done solely within the IDE becomes counterproductive. I say this because most IDE's wants you to work in their peculiar I-control-how-the-world-works style. You have to slice and dice your projects along their lines. You have manage your project builds using their odd dialog boxes. Most IDE's manage complex build dependencies between projects poorly, and dependencies can be difficult to get working 100%. I have been in situations where IDE's would not produce a working build of my code unless I did a Clean/Rebuild All. Finally, there's rarely a clean way to move your software out of development and into other environments like QA or Production from an IDE. It's usually a clicky fest to get all your deployment units built, or you've got some awkward tool that the IDE vendor gives you to bundle stuff up. But again, that tool usually demands that your project and build structure absolutely conforms to their rules - and sometimes that just won't work for your projects' requirements.

I have learned that, to do large-scale development with a team, we can be the most productive if we develop our code using an IDE and do all of our builds using manually written command line scripts. (We like Apache Ant for Java development.) We've found that running our scripts out of the IDE is just a click fest or an automation nightmare for complex builds, it's much easier (and less disruptive) to alt+tab out to a shell and run the scripts there.

Manual builds requires us to miss out on some of the niceties in the modern IDE like background compilation, but what we gain is much more critical: clean and easy builds that can live in multiple environments. The "one click build" all those agile guys talk about? We have it. Our build scripts can be directly invoked by continuous integration systems as well. Having builds managed through continuous integration allows us to more formally stage and migrate your code deployments to different environments, and lets us know almost immediately when someone checks in bad code that breaks the build or unit tests.

In truth, my taking the role of build away from the IDE hasn't hurt us too badly. The intellisense and refactoring tools in Eclipse are still completely useful and valid - the background compilation simply serves to support those tools. And, Eclipse's peculiar slicing of projects has served as a very nice way to mentally break down our problem sets in a way everyone can understand (still a tad bit verbose for my tastes though). I think one of the most important things about Eclipse is the excellent SCM integrations, that's what makes team development so enjoyable. We use Subversion+Eclipse, and that has been very productive and very easy to train our people to become experts at.

Eclipse jump to closing brace

To select content use Alt + Shift + Up arrow

To select content up to the next wrapping block press this shortcut again

To go back one step press Alt + Shift + Down arrow. This is also a useful shortcut when you need to select content in a complex expression and do not want to miss something.

Windows Task Scheduler doesn't start batch file task

Try the code below:

Batchfile.bat:

cd c:\batchfilepath
net stop "SQL Server Reporting Services (MSSQLSERVER)" 
timeout /t 10
net start "SQL Server Reporting Services (MSSQLSERVER)"

What is a CSRF token? What is its importance and how does it work?

Yes, the post data is safe. But the origin of that data is not. This way somebody can trick user with JS into logging in to your site, while browsing attacker's web page.

In order to prevent that, django will send a random key both in cookie, and form data. Then, when users POSTs, it will check if two keys are identical. In case where user is tricked, 3rd party website cannot get your site's cookies, thus causing auth error.

What is the difference between application server and web server?

An application server is a machine (an executable process running on some machine, actually) that "listens" (on any channel, using any protocol), for requests from clients for whatever service it provides, and then does something based on those requests. (may or may not involve a respose to the client)

A Web server is process running on a machine that "listens" specifically on TCP/IP Channel using one of the "internet" protocols, (http, https, ftp, etc..) and does whatever it does based on those incoming requests... Generally, (as origianly defined), it fetched/generated and returned an html web page to the client, either fetched from a static html file on the server, or constructed dynamically based on parameters in the incoming client request.

JUnit Eclipse Plugin?

JUnit is part of Eclipse Java Development Tools (JDT). So, either install the JDT via Software Updates or download and install Eclipse IDE for Java Developers (actually, I'd recommend installing Eclipse IDE for Java EE Developers if you want a complete built-in environment for server side development).

You add it to a project by right clicking the project in the Package Explorer and selecting Build Path -> Add Libraries... Then simply select JUnit and click Next >.

PHP Foreach Arrays and objects

Recursive traverse object or array with array or objects elements:

function traverse(&$objOrArray)
{
    foreach ($objOrArray as $key => &$value)
    {
        if (is_array($value) || is_object($value))
        {
            traverse($value);
        }
        else
        {
            // DO SOMETHING
        }
    }
}

Current Subversion revision command

Nobody mention for Windows world SubWCRev, which, properly used, can substitute needed data into the needed places automagically, if script call SubWCRev in form SubWCRev WC_PATH TPL-FILE READY-FILE

Sample of my post-commit hook (part of)

SubWCRev.exe CustomLocations Builder.tpl  z:\Builder.bat
...
call z:\Builder.bat

where my Builder.tpl is

svn.exe export trunk z:\trunk$WCDATE=%Y%m%d$-r$WCREV$

as result, I have every time bat-file with variable part - name of dir - which corresponds to the metadata of Working Copy

Laravel use same form for create and edit

I hope this will help you!!

form.blade.php

@php
$name         = $user->name ?? null;
$email        = $user->email ?? null;
$info         = $user->info ?? null;
$role         = $user->role ?? null;
@endphp

<div class="form-group">
        {!! Form::label('name', 'Name') !!}
        {!! Form::text('name', $name, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
        {!! Form::label('email', 'Email') !!}
        {!! Form::email('email', $email, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
        {!! Form::label('role', 'Função') !!}
        {!! Form::text('role', $role, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
        {!! Form::label('info', 'Informações') !!}
        {!! Form::textarea('info', $info, ['class' => 'form-control']) !!}
</div>

<a class="btn btn-danger float-right" href="{{ route('users.index') }}">CANCELAR</a>

create.blade.php

@extends('layouts.app')

@section('title', 'Criar usuário')

@section('content')
        {!! Form::open(['action' => 'UsersController@store', 'method' => 'POST'])  !!}
            @include('users.form')
            <div class="form-group">
                {!! Form::label('password', 'Senha') !!}
                {!! Form::password('password', ['class' => 'form-control']) !!}
            </div>
            <div class="form-group">
                {!! Form::label('password', 'Confirmação de senha') !!}
                {!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
            </div>
            {!! Form::submit('ADICIONAR', array('class' => 'btn btn-primary')) !!}
        {!! Form::close() !!}
@endsection

edit.blade.php

@extends('layouts.app')

@section('title', 'Editar usuário')

@section('content')
        {!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'PUT']) !!}
            @include('users.form', compact('user'))
            {!! Form::submit('EDITAR', ['class' => 'btn btn-primary']) !!}
        {!! Form::close() !!}
        <a href="{{route('users.editPassword', $user->id)}}">Editar senha</a>
@endsection

UsersController.php

use App\User;

Class UsersController extends Controller {
  #... 
    public function create()
    {
        return view('users.create';
    }

    public function edit($id)
    {
        $user  = User::findOrFail($id);
        return view('users.edit', compact('user');
    }
}

How can I make the computer beep in C#?

In .Net 2.0, you can use Console.Beep().

// Default beep
Console.Beep();

You can also specify the frequency and length of the beep in milliseconds.

// Beep at 5000 Hz for 1 second
Console.Beep(5000, 1000);

For more information refer http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx

Node.js Web Application examples/tutorials

DailyJS has a good tutorial (long series of 24 posts) that walks you through all the aspects of building a notepad app (including all the possible extras).

Heres an overview of the tutorial: http://dailyjs.com/2010/11/01/node-tutorial/

And heres a link to all the posts: http://dailyjs.com/tags.html#nodepad

Bind a function to Twitter Bootstrap Modal Close

Bootstrap 4:

$('#myModal').on('hidden.bs.modal', function (e) {
   // call your method
})

hide.bs.modal: This event is fired immediately when the hide instance method has been called.

hidden.bs.modal: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Seeding the random number generator in Javascript

NOTE: Despite (or rather, because of) succinctness and apparent elegance, this algorithm is by no means a high-quality one in terms of randomness. Look for e.g. those listed in this answer for better results.

(Originally adapted from a clever idea presented in a comment to another answer.)

var seed = 1;
function random() {
    var x = Math.sin(seed++) * 10000;
    return x - Math.floor(x);
}

You can set seed to be any number, just avoid zero (or any multiple of Math.PI).

The elegance of this solution, in my opinion, comes from the lack of any "magic" numbers (besides 10000, which represents about the minimum amount of digits you must throw away to avoid odd patterns - see results with values 10, 100, 1000). Brevity is also nice.

It's a bit slower than Math.random() (by a factor of 2 or 3), but I believe it's about as fast as any other solution written in JavaScript.

How to set value in @Html.TextBoxFor in Razor syntax?

_x000D_
_x000D_
Tries with following it will definitely work:_x000D_
_x000D_
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })_x000D_
_x000D_
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", @Value= "3" })_x000D_
_x000D_
<input id="txtPlace" name="Destination" type="text" value="3" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset ui-mini" >
_x000D_
_x000D_
_x000D_

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

How to set the style -webkit-transform dynamically using JavaScript?

The JavaScript style names are WebkitTransformOrigin and WebkitTransform

element.style.webkitTransform = "rotate(-2deg)";

Check the DOM extension reference for WebKit here.

How to change the status bar background color and text color on iOS 7?

Goto your app info.plist

1) Set View controller-based status bar appearance to NO
2) Set Status bar style to UIStatusBarStyleLightContent

Then Goto your app delegate and paste the following code where you set your Windows's RootViewController.

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
    view.backgroundColor=[UIColor blackColor];
    [self.window.rootViewController.view addSubview:view];
}

Hope it helps.

Add data to JSONObject

The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:

JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()

JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);

Better way to convert an int to a boolean

Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.

int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
    case 0: yourBool = false; break;
    case 1: yourBool = true;  break;
    default:
        throw new InvalidOperationException("Integer value is not valid");
}

The out-of-the-box Convert won't check this; nor will yourInteger (==|!=) (0|1).

"Debug certificate expired" error in Eclipse Android plugins

The Android SDK generates a "debug" signing certificate for you in a keystore called debug.keystore.The Eclipse plug-in uses this certificate to sign each application build that is generated.

Unfortunately a debug certificate is only valid for 365 days. To generate a new one, you must delete the existing debug.keystore file. Its location is platform dependent - you can find it in Preferences -> Android -> Build -> *Default debug keystore.

If you are using Windows, follow the steps below.

DOS: del c:\user\dad.android\debug.keystore

Eclipse: In Project, Clean the project. Close Eclipse. Re-open Eclipse.

Eclipse: Start the Emulator. Remove the Application from the emulator.

If you are using Linux or Mac, follow the steps below.

Manually delete debug.keystore from the .android folder.

You can find the .android folder like this: home/username/.android

Note: the default .android file will be hidden.

So click on the places menu. Under select home folder. Under click on view, under click show hidden files and then the .android folder will be visible.

Delete debug.keystore from the .android folder.

Then clean your project. Now Android will generate a new .android folder file.

"Insufficient Storage Available" even there is lot of free space in device memory

The package manager (“installer”) has a design problem: it can’t distinguish between a bunch of possible errors and regularly comes up with the “insufficient storage” excuse.

The first steps are done: identify it’s an install problem (1.) and not related to storage shortage (2.)

  1. It happens on the console (pm install file.apk), with Google Play, other markets and manual GUI-install (for example, “clicking” on a downloaded APK file); it is not a download issue, ...
  2. Packages end up entirely on the /data partition -or- mostly on the SD card (and a little on /data). – Both places show enough space as indicated by the original poster (33 MB and >900 MB respectively) for the <20 MB package. –And– the /data partition has more than 10% free (33 MB is more than 10% of 200 MB).

Surprisingly most answers don’t take this into account...

In reality, the /data partition needs a cleanup from residues from previous installs.

  • Identify the common name of the problematic package (for example, com.abc.def)
  • Uninstall the package (for example, pm uninstall com.abc.def)
  • Check what’s left of it in data (for example, find /data -name 'com.abc.def*')
  • Delete that stuff

The installer chokes on those, returning with the wrong reason. – The interesting part is: if the package gets installed on the SD card (forced or by other means) some (all?) leftovers on /data don’t hurt... which leads to the false belief that it is indeed a space problem (more space on the SD card...)!

The Stack Overflow question where I got half of this from is Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android.

What does the "yield" keyword do?

(My below answer only speaks from the perspective of using Python generator, not the underlying implementation of generator mechanism, which involves some tricks of stack and heap manipulation.)

When yield is used instead of a return in a python function, that function is turned into something special called generator function. That function will return an object of generator type. The yield keyword is a flag to notify the python compiler to treat such function specially. Normal functions will terminate once some value is returned from it. But with the help of the compiler, the generator function can be thought of as resumable. That is, the execution context will be restored and the execution will continue from last run. Until you explicitly call return, which will raise a StopIteration exception (which is also part of the iterator protocol), or reach the end of the function. I found a lot of references about generator but this one from the functional programming perspective is the most digestable.

(Now I want to talk about the rationale behind generator, and the iterator based on my own understanding. I hope this can help you grasp the essential motivation of iterator and generator. Such concept shows up in other languages as well such as C#.)

As I understand, when we want to process a bunch of data, we usually first store the data somewhere and then process it one by one. But this naive approach is problematic. If the data volume is huge, it's expensive to store them as a whole beforehand. So instead of storing the data itself directly, why not store some kind of metadata indirectly, i.e. the logic how the data is computed.

There are 2 approaches to wrap such metadata.

  1. The OO approach, we wrap the metadata as a class. This is the so-called iterator who implements the iterator protocol (i.e. the __next__(), and __iter__() methods). This is also the commonly seen iterator design pattern.
  2. The functional approach, we wrap the metadata as a function. This is the so-called generator function. But under the hood, the returned generator object still IS-A iterator because it also implements the iterator protocol.

Either way, an iterator is created, i.e. some object that can give you the data you want. The OO approach may be a bit complex. Anyway, which one to use is up to you.

Detecting installed programs via registry

An application does not need to have any registry entry. In fact, many applications do not need to be installed at all. U3 USB sticks are a good example; the programs on them just run from the file system.

As noted, most good applications can be found via their uninstall registry key though. This is actually a pair of keys, per-user and per-machine (HKCU/HKLM - Piskvor mentioned only the HKLM one). It does not (always) give you the install directory, though.

If it's in HKCU, then you have to realise that HKEY_CURRENT_USER really means "Current User". Other users have their own HKCU entries, and their own installed software. You can't find that. Reading every HKEY_USERS hive is a disaster on corporate networks with roaming profiles. You really don't want to fetch 1000 accounts from your remote [US|China|Europe] office.

Even if an application is installed, and you know where, it may not have the same "version" notion you have. The best source is the "version" resource in the executables. That's indeed a plural, so you have to find all of them, extract version resources from all and in case of a conflict decid on something reasonable.

So - good luck. There are dozes of ways to fail.

How can I send mail from an iPhone application

MFMailComposeViewController is the way to go after the release of iPhone OS 3.0 software. You can look at the sample code or the tutorial I wrote.

jQuery - Create hidden form element on the fly

The same as David's, but without attr()

$('<input>', {
    type: 'hidden',
    id: 'foo',
    name: 'foo',
    value: 'bar'
}).appendTo('form');

How to set base url for rest in spring boot?

You can create a custom annotation for your controllers:

Use it instead of the usual @RestController on your controller classes and annotate methods with @RequestMapping.

Works fine in Spring 4.2!

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

You can define 2 images in your HTML code and use display: none; to decide which one will be visible.

Error inflating class android.support.design.widget.NavigationView

Just for who still get to this issue. I got to the same problem but all the solutions here is not work for me.

Just take alook on NavigationView class with cue from logcat, i found the issue come form this line of code:

itemTextColor = this.createDefaultColorStateList(16842806);

So, it seem related to itemTextColor as Aenur56 mentioned. So i tried with Aenur56's solution but it doesn't work.

Take a look on the line of code above, i notice that there is ColorStateList. So i create one then set for itemTextColor then it work.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#00FF00" android:state_checked="true" />
    <item android:color="#000000" />
</selector>

Hope it help!

generate random string for div id

I would suggest that you start with some sort of placeholder, you may have this already, but its somewhere to append the div.

<div id="placeholder"></div>

Now, the idea is to dynamically create a new div, with your random id:

var rndId = randomString(8); 
var div = document.createElement('div');
div.id = rndId
div.innerHTML = "Whatever you want the content of your div to be";

this can be apended to your placeholder as follows:

document.getElementById('placeholder').appendChild(div);

You can then use that in your jwplayer code:

jwplayer(rndId).setup(...);

Live example: http://jsfiddle.net/pNYZp/

Sidenote: Im pretty sure id's must start with an alpha character (ie, no numbers) - you might want to change your implementation of randomstring to enforce this rule. (ref)

How can I print the contents of an array horizontally?

foreach(var item in array)
Console.Write(item.ToString() + "\t");

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

The basic concept we have to be clear while approaching this question is to understand the difference between is and ==.

"is" is will compare the memory location. if id(a)==id(b), then a is b returns true else it returns false.

so, we can say that is is used for comparing memory locations. Whereas,

== is used for equality testing which means that it just compares only the resultant values. The below shown code may acts as an example to the above given theory.

code

Click here for the code

In the case of string literals(strings without getting assigned to variables), the memory address will be same as shown in the picture. so, id(a)==id(b). remaining this is self-explanatory.

Image change every 30 seconds - loop

You should take a look at various javascript libraries, they should be able to help you out:

All of them have tutorials, and fade in/fade out is a basic usage.

For e.g. in jQuery:

var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
  $img.fadeOut(speed, function() {
    $img.attr("src", images[(++i % images.length)]);
    $img.fadeIn(speed);
  });
}, 30000);

How to parse/format dates with LocalDateTime? (Java 8)

GET CURRENT UTC TIME IN REQUIRED FORMAT

// Current UTC time
        OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);

        // GET LocalDateTime 
        LocalDateTime localDateTime = utc.toLocalDateTime();
        System.out.println("*************" + localDateTime);

        // formated UTC time
        DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF.format(localDateTime));

        //GET UTC time for current date
        Date now= new Date();
        LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
        DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

I had the same exception and I tried many snippet that I found here on this stackoverflow discussion, but no snippets worked for me.

But I was able to resolve all issues, I will share with you the solutions :

  • In a First part : I tried to show a DialogFragment on a Activity but from another java class. Then by checking the attribute of that instance, I found that was an old instance of the Activity, it was not the current running Activity. [More precisly I was using socket.io, and I forgot to do a socket.off("example",example) ... so it attached to an old instance of the activity. ]

  • In a Second part : I was trying to show a DialogFragment in a Activity when I come back to it with an intent, but when I checked my logs, I saw that when it tried to show the fragment the activity was still not in onStart method, so it crashed the app because it didn't find the Activity class to show the fragment on it.

Some tips : check with some attributes if you are not using an old instance of your activity with which one you are trying to show your fragment, or check your activity lifecycle before showing your fragment and be sure you are in onStart or onResume before showing it.

I hope those explanations will help you.

document.body.appendChild(i)

May also want to use "documentElement":

var elem = document.createElement("div");
elem.style = "width:100px;height:100px;position:relative;background:#FF0000;";
document.documentElement.appendChild(elem);

Move seaborn plot legend to a different position?

Check out the docs here: https://matplotlib.org/users/legend_guide.html#legend-location

adding this simply worked to bring legend out of the plot:

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

Change background colour for Visual Studio

This is the only one right answer on this whole page as people answered about "Visual Studio", not "Visual Studio Code":

To change color theme in "Visual Studio Code", use:

File -> Preferences -> Color Theme -> select any color theme you like

You can also download other custom themes as extensions. To do that, open extensions tab on sidebar and type "theme" into the search field to filter extensions only to themes related ones. Click any you like, click "download" and then "install". After installation and restarting VSC, you can find newly installed themes next to default themes in the same place:

File -> Preferences -> Color Theme -> select newly downloaded color theme

PS - Microsoft made bad naming decision by calling this new editor Visual Studio Code, it's terrible how many wrong links we have in google and stackoverflow. They should rename it to VSCode or something.

Loading DLLs at runtime in C#

You need to create an instance of the type that expose the Output method:

static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var class1Type = DLL.GetType("DLL.Class1");

        //Now you can use reflection or dynamic to call the method. I will show you the dynamic way

        dynamic c = Activator.CreateInstance(class1Type);
        c.Output(@"Hello");

        Console.ReadLine();
     }

How to compare oldValues and newValues on React Hooks useEffect?

Incase anybody is looking for a TypeScript version of usePrevious:

In a .tsx module:

import { useEffect, useRef } from "react";

const usePrevious = <T extends unknown>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

Or in a .ts module:

import { useEffect, useRef } from "react";

const usePrevious = <T>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

How to initialize an array in angular2 and typescript

you can create and initialize array of any object like this.

hero:Hero[]=[];

Is there a simple, elegant way to define singletons?

You can override the __new__ method like this:

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(
                                cls, *args, **kwargs)
        return cls._instance


if __name__ == '__main__':
    s1 = Singleton()
    s2 = Singleton()
    if (id(s1) == id(s2)):
        print "Same"
    else:
        print "Different"

Is it possible to set a custom font for entire of application?

This solution does not work correctly in some situations.
So I extend it:

FontsReplacer.java

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        FontsReplacer.replaceFonts(this);
        super.onCreate();
    }

}

https://gist.github.com/orwir/6df839e3527647adc2d56bfadfaad805

Howto: Clean a mysql InnoDB storage engine?

Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.

Keep in mind that /var/lib/mysql/ibdata1 is the busiest file in the InnoDB infrastructure. It normally houses six types of information:

InnoDB Architecture

InnoDB Architecture

Many people create multiple ibdata files hoping for better disk-space management and performance, however that belief is mistaken.

Can I run OPTIMIZE TABLE ?

Unfortunately, running OPTIMIZE TABLE against an InnoDB table stored in the shared table-space file ibdata1 does two things:

  • Makes the table’s data and indexes contiguous inside ibdata1
  • Makes ibdata1 grow because the contiguous data and index pages are appended to ibdata1

You can however, segregate Table Data and Table Indexes from ibdata1 and manage them independently.

Can I run OPTIMIZE TABLE with innodb_file_per_table ?

Suppose you were to add innodb_file_per_table to /etc/my.cnf (my.ini). Can you then just run OPTIMIZE TABLE on all the InnoDB Tables?

Good News : When you run OPTIMIZE TABLE with innodb_file_per_table enabled, this will produce a .ibd file for that table. For example, if you have table mydb.mytable witha datadir of /var/lib/mysql, it will produce the following:

  • /var/lib/mysql/mydb/mytable.frm
  • /var/lib/mysql/mydb/mytable.ibd

The .ibd will contain the Data Pages and Index Pages for that table. Great.

Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable from living in ibdata. The data dictionary entry for every table, including mydb.mytable, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1 AT THIS POINT !!! Please note that ibdata1 has not shrunk at all.

InnoDB Infrastructure Cleanup

To shrink ibdata1 once and for all you must do the following:

  1. Dump (e.g., with mysqldump) all databases into a .sql text file (SQLData.sql is used below)

  2. Drop all databases (except for mysql and information_schema) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:

    mkdir /var/lib/mysql_grants
    cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
    chown -R mysql:mysql /var/lib/mysql_grants
    
  3. Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0; (This will completely flush all remaining transactional changes from ib_logfile0 and ib_logfile1)

  4. Shutdown MySQL

  5. Add the following lines to /etc/my.cnf (or my.ini on Windows)

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    (Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Also: innodb_flush_method=O_DIRECT is not available on Windows)

  6. Delete ibdata* and ib_logfile*, Optionally, you can remove all folders in /var/lib/mysql, except /var/lib/mysql/mysql.

  7. Start MySQL (This will recreate ibdata1 [10MB by default] and ib_logfile0 and ib_logfile1 at 1G each).

  8. Import SQLData.sql

Now, ibdata1 will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1. ibdata1 will no longer contain InnoDB data and indexes for other tables.

For example, suppose you have an InnoDB table named mydb.mytable. If you look in /var/lib/mysql/mydb, you will see two files representing the table:

  • mytable.frm (Storage Engine Header)
  • mytable.ibd (Table Data and Indexes)

With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1 file down to only 500MB!

Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.

CAVEAT

At Step 6, if mysql cannot restart because of the mysql schema begin dropped, look back at Step 2. You made the physical copy of the mysql schema. You can restore it as follows:

mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql

Go back to Step 6 and continue

UPDATE 2013-06-04 11:13 EDT

With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.

Back on July 03, 2006, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.

I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.

Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.

Call a function from another file?

Rename the module to something other than 'file'.

Then also be sure when you are calling the function that:

1)if you are importing the entire module, you reiterate the module name when calling it:

import module
module.function_name()

or

import pizza
pizza.pizza_function()

2)or if you are importing specific functions, functions with an alias, or all functions using *, you don't reiterate the module name:

from pizza import pizza_function
pizza_function()

or

from pizza import pizza_function as pf
pf()

or

from pizza import *
pizza_function()

How to store .pdf files into MySQL as BLOBs using PHP?

//Pour inserer :
            $pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
            $filetype = addslashes($_FILES['inputname']['type']);//pour le test 
            $namepdf = addslashes($_FILES['inputname']['name']);            
            if (substr($filetype, 0, 11) == 'application'){
            $mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
            }
//Pour afficher :
            $row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
            foreach($row as $result){
                 $file=$result['pdf'];
            }
            header('Content-type: application/pdf');
            echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));

How to overcome root domain CNAME restrictions?

You have to put a period at the end of the external domain so it doesn't think you mean customer1.mycompanydomain.com.localdomain;

So just change:

customer1.com IN CNAME customer1.mycompanydomain.com

To

customer1.com IN CNAME customer1.mycompanydomain.com.

Serializing with Jackson (JSON) - getting "No serializer found"?

If you can edit the class containing that object, I usually just add the annotation

import com.fasterxml.jackson.annotation.JsonIgnore;

@JsonIgnore 
NonSerializeableClass obj;

android - How to get view from context?

For example you can find any textView:

TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

Question 3: Can you offer me some hints how to optimize these implementations without changing the way I determine the factors? Optimization in any way: nicer, faster, more "native" to the language.

The C implementation is suboptimal (as hinted at by Thomas M. DuBuisson), the version uses 64-bit integers (i.e. long datatype). I'll investigate the assembly listing later, but with an educated guess, there are some memory accesses going on in the compiled code, which make using 64-bit integers significantly slower. It's that or generated code (be it the fact that you can fit less 64-bit ints in a SSE register or round a double to a 64-bit integer is slower).

Here is the modified code (simply replace long with int and I explicitly inlined factorCount, although I do not think that this is necessary with gcc -O3):

#include <stdio.h>
#include <math.h>

static inline int factorCount(int n)
{
    double square = sqrt (n);
    int isquare = (int)square;
    int count = isquare == square ? -1 : 0;
    int candidate;
    for (candidate = 1; candidate <= isquare; candidate ++)
        if (0 == n % candidate) count += 2;
    return count;
}

int main ()
{
    int triangle = 1;
    int index = 1;
    while (factorCount (triangle) < 1001)
    {
        index++;
        triangle += index;
    }
    printf ("%d\n", triangle);
}

Running + timing it gives:

$ gcc -O3 -lm -o euler12 euler12.c; time ./euler12
842161320
./euler12  2.95s user 0.00s system 99% cpu 2.956 total

For reference, the haskell implementation by Thomas in the earlier answer gives:

$ ghc -O2 -fllvm -fforce-recomp euler12.hs; time ./euler12                                                                                      [9:40]
[1 of 1] Compiling Main             ( euler12.hs, euler12.o )
Linking euler12 ...
842161320
./euler12  9.43s user 0.13s system 99% cpu 9.602 total

Conclusion: Taking nothing away from ghc, its a great compiler, but gcc normally generates faster code.

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

JavascriptExecutor jse = ((JavascriptExecutor) driver);
jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");

This code works for me. As the page which I'm testing, loads as we scroll down.

Laravel update model with unique validation rule for attribute

For anyone using a Form request

In my case i tried all of the following none of them worked:

$this->id, $this->user->id, $this->user.

It was because i could not access the model $id nor the $id directly.

So i got the $id from a query using the same unique field i am trying to validate:

    /**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    $id = YourModel::where('unique_field',$this->request->get('unique_field'))->value('id');
    return [
        'unique_field' => ['rule1','rule2',Rule::unique('yourTable')->ignore($id)],
    ];
}

Difference between a Structure and a Union

With a union, you're only supposed to use one of the elements, because they're all stored at the same spot. This makes it useful when you want to store something that could be one of several types. A struct, on the other hand, has a separate memory location for each of its elements and they all can be used at once.

To give a concrete example of their use, I was working on a Scheme interpreter a little while ago and I was essentially overlaying the Scheme data types onto the C data types. This involved storing in a struct an enum indicating the type of value and a union to store that value.

union foo {
  int a;   // can't use both a and b at once
  char b;
} foo;

struct bar {
  int a;   // can use both a and b simultaneously
  char b;
} bar;

union foo x;
x.a = 3; // OK
x.b = 'c'; // NO! this affects the value of x.a!

struct bar y;
y.a = 3; // OK
y.b = 'c'; // OK

edit: If you're wondering what setting x.b to 'c' changes the value of x.a to, technically speaking it's undefined. On most modern machines a char is 1 byte and an int is 4 bytes, so giving x.b the value 'c' also gives the first byte of x.a that same value:

union foo x;
x.a = 3;
x.b = 'c';
printf("%i, %i\n", x.a, x.b);

prints

99, 99

Why are the two values the same? Because the last 3 bytes of the int 3 are all zero, so it's also read as 99. If we put in a larger number for x.a, you'll see that this is not always the case:

union foo x;
x.a = 387439;
x.b = 'c';
printf("%i, %i\n", x.a, x.b);

prints

387427, 99

To get a closer look at the actual memory values, let's set and print out the values in hex:

union foo x;
x.a = 0xDEADBEEF;
x.b = 0x22;
printf("%x, %x\n", x.a, x.b);

prints

deadbe22, 22

You can clearly see where the 0x22 overwrote the 0xEF.

BUT

In C, the order of bytes in an int are not defined. This program overwrote the 0xEF with 0x22 on my Mac, but there are other platforms where it would overwrite the 0xDE instead because the order of the bytes that make up the int were reversed. Therefore, when writing a program, you should never rely on the behavior of overwriting specific data in a union because it's not portable.

For more reading on the ordering of bytes, check out endianness.

How to find my php-fpm.sock?

Check the config file, the config path is /etc/php5/fpm/pool.d/www.conf, there you'll find the path by config and if you want you can change it.

EDIT:
well you're correct, you need to replace listen = 127.0.0.1:9000 to listen = /var/run/php5-fpm/php5-fpm.sock, then you need to run sudo service php5-fpm restart, and make sure it says that it restarted correctly, if not then make sure that /var/run/ has a folder called php5-fpm, or make it listen to /var/run/php5-fpm.sock cause i don't think the folder inside /var/run is created automatically, i remember i had to edit the start up script to create that folder, otherwise even if you mkdir /var/run/php5-fpm after restart that folder will disappear and the service starting will fail.

Can I have multiple Xcode versions installed?

Yes, you can install multiple versions of Xcode. They will install into separate directories. I've found that the best practice is to install the version that came with your Mac first and then install downloaded versions, but it probably doesn't make a big difference. See http://developer.apple.com/documentation/Xcode/Conceptual/XcodeCoexistence/Contents/Resources/en.lproj/Details/Details.html this Apple Developer Connection page for lots of details. <- Page does not exist anymore!

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

How do I execute a file in Cygwin?

just type ./a in the shell

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

I had an issue with the path of the MySQL service in the Windows 7 registry which was not changed with the new installed XAMPP or newer easyPHP version.

So if anybody has the same problem (#2002 error, phpMyAdmin cannot be started) you can search into the win regedit for 'my.ini' and exchange the path to the new package.

For example I exchanged on a few places the older path:

C:\EASYPH~1.1VC\binaries\mysql\bin\eds-mysqld.exe --defaults-file=C:\EASYPH~1.1VC\binaries\mysql\my.ini MySQL

with the newer one:

c:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysql

It is strange that nobody described this issue before on the web!

How to implement the factory method pattern in C++ correctly

I know this question has been answered 3 years ago, but this may be what your were looking for.

Google has released a couple of weeks ago a library allowing easy and flexible dynamic object allocations. Here it is: http://google-opensource.blogspot.fr/2014/01/introducing-infact-library.html

Drop-down box dependent on the option selected in another drop-down box

Try something like this... jsfiddle demo

HTML

<!-- Source: -->
<select id="source" name="source">
     <option>MANUAL</option>
     <option>ONLINE</option>
</select>

<!-- Status: -->
<select id="status" name="status">
    <option>OPEN</option>
    <option>DELIVERED</option>
</select>

JS

$(document).ready(function () {

    $("#source").change(function () {
        var el = $(this);
        if (el.val() === "ONLINE") {
            $("#status").append("<option>SHIPPED</option>");
        } else if (el.val() === "MANUAL") {
            $("#status option:last-child").remove();
        }
    });

});

add image to uitableview cell

cell.imageView.image = [UIImage imageNamed:@"image.png"];

UPDATE: Like Steven Fisher said, this should only work for cells with style UITableViewCellStyleDefault which is the default style. For other styles, you'd need to add a UIImageView to the cell's contentView.

MVC 4 - how do I pass model data to a partial view?

Three ways to pass model data to partial view (there may be more)

This is view page

Method One Populate at view

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

Method Two Pass Through ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

Method Three pass through model

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

enter image description here

What is the difference between old style and new style classes in Python?

Declaration-wise:

New-style classes inherit from object, or from another new-style class.

class NewStyleClass(object):
    pass

class AnotherNewStyleClass(NewStyleClass):
    pass

Old-style classes don't.

class OldStyleClass():
    pass

Python 3 Note:

Python 3 doesn't support old style classes, so either form noted above results in a new-style class.

How to reenable event.preventDefault?

You can re-activate the actions by adding

this.delegateEvents();  // Re-activates the events for all the buttons

If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.

How to retrieve JSON Data Array from ExtJS Store

A better (IMO) one-line approach, works on ExtJS 4, not sure about 3:

store.proxy.reader.jsonData

jQuery delete all table rows except first

This should work:

$(document).ready(function() {
   $("someTableSelector").find("tr:gt(0)").remove();
});

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

How to downgrade or install an older version of Cocoapods

Several notes:

Make sure you first get a list of all installed versions. I actually had the version I wanted to downgrade to already installed, but ended up uninstalling that as well. To see the list of all your versions do:

sudo gem list cocoapods

Then when you want to delete a version, specify that version.

sudo gem uninstall cocoapods -v 1.6.2

You could remove the version specifier -v 1.6.2 and that would delete all versions:

You may try all this and still see that the Cocoapods you expected is still installed. If that's the case then it might be because Cocoaposa is stored in a different directory.

sudo gem uninstall -n /usr/local/bin cocoapods -v 1.6.2

Then you will have to also install it in a different directory, otherwise you may get an error saying You don't have write permissions for the /usr/bin directory

sudo gem install -n /usr/local/bin cocoapods -v 1.6.1

To check which version is your default do:

pod --version

For more on the directory problem see here

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

Just in case this helps someone, I was getting this error because I completely missed the stated fact that the scope prefix must not be used when calling a local scope. So if you defined a local scope in your model like this:

public function scopeRecentFirst($query)
{
    return $query->orderBy('updated_at', 'desc');
}

You should call it like:

$CurrentUsers = \App\Models\Users::recentFirst()->get();

Note that the prefix scope is not present in the call.

Googlemaps API Key for Localhost

Typing 'my IP' in google search I got my public IP address and pasted it in IP address (the third option). It works for me.

What does '?' do in C++?

The question mark is the conditional operator. The code means that if f==r then 1 is returned, otherwise, return 0. The code could be rewritten as

int qempty()
{
  if(f==r)
    return 1;
  else
    return 0;
}

which is probably not the cleanest way to do it, but hopefully helps your understanding.

Splitting a list into N parts of approximately equal length

Implementation using numpy.linspace method.

Just specify the number of parts you want the array to be divided in to.The divisions will be of nearly equal size.

Example :

import numpy as np   
a=np.arange(10)
print "Input array:",a 
parts=3
i=np.linspace(np.min(a),np.max(a)+1,parts+1)
i=np.array(i,dtype='uint16') # Indices should be floats
split_arr=[]
for ind in range(i.size-1):
    split_arr.append(a[i[ind]:i[ind+1]]
print "Array split in to %d parts : "%(parts),split_arr

Gives :

Input array: [0 1 2 3 4 5 6 7 8 9]
Array split in to 3 parts :  [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8, 9])]

What is the correct XPath for choosing attributes that contain "foo"?

If you also need to match the content of the link itself, use text():

//a[contains(@href,"/some_link")][text()="Click here"]

Fastest way to check if a value exists in a list

As stated by others, in can be very slow for large lists. Here are some comparisons of the performances for in, set and bisect. Note the time (in second) is in log scale.

enter image description here

Code for testing:

import random
import bisect
import matplotlib.pyplot as plt
import math
import time


def method_in(a, b, c):
    start_time = time.time()
    for i, x in enumerate(a):
        if x in b:
            c[i] = 1
    return time.time() - start_time


def method_set_in(a, b, c):
    start_time = time.time()
    s = set(b)
    for i, x in enumerate(a):
        if x in s:
            c[i] = 1
    return time.time() - start_time


def method_bisect(a, b, c):
    start_time = time.time()
    b.sort()
    for i, x in enumerate(a):
        index = bisect.bisect_left(b, x)
        if index < len(a):
            if x == b[index]:
                c[i] = 1
    return time.time() - start_time


def profile():
    time_method_in = []
    time_method_set_in = []
    time_method_bisect = []

    # adjust range down if runtime is to great or up if there are to many zero entries in any of the time_method lists
    Nls = [x for x in range(10000, 30000, 1000)]
    for N in Nls:
        a = [x for x in range(0, N)]
        random.shuffle(a)
        b = [x for x in range(0, N)]
        random.shuffle(b)
        c = [0 for x in range(0, N)]

        time_method_in.append(method_in(a, b, c))
        time_method_set_in.append(method_set_in(a, b, c))
        time_method_bisect.append(method_bisect(a, b, c))

    plt.plot(Nls, time_method_in, marker='o', color='r', linestyle='-', label='in')
    plt.plot(Nls, time_method_set_in, marker='o', color='b', linestyle='-', label='set')
    plt.plot(Nls, time_method_bisect, marker='o', color='g', linestyle='-', label='bisect')
    plt.xlabel('list size', fontsize=18)
    plt.ylabel('log(time)', fontsize=18)
    plt.legend(loc='upper left')
    plt.yscale('log')
    plt.show()


profile()

Javascript set img src

Pure JavaScript to Create img tag and add attributes manually ,

var image = document.createElement("img");
var imageParent = document.getElementById("body");
image.id = "id";
image.className = "class";
image.src = searchPic.src;            // image.src = "IMAGE URL/PATH"
imageParent.appendChild(image);

Set src in pic1

document["#pic1"].src = searchPic.src;

or with getElementById

document.getElementById("pic1").src= searchPic.src;

j-Query to archive this,

$("#pic1").attr("src", searchPic.src);

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Can I pass column name as input parameter in SQL stored Procedure

You can do this in a couple of ways.

One, is to build up the query yourself and execute it.

SET @sql = 'SELECT ' + @columnName + ' FROM yourTable'
sp_executesql @sql

If you opt for that method, be very certain to santise your input. Even if you know your application will only give 'real' column names, what if some-one finds a crack in your security and is able to execute the SP directly? Then they can execute just about anything they like. With dynamic SQL, always, always, validate the parameters.

Alternatively, you can write a CASE statement...

SELECT
  CASE @columnName
    WHEN 'Col1' THEN Col1
    WHEN 'Col2' THEN Col2
                ELSE NULL
  END as selectedColumn
FROM
  yourTable

This is a bit more long winded, but a whole lot more secure.

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

Try to use GMT instead of UTC. They refer to the same time zone, yet the name GMT is more common and might work.

Why is the default value of the string type null instead of an empty string?

Empty strings and nulls are fundamentally different. A null is an absence of a value and an empty string is a value that is empty.

The programming language making assumptions about the "value" of a variable, in this case an empty string, will be as good as initiazing the string with any other value that will not cause a null reference problem.

Also, if you pass the handle to that string variable to other parts of the application, then that code will have no ways of validating whether you have intentionally passed a blank value or you have forgotten to populate the value of that variable.

Another occasion where this would be a problem is when the string is a return value from some function. Since string is a reference type and can technically have a value as null and empty both, therefore the function can also technically return a null or empty (there is nothing to stop it from doing so). Now, since there are 2 notions of the "absence of a value", i.e an empty string and a null, all the code that consumes this function will have to do 2 checks. One for empty and the other for null.

In short, its always good to have only 1 representation for a single state. For a broader discussion on empty and nulls, see the links below.

https://softwareengineering.stackexchange.com/questions/32578/sql-empty-string-vs-null-value

NULL vs Empty when dealing with user input

Change fill color on vector asset in Android Studio

Go to you MainActivity.java and below this code
-> NavigationView navigationView = findViewById(R.id.nav_view);
Add single line of code -> navigationView.setItemIconTintList(null);
i.e. the last line of my code

I hope this might solve your problem.

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);

SQL - How to select a row having a column with max value

Keywords like TOP, LIMIT, ROWNUM, ...etc are database dependent. Please read this article for more information.

http://en.wikipedia.org/wiki/Select_(SQL)#Result_limits

Oracle: ROWNUM could be used.

select * from (select * from table 
order by value desc, date_column) 
where rownum = 1;

Answering the question more specifically:

select high_val, my_key
from (select high_val, my_key
      from mytable
      where something = 'avalue'
      order by high_val desc)
where rownum <= 1

Find object in list that has attribute equal to some value (that meets any condition)

I just ran into a similar problem and devised a small optimization for the case where no object in the list meets the requirement.(for my use-case this resulted in major performance improvement):

Along with the list test_list, I keep an additional set test_value_set which consists of values of the list that I need to filter on. So here the else part of agf's solution becomes very-fast.

Watermark / hint text / placeholder TextBox

Well here is mine: not necessarily the best, but as it is simple it is easy to edit to your taste.

<UserControl x:Class="WPFControls.ShadowedTextBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WPFControls"
    Name="Root">
<UserControl.Resources>
    <local:ShadowConverter x:Key="ShadowConvert"/>
</UserControl.Resources>
<Grid>
    <TextBox Name="textBox" 
             Foreground="{Binding ElementName=Root, Path=Foreground}"
             Text="{Binding ElementName=Root, Path=Text, UpdateSourceTrigger=PropertyChanged}"
             TextChanged="textBox_TextChanged"
             TextWrapping="Wrap"
             VerticalContentAlignment="Center"/>
    <TextBlock Name="WaterMarkLabel"
           IsHitTestVisible="False"
           Foreground="{Binding ElementName=Root,Path=Foreground}"
           FontWeight="Thin"
           Opacity=".345"
           FontStyle="Italic"
           Text="{Binding ElementName=Root, Path=Watermark}"
           VerticalAlignment="Center"
           TextWrapping="Wrap"
           TextAlignment="Center">
        <TextBlock.Visibility>
            <MultiBinding Converter="{StaticResource ShadowConvert}">
                <Binding ElementName="textBox" Path="Text"/>
            </MultiBinding>
        </TextBlock.Visibility> 
    </TextBlock>
</Grid>

The converter, as it is written now it is not necessary that it is a MultiConverter, but in this wasy it can be extended easily

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace WPFControls
{
    class ShadowConverter:IMultiValueConverter
    {
        #region Implementation of IMultiValueConverter

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var text = (string) values[0];
            return text == string.Empty
                       ? Visibility.Visible
                       : Visibility.Collapsed;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return new object[0];
        }

        #endregion
    }
}

and finally the code behind:

using System.Windows;
using System.Windows.Controls;

namespace WPFControls
{
    /// <summary>
    /// Interaction logic for ShadowedTextBox.xaml
    /// </summary>
    public partial class ShadowedTextBox : UserControl
    {
        public event TextChangedEventHandler TextChanged;

        public ShadowedTextBox()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty WatermarkProperty =
            DependencyProperty.Register("Watermark",
                                        typeof (string),
                                        typeof (ShadowedTextBox),
                                        new UIPropertyMetadata(string.Empty));

        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text",
                                        typeof (string),
                                        typeof (ShadowedTextBox),
                                        new UIPropertyMetadata(string.Empty));

        public static readonly DependencyProperty TextChangedProperty =
            DependencyProperty.Register("TextChanged",
                                        typeof (TextChangedEventHandler),
                                        typeof (ShadowedTextBox),
                                        new UIPropertyMetadata(null));

        public string Watermark
        {
            get { return (string)GetValue(WatermarkProperty); }
            set
            {
                SetValue(WatermarkProperty, value);
            }
        }

        public string Text
        {
            get { return (string) GetValue(TextProperty); }
            set{SetValue(TextProperty,value);}
        }

        private void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (TextChanged != null) TextChanged(this, e);
        }

        public void Clear()
        {
            textBox.Clear();
        }

    }
}

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

How do I "commit" changes in a git submodule?

Before you can commit and push, you need to init a working repository tree for a submodule. I am using tortoise and do following things:

First check if there exist .git file (not a directory)

  • if there is such file it contains path to supermodule git directory
  • delete this file
  • do git init
  • do git add remote path the one used for submodule
  • follow instructions below

If there was .git file, there surly was .git directory which tracks local tree. You still need to a branch (you can create one) or switch to master (which sometimes does not work). Best to do is - git fetch - git pull. Do not omit fetch.

Now your commits and pulls will be synchronized with your origin/master

What is VanillaJS?

"Vanilla JS” is an expression that got popular after the publishing of a satire website in 2012 (http://vanilla-js.com/). There’s a section covering its story/meaning in this post.

So why the joke? It kind of came as a modern response to the old school knee-jerk reflex of relying on jQuery and additional JS libraries. With the ECMAScript spec and modern browsers capabilities, the need to bypass plain JS with external libraries to maintain consistency across browsers just isn’t there anymore. Here’s a site that shows you how true this is with concrete examples: http://youmightnotneedjquery.com/

System.drawing namespace not found under console application

For,Adding System.Drawing Follow some steps: Firstly, right click on the solution and click on add Reference. Secondly, Select the .NET Folder. And then double click on the Using.System.Drawing;

Python 3 Building an array of bytes

I think Scapy is what are you looking for.

http://www.secdev.org/projects/scapy/

you can build and send frames (packets) with it

Function pointer as a member of a C struct

You can use also "void*" (void pointer) to send an address to the function.

typedef struct pstring_t {
    char * chars;
    int(*length)(void*);
} PString;

int length(void* self) {
    return strlen(((PString*)self)->chars);
}

PString initializeString() {
    PString str;
    str.length = &length;
    return str;
}

int main()
{
    PString p = initializeString();

    p.chars = "Hello";

    printf("Length: %i\n", p.length(&p));

    return 0;
}

Output:

Length: 5

Decreasing for loops in Python impossible?

For python3 where -1 indicate the value that to be decremented in each step for n in range(6,0,-1): print(n)

Best way to test for a variable's existence in PHP; isset() is clearly broken

I prefer using not empty as the best method to check for the existence of a variable that a) exists, and b) is not null.

if (!empty($variable)) do_something();

jQuery Determine if a matched class has a given id

You can bake that logic into the selector by combining multiple selectors. For instance, we could target all elements with a given id, that also have a particular class:

$("#foo.bar"); // Matches <div id="foo" class="bar">

This should look similar to something you'd write in CSS. Note that it won't apply to all #foo elements (though there should only be one), and it won't apply to all .bar elements (though there may be many). It will only reference elements that qualify on both attributes.

jQuery also has a great .is method that lets your determine whether an element has certain qualities. You can test a jQuery collection against a string selector, an HTML Element, or another jQuery object. In this case, we'll just check it against a string selector:

$(".bar:first").is("#foo"); // TRUE if first '.bar' in document is also '#foo'

Accessing the logged-in user in a template

{{ app.user.username|default('') }}

Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.

Count characters in textarea

Your code was a bit mixed up. Here is a clean version:

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
            $.post("SetAndGet.php", {
                know: $("#know").val()
            }, function(data) {
                $("#know_list").html(data);
            });
        });

        function countChar(val) {
            var len = val.value.length;
            if (len >= 500) {
                val.value = val.value.substring(0, 500);
            } else {
                $('#charNum').text(500 - len);
            }
        }
    });
</script>

Java sending and receiving file (byte[]) over sockets

To avoid the limitation of the file size , which can cause the Exception java.lang.OutOfMemoryError to be thrown when creating an array of the file size byte[] bytes = new byte[(int) length];, instead we could do

    byte[] bytearray = new byte[1024*16];
    FileInputStream fis = null;
    try {

        fis = new FileInputStream(file);
        OutputStream output= socket.getOututStream();
        BufferedInputStream bis = new BufferedInputStream(fis);

        int readLength = -1;
        while ((readLength = bis.read(bytearray)) > 0) {
            output.write(bytearray, 0, readLength);

        }
        bis.close();
        output.close();
    }
    catch(Exception ex ){

        ex.printStackTrace();
    } //Excuse the poor exception handling...

Is there a way to do repetitive tasks at intervals?

The function time.NewTicker makes a channel that sends a periodic message, and provides a way to stop it. Use it something like this (untested):

ticker := time.NewTicker(5 * time.Second)
quit := make(chan struct{})
go func() {
    for {
       select {
        case <- ticker.C:
            // do stuff
        case <- quit:
            ticker.Stop()
            return
        }
    }
 }()

You can stop the worker by closing the quit channel: close(quit).

How do you delete all text above a certain line

kdgg

delete all lines above the current one.

Oracle SQL Developer: Unable to find a JVM

There is another route of failure, besides the version of Java you are running: You could be running out of Heap/RAM

If you had a once working version of SQLDeveloper, and you are starting to see the screenshot referenced in the original post, then you can try to adjust the amount of space SQLDeveloper requests when starting up.

Edit the file:

/ide/bin/ide.conf

Edit the line that specifies the max ram to use: AddVMOption -Xmx, reducing the size. For example I changed my file to have the following lines, which solved the issue.

#AddVMOption  -Xmx640M   # Original Value
AddVMOption  -Xmx256M    # New Value

How do I debug a stand-alone VBScript script?

For posterity, here's Microsoft's article KB308364 on the subject. This no longer exists on their website, it is from an archive.

How to debug Windows Script Host, VBScript, and JScript files

SUMMARY

The purpose of this article is to explain how to debug Windows Script Host (WSH) scripts, which can be written in any ActiveX script language (as long as the proper language engine is installed), but which, by default, are written in VBScript and JScript. There are certain flags in the registry and, depending on the debugger used, certain required procedures to enable debugging.

MORE INFORMATION

To debug WSH scripts in Microsoft Visual InterDev, the Microsoft Script Debugger, or any other debugger, use the following command-line syntax to start the script:

wscript.exe //d <path to WSH file>
           This code informs the user when a runtime error has occurred and gives the user a choice to debug the application. Also, the //x flag

can be used, as follows, to throw an immediate exception, which starts the debugger immediately after the script starts running:

wscript.exe //d //x <path to WSH file>
           After a debug condition exists, the following registry key determines which debugger will be used:

HKEY_CLASSES_ROOT\CLSID\{834128A2-51F4-11D0-8F20-00805F2CD064}\LocalServer32

The script debugger should be Msscrdbg.exe, and the Visual InterDev debugger should be Mdm.exe.

If Visual InterDev is the default debugger, make sure that just-in-time (JIT) functionality is enabled. To do this, follow these steps:

  1. Start Visual InterDev.

  2. On the Tools menu, click Options.

  3. Click Debugger, and then ensure that the Just-In-Time options are selected for both the General and Script categories.

Additionally, if you are trying to debug a .wsf file, make sure that the following registry key is set to 1:

HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug

PROPERTIES

Article ID: 308364 - Last Review: June 19, 2014 - Revision: 3.0

Keywords: kbdswmanage2003swept kbinfo KB308364

Python strip() multiple characters?

string.translate with table=None works fine.

>>> name = "Barack (of Washington)"
>>> name = name.translate(None, "(){}<>")
>>> print name
Barack of Washington

Get class labels from Keras functional model

You must use the labels index you have, here what I do for text classification:

# data labels = [1, 2, 1...]
labels_index = { "website" : 0, "money" : 1 ....} 
# to feed model
label_categories = to_categorical(np.asarray(labels)) 

Then, for predictions:

texts = ["hello, rejoins moi sur skype", "bonjour comment ça va ?", "tu me donnes de l'argent"]

sequences = tokenizer.texts_to_sequences(texts)

data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)

predictions = model.predict(data)

t = 0

for text in texts:
    i = 0
    print("Prediction for \"%s\": " % (text))
    for label in labels_index:
        print("\t%s ==> %f" % (label, predictions[t][i]))
        i = i + 1
    t = t + 1

This gives:

Prediction for "hello, rejoins moi sur skype": 
    website ==> 0.759483
    money ==> 0.037091
    under ==> 0.010587
    camsite ==> 0.114436
    email ==> 0.075975
    abuse ==> 0.002428
Prediction for "bonjour comment ça va ?": 
    website ==> 0.433079
    money ==> 0.084878
    under ==> 0.048375
    camsite ==> 0.036674
    email ==> 0.369197
    abuse ==> 0.027798
Prediction for "tu me donnes de l'argent": 
    website ==> 0.006223
    money ==> 0.095308
    under ==> 0.003586
    camsite ==> 0.003115
    email ==> 0.884112
    abuse ==> 0.007655

How can I save a base64-encoded image to disk?

This did it for me simply and perfectly.

Excellent explanation by Scott Robinson

From image to base64 string

let buff = fs.readFileSync('stack-abuse-logo.png');
let base64data = buff.toString('base64');

From base64 string to image

let buff = new Buffer(data, 'base64');
fs.writeFileSync('stack-abuse-logo-out.png', buff);

How to read/write files in .Net Core?

To write:

using (System.IO.StreamWriter file =
new System.IO.StreamWriter(System.IO.File.Create(filePath).Dispose()))
{
    file.WriteLine("your text here");
}

How to know if .keyup() is a character key (jQuery)

I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters

_x000D_
_x000D_
$('#input').on('keyup', function() {_x000D_
    var words = $(this).val();_x000D_
    // if input is empty, remove the word count data and return_x000D_
    if(!words.length) {_x000D_
        $(this).removeData('wcount');_x000D_
        return true;_x000D_
    }_x000D_
    // if word count data equals the count of the input, return_x000D_
    if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){_x000D_
        return true;_x000D_
    }_x000D_
    // update or initialize the word count data_x000D_
    $(this).data('wcount', words.length);_x000D_
    console.log('user tiped ' + words);_x000D_
    // do you stuff..._x000D_
});
_x000D_
<html lang="en">_x000D_
  <head>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
  <input type="text" name="input" id="input">_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Is Visual Studio Community a 30 day trial?

I'm using Visual Studio Professional licensed over the MAPS Action Pack subscription. Since the new version of the Microsoft Partner Center one have to add the subscribed user to the partner benefit software.

Partner Center->Benefits->Visual Studio Subscriptions->Add user

After that one have to sign out and reenter the credentials in the account settings of VS.

jQuery iframe load() event?

You may use the jquery's Contents method to get the content of the iframe.

Creating a script for a Telnet session?

Write the telnet session inside a BAT Dos file and execute.

Ruby replace string with captured regex pattern

Try '\1' for the replacement (single quotes are important, otherwise you need to escape the \):

"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"

But since you only seem to be interested in the capture group, note that you can index a string with a regex:

"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"

Getting value of select (dropdown) before change

Combine the focus event with the change event to achieve what you want:

(function () {
    var previous;

    $("select").on('focus', function () {
        // Store the current value on focus and on change
        previous = this.value;
    }).change(function() {
        // Do something with the previous value after the change
        alert(previous);

        // Make sure the previous value is updated
        previous = this.value;
    });
})();

Working example: http://jsfiddle.net/x5PKf/766

Java 8 Lambda filter by Lists

Look this:

List<Client> result = clients
    .stream()
    .filter(c -> 
        (users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
        .collect(Collectors.toList());

Add text to Existing PDF using Python

If you're on Windows, this might work:

PDF Creator Pilot

There's also a whitepaper of a PDF creation and editing framework in Python. It's a little dated, but maybe can give you some useful info:

Using Python as PDF Editing and Processing Framework

Group query results by month and year in postgresql

Take a look at example E of this tutorial -> https://www.postgresqltutorial.com/postgresql-group-by/

You need to call the function on your GROUP BY instead of calling the name of the virtual attribute you created on select. I was doing what all the answers above recommended and I was getting a column 'year_month' does not exist error.

What worked for me was:

SELECT 
    date_trunc('month', created_at), 'MM/YYYY' AS month
FROM 
    "orders"  
GROUP BY 
    date_trunc('month', created_at)

How can I fetch all items from a DynamoDB table without specifying the primary key?

I figured you are using PHP but not mentioned (edited). I found this question by searching internet and since I got solution working , for those who use nodejs here is a simple solution using scan :

  var dynamoClient = new AWS.DynamoDB.DocumentClient();
  var params = {
    TableName: config.dynamoClient.tableName, // give it your table name 
    Select: "ALL_ATTRIBUTES"
  };

  dynamoClient.scan(params, function(err, data) {
    if (err) {
       console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
       console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
  });

I assume same code can be translated to PHP too using different AWS SDK

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

you should not use swap to copy vectors, it would change the "original" vector.

pass the original as a parameter to the new instead.

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

How to re import an updated package while in Python Interpreter?

Short answer:

try using reimport: a full featured reload for Python.

Longer answer:

It looks like this question was asked/answered prior to the release of reimport, which bills itself as a "full featured reload for Python":

This module intends to be a full featured replacement for Python's reload function. It is targeted towards making a reload that works for Python plugins and extensions used by longer running applications.

Reimport currently supports Python 2.4 through 2.6.

By its very nature, this is not a completely solvable problem. The goal of this module is to make the most common sorts of updates work well. It also allows individual modules and package to assist in the process. A more detailed description of what happens is on the overview page.

Note: Although the reimport explicitly supports Python 2.4 through 2.6, I've been trying it on 2.7 and it seems to work just fine.