Programs & Examples On #Script#

Script# is a free tool that generates JavaScript by compiling C# source code.

How can I mock an ES6 module import using Jest?

To mock an ES6 dependency module default export using Jest:

import myModule from '../myModule';
import dependency from '../dependency';


// If necessary, you can place a mock implementation like this:
dependency.mockImplementation(() => 42);

describe('myModule', () => {
  it('calls the dependency once with double the input', () => {


The other options didn't work for my case.

Original purpose of <input type="hidden">?

The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.

SO uses a hidden field for the upvote click.

<input value="16293741" name="postId" type="hidden">

Using this value, the server-side script can store the upvote.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

How to get to a particular element in a List in java?

CSVReader reader = new CSVReader(new FileReader(
        try {
            List<String[]> myEntries = reader.readAll();
            for (String[] s : myEntries) {
               for(String ss : s) {
                   System.out.print(", " + ss);

        } catch (IOException e) {

Expected response code 220 but got code "", with message "" in Laravel

For me the problem was the port. I first incorrectly used port 465, which works for SSL but not TLS. So the key thing was changing the port to 587.

How can I capitalize the first letter of each word in a string?

The .title() method of a string (either ASCII or Unicode is fine) does this:

>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'

However, look out for strings with embedded apostrophes, as noted in the docs.

The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

I had to run my commands in the one and same terminal, not seperately.

nohup sudo Xvfb :10 -ac
export DISPLAY=:10
java -jar vendor/se/selenium-server-standalone/bin/selenium-server-standalone.jar"/usr/bin/google-chrome""vendor/bin/chromedriver"

Why doesn't the height of a container element increase if it contains floated elements?

You need to add overflow:auto to your parent div for it to encompass the inner floated div:

<div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange;overflow:auto">
    <div style="width:500px; height:200px; background-color:black; float:right">

jsFiddle example

Passing a variable from one php include file to another: global vs. not

This is all you have to do:


global $name;
$name = 'james';

How can I convert a stack trace to a string?

Warning: This may be a bit off topic, but oh well... ;)

I don't know what the original posters reason was for wanting the stack trace as string in the first place. When the stack trace should end up in an SLF4J/Logback LOG, but no exception was or should be thrown here's what I do:

public void remove(List<String> ids) {
    if(ids == null || ids.isEmpty()) {
            "An empty list (or null) was passed to {}.remove(List). " +
            "Clearly, this call is unneccessary, the caller should " + 
            "avoid making it. A stacktrace follows.", 
            new Throwable ("Stacktrace")


    // actual work, remove stuff

I like it because it does not require an external library (other than your logging backend, which will be in place most of the time anyway, of course).

instantiate a class from a variable in PHP?

How to pass dynamic constructor parameters too

If you want to pass dynamic constructor parameters to the class, you can use this code:

$reflectionClass = new ReflectionClass($className);

$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);

More information on dynamic classes and parameters

PHP >= 5.6

As of PHP 5.6 you can simplify this even more by using Argument Unpacking:

// The "..." is part of the language and indicates an argument array to unpack.
$module = new $className(...$arrayOfConstructorParameters);

Thanks to DisgruntledGoat for pointing that out.

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

Lua - Current time in milliseconds

In standard C lua, no. You will have to settle for seconds, unless you are willing to modify the lua interpreter yourself to have os.time use the resolution you want. That may be unacceptable, however, if you are writing code for other people to run on their own and not something like a web application where you have full control of the environment.

Edit: another option is to write your own small DLL in C that extends lua with a new function that would give you the values you want, and require that dll be distributed with your code to whomever is going to be using it.

How do I select an entire row which has the largest ID in the table?

You could use a subselect:

FROM table 
WHERE id=(
    SELECT max(id) FROM table

Note that if the value of max(id) is not unique, multiple rows are returned.

If you only want one such row, use @MichaelMior's answer,

SELECT row from table ORDER BY id DESC LIMIT 1

ASP.Net MVC: Calling a method from a view

why You don't use Ajax to

its simple and does not require page refresh and has success and error callbacks

take look at my samlpe

<a id="ResendVerificationCode" >@Resource_en.ResendVerificationCode</a>

and in JQuery

 $("#ResendVerificationCode").on("click", function() {

and this is my ajax which call my controller and my controller and return object from database

function getUserbyPhoneIfNotRegisterd(userphone) {

                    type: "GET",
                    dataType: "Json",
                    url: '@Url.Action("GetUserByPhone", "User")' + '?phone=' + userphone,
                    async: false,
                    success: function(data) {
                        if (data == null || == null) {
                            ErrorMessage("", "@Resource_en.YourPhoneDoesNotExistInOurDatabase");
                        } else {
                            user = data[Object.keys(data)[0]];
                                AddVereCode(user.ID);// anather Ajax call 
                                SuccessMessage("Done", "@Resource_en.VerificationCodeSentSuccessfully", "Done");
                    error: function() {
                        ErrorMessage("", '@Resource_en.ErrorOccourd');

Delete cookie by name?

You should define the path on which the cookie exists to ensure that you are deleting the correct cookie.

function set_cookie(name, value) {
  document.cookie = name +'='+ value +'; Path=/;';
function delete_cookie(name) {
  document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';

If you don't specify the path, the browser will set a cookie relative to the page you are currently on, so if you delete the cookie while on a different page, the other cookie continues its existence.

Edit based on @Evan Morrison's comment.
Be aware that in some cases to identify the correct cookie, the Domain parameter is required.
Usually it's defined as
Placing a dot in front of your domain name means that this cookie may exist on any sub-domain (www also counts as sub-domain).

Also, as mentioned in @RobertT's answer, HttpOnly cookies cannot be deleted with JavaScript on the client side.

What's the difference between primitive and reference types?

These are the primitive types in Java:

  • boolean
  • byte
  • short
  • char
  • int
  • long
  • float
  • double

All the other types are reference types: they reference objects.

This is the first part of the Java tutorial about the basics of the language.

Fast and simple String encrypt/decrypt in JAVA


the library already have Java/Kotlin support, see github.


To simplify I did a class to be used simply, I added it on Encryption library to use it you just do as follow:

Add the gradle library:

compile 'se.simbio.encryption:library:2.0.0'

and use it:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

if you not want add the Encryption library you can just copy the following class to your project. If you are in an android project you need to import android Base64 in this class, if you are in a pure java project you need to add this class manually you can get it here

package se.simbio.encryption;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

 * A class to make more easy and simple the encrypt routines, this is the core of Encryption library
public class Encryption {

     * The Builder used to create the Encryption instance and that contains the information about
     * encryption specifications, this instance need to be private and careful managed
    private final Builder mBuilder;

     * The private and unique constructor, you should use the Encryption.Builder to build your own
     * instance or get the default proving just the sensible information about encryption
    private Encryption(Builder builder) {
        mBuilder = builder;

     * @return an default encryption instance or {@code null} if occur some Exception, you can
     * create yur own Encryption instance using the Encryption.Builder
    public static Encryption getDefault(String key, String salt, byte[] iv) {
        try {
            return Builder.getDefaultBuilder(key, salt, iv).build();
        } catch (NoSuchAlgorithmException e) {
            return null;

     * Encrypt a String
     * @param data the String to be encrypted
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
    public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());

     * This is a sugar method that calls encrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     * @param data the String to be encrypted
     * @return the encrypted String or {@code null} if you send the data as {@code null}
    public String encryptOrNull(String data) {
        try {
            return encrypt(data);
        } catch (Exception e) {
            return null;

     * This is a sugar method that calls encrypt method in background, it is a good idea to use this
     * one instead the default method because encryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     * @param data     the String to be encrypted
     * @param callback the Callback to handle the results
    public void encryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            public void run() {
                try {
                    String encrypt = encrypt(data);
                    if (encrypt == null) {
                        callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
                } catch (Exception e) {

     * Decrypt a String
     * @param data the String to be decrypted
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
    public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
        return new String(dataBytesDecrypted);

     * This is a sugar method that calls decrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     * @param data the String to be decrypted
     * @return the decrypted String or {@code null} if you send the data as {@code null}
    public String decryptOrNull(String data) {
        try {
            return decrypt(data);
        } catch (Exception e) {
            return null;

     * This is a sugar method that calls decrypt method in background, it is a good idea to use this
     * one instead the default method because decryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     * @param data     the String to be decrypted
     * @param callback the Callback to handle the results
    public void decryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            public void run() {
                try {
                    String decrypt = decrypt(data);
                    if (decrypt == null) {
                        callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
                } catch (Exception e) {

     * creates a 128bit salted aes key
     * @param key encoded input key
     * @return aes 128 bit salted key
     * @throws NoSuchAlgorithmException     if no installed provider that can provide the requested
     *                                      by the Builder secret key type
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws InvalidKeySpecException      if the specified key specification cannot be used to
     *                                      generate a secret key
     * @throws NullPointerException         if the specified Builder secret key type is {@code null}
    private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
        KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
        SecretKey tmp = factory.generateSecret(spec);
        return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());

     * takes in a simple string and performs an sha1 hash
     * that is 128 bits long...we then base64 encode it
     * and return the char array
     * @param key simple inputted string
     * @return sha1 base64 encoded representation
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws NoSuchAlgorithmException     if the Builder digest algorithm is not available
     * @throws NullPointerException         if the Builder digest algorithm is {@code null}
    private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
        return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();

     * When you encrypt or decrypt in callback mode you get noticed of result using this interface
    public interface Callback {

         * Called when encrypt or decrypt job ends and the process was a success
         * @param result the encrypted or decrypted String
        void onSuccess(String result);

         * Called when encrypt or decrypt job ends and has occurred an error in the process
         * @param exception the Exception related to the error
        void onError(Exception exception);


     * This class is used to create an Encryption instance, you should provide ALL data or start
     * with the Default Builder provided by the getDefaultBuilder method
    public static class Builder {

        private byte[] mIv;
        private int mKeyLength;
        private int mBase64Mode;
        private int mIterationCount;
        private String mSalt;
        private String mKey;
        private String mAlgorithm;
        private String mKeyAlgorithm;
        private String mCharsetName;
        private String mSecretKeyType;
        private String mDigestAlgorithm;
        private String mSecureRandomAlgorithm;
        private SecureRandom mSecureRandom;
        private IvParameterSpec mIvParameterSpec;

         * @return an default builder with the follow defaults:
         * the default char set is UTF-8
         * the default base mode is Base64
         * the Secret Key Type is the PBKDF2WithHmacSHA1
         * the default salt is "some_salt" but can be anything
         * the default length of key is 128
         * the default iteration count is 65536
         * the default algorithm is AES in CBC mode and PKCS 5 Padding
         * the default secure random algorithm is SHA1PRNG
         * the default message digest algorithm SHA1
        public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
            return new Builder()

         * Build the Encryption with the provided information
         * @return a new Encryption instance with provided information
         * @throws NoSuchAlgorithmException if the specified SecureRandomAlgorithm is not available
         * @throws NullPointerException     if the SecureRandomAlgorithm is {@code null} or if the
         *                                  IV byte array is null
        public Encryption build() throws NoSuchAlgorithmException {
            setIvParameterSpec(new IvParameterSpec(getIv()));
            return new Encryption(this);

         * @return the charset name
        private String getCharsetName() {
            return mCharsetName;

         * @param charsetName the new charset name
         * @return this instance to follow the Builder patter
        public Builder setCharsetName(String charsetName) {
            mCharsetName = charsetName;
            return this;

         * @return the algorithm
        private String getAlgorithm() {
            return mAlgorithm;

         * @param algorithm the algorithm to be used
         * @return this instance to follow the Builder patter
        public Builder setAlgorithm(String algorithm) {
            mAlgorithm = algorithm;
            return this;

         * @return the key algorithm
        private String getKeyAlgorithm() {
            return mKeyAlgorithm;

         * @param keyAlgorithm the keyAlgorithm to be used in keys
         * @return this instance to follow the Builder patter
        public Builder setKeyAlgorithm(String keyAlgorithm) {
            mKeyAlgorithm = keyAlgorithm;
            return this;

         * @return the Base 64 mode
        private int getBase64Mode() {
            return mBase64Mode;

         * @param base64Mode set the base 64 mode
         * @return this instance to follow the Builder patter
        public Builder setBase64Mode(int base64Mode) {
            mBase64Mode = base64Mode;
            return this;

         * @return the type of aes key that will be created, on KITKAT+ the API has changed, if you
         * are getting problems please @see <a href=""></a>
        private String getSecretKeyType() {
            return mSecretKeyType;

         * @param secretKeyType the type of AES key that will be created, on KITKAT+ the API has
         *                      changed, if you are getting problems please @see <a href=""></a>
         * @return this instance to follow the Builder patter
        public Builder setSecretKeyType(String secretKeyType) {
            mSecretKeyType = secretKeyType;
            return this;

         * @return the value used for salting
        private String getSalt() {
            return mSalt;

         * @param salt the value used for salting
         * @return this instance to follow the Builder patter
        public Builder setSalt(String salt) {
            mSalt = salt;
            return this;

         * @return the key
        private String getKey() {
            return mKey;

         * @param key the key.
         * @return this instance to follow the Builder patter
        public Builder setKey(String key) {
            mKey = key;
            return this;

         * @return the length of key
        private int getKeyLength() {
            return mKeyLength;

         * @param keyLength the length of key
         * @return this instance to follow the Builder patter
        public Builder setKeyLength(int keyLength) {
            mKeyLength = keyLength;
            return this;

         * @return the number of times the password is hashed
        private int getIterationCount() {
            return mIterationCount;

         * @param iterationCount the number of times the password is hashed
         * @return this instance to follow the Builder patter
        public Builder setIterationCount(int iterationCount) {
            mIterationCount = iterationCount;
            return this;

         * @return the algorithm used to generate the secure random
        private String getSecureRandomAlgorithm() {
            return mSecureRandomAlgorithm;

         * @param secureRandomAlgorithm the algorithm to generate the secure random
         * @return this instance to follow the Builder patter
        public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
            mSecureRandomAlgorithm = secureRandomAlgorithm;
            return this;

         * @return the IvParameterSpec bytes array
        private byte[] getIv() {
            return mIv;

         * @param iv the byte array to create a new IvParameterSpec
         * @return this instance to follow the Builder patter
        public Builder setIv(byte[] iv) {
            mIv = iv;
            return this;

         * @return the SecureRandom
        private SecureRandom getSecureRandom() {
            return mSecureRandom;

         * @param secureRandom the Secure Random
         * @return this instance to follow the Builder patter
        public Builder setSecureRandom(SecureRandom secureRandom) {
            mSecureRandom = secureRandom;
            return this;

         * @return the IvParameterSpec
        private IvParameterSpec getIvParameterSpec() {
            return mIvParameterSpec;

         * @param ivParameterSpec the IvParameterSpec
         * @return this instance to follow the Builder patter
        public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
            mIvParameterSpec = ivParameterSpec;
            return this;

         * @return the message digest algorithm
        private String getDigestAlgorithm() {
            return mDigestAlgorithm;

         * @param digestAlgorithm the algorithm to be used to get message digest instance
         * @return this instance to follow the Builder patter
        public Builder setDigestAlgorithm(String digestAlgorithm) {
            mDigestAlgorithm = digestAlgorithm;
            return this;



round up to 2 decimal places in java?

Go back to your code, and replace 100 by 100.00 and let me know if it works. However, if you want to be formal, try this:

import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

Initialise a list to a specific length in Python

If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.

Importing large sql file to MySql via command line

+1 to @MartinNuc, you can run the mysql client in batch mode and then you won't see the long stream of "OK" lines.

The amount of time it takes to import a given SQL file depends on a lot of things. Not only the size of the file, but the type of statements in it, how powerful your server server is, and how many other things are running at the same time.

@MartinNuc says he can load 4GB of SQL in 4-5 minutes, but I have run 0.5 GB SQL files and had it take 45 minutes on a smaller server.

We can't really guess how long it will take to run your SQL script on your server.

Re your comment,

@MartinNuc is correct you can choose to make the mysql client print every statement. Or you could open a second session and run mysql> SHOW PROCESSLIST to see what's running. But you probably are more interested in a "percentage done" figure or an estimate for how long it will take to complete the remaining statements.

Sorry, there is no such feature. The mysql client doesn't know how long it will take to run later statements, or even how many there are. So it can't give a meaningful estimate for how much time it will take to complete.

Getting unique items from a list

In .Net 2.0 I`m pretty sure about this solution:

public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
     List<T> uniques = new List<T>();
     foreach (T item in source)
         if (!uniques.Contains(item)) uniques.Add(item);
     return uniques;

How do I call Objective-C code from Swift?

See Apple's guide to Using Swift with Cocoa and Objective-C. This guide covers how to use Objective-C and C code from Swift and vice versa and has recommendations for how to convert a project or mix and match Objective-C/C and Swift parts in an existing project.

The compiler automatically generates Swift syntax for calling C functions and Objective-C methods. As seen in the documentation, this Objective-C:

UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];

turns into this Swift code:

let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)

Xcode also does this translation on the fly — you can use Open Quickly while editing a Swift file and type an Objective-C class name, and it'll take you to a Swift-ified version of the class header. (You can also get this by cmd-clicking on an API symbol in a Swift file.) And all the API reference documentation in the iOS 8 and OS X v10.10 (Yosemite) developer libraries is visible in both Objective-C and Swift forms (e.g. UIView).

Exception from HRESULT: 0x800A03EC Error

This must be the world's most generic error message because I got it today on the following command using Excel Interop:

Excel.WorkbookConnection conn;
conn.ODBCConnection.Connection = "DSN=myserver;";

What fixed it was specifying ODBC in the connection string:

conn.ODBCConnection.Connection = "ODBC;DSN=myserver;";

On the off chance anyone else has this error, I hope it helps.

How to remove a newline from a string in Bash

Clean your variable by removing all the carriage returns:

COMMAND=$(echo $COMMAND|tr -d '\n')

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

Swift 5 : For evenly distributed spaces between cells with dynamic cell width to make the best of container space you may use the code snippet below by providing a minimumCellWidth value.

private func collectionViewLayout() -> UICollectionViewLayout {
    let layout = UICollectionViewFlowLayout()
    layout.sectionHeadersPinToVisibleBounds = true
    // Important: if direction is horizontal use minimumItemSpacing instead. 
    layout.scrollDirection = .vertical
    let itemHeight: CGFloat = 240
    let minCellWidth :CGFloat = 130.0
    let minItemSpacing: CGFloat = 10
    let containerWidth: CGFloat = self.view.bounds.width
    let maxCellCountPerRow: CGFloat =  floor((containerWidth - minItemSpacing) / (minCellWidth+minItemSpacing ))
    let itemWidth: CGFloat = floor( ((containerWidth - (2 * minItemSpacing) - (maxCellCountPerRow-1) * minItemSpacing) / maxCellCountPerRow  ) )
    // Calculate the remaining space after substracting calculating cellWidth (Divide by 2 because of left and right insets)
    let inset = max(minItemSpacing, floor( (containerWidth - (maxCellCountPerRow*itemWidth) - (maxCellCountPerRow-1)*minItemSpacing) / 2 ) )

    layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
    layout.minimumInteritemSpacing = min(minItemSpacing,inset)
    layout.minimumLineSpacing = minItemSpacing
    layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom: minItemSpacing, right: inset)

    return layout

jQuery get value of selected radio button

I am not a javascript person, but I found here for searching this problem. For who google it and find here, I am hoping that this helps some. So, as in question if we have a list of radio buttons:

<div class="list">
    <input type="radio" name="b1" value="1">
    <input type="radio" name="b2" value="2" checked="checked">
    <input type="radio" name="b3" value="3">

I can find which one selected with this selector:

$('.list input[type="radio"]:checked:first').val();

Even if there is no element selected, I still don't get undefined error. So, you don't have to write extra if statement before taking element's value.

Here is very basic jsfiddle example.

jQuery - how to check if an element exists?

jQuery should be able to find even hidden elements. It also has the :visible and :hidden selectors to find both visible and hidden elements.

Does this help? Not sure without more info.

Show DialogFragment with animation growing from a point

If you want to work over APIs you have to do inside your DialogFragemnt->onStart and not inside onCreateDialog

    public void onStart() 
        if (getDialog() == null) 



Increasing nesting function calls limit

This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:

xdebug.max_nesting_level = 200

or in your PHP code:

ini_set('xdebug.max_nesting_level', 200);

As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.

What is the maximum number of edges in a directed graph with n nodes?

There can be as many as n(n-1)/2 edges in the graph if not multi-edge is allowed.

And this is achievable if we label the vertices 1,2,...,n and there's an edge from i to j iff i>j.

See here.

ECMAScript 6 arrow function that returns an object


When you do are doing:

p => {foo: "bar"}

JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.


If your arrow function expression has a single statement, then you can use the following syntax:

p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})

But if you want to have multiple statements then you can use the following syntax:

p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}

In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements

For more details, check Mozilla Docs for JS Arrow Function Expressions

Java ArrayList for integers

Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.

For Ex:

list.add(new Integer[3]);

In this way first entry of ArrayList is an integer array which can hold at max 3 values.

Compression/Decompression string with C#

I like @fubo's answer the best but I think this is much more elegant.

This method is more compatible because it doesn't manually store the length up front.

Also I've exposed extensions to support compression for string to string, byte[] to byte[], and Stream to Stream.

public static class ZipExtensions
    public static string CompressToBase64(this string data)
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(data).Compress());

    public static string DecompressFromBase64(this string data)
        return Encoding.UTF8.GetString(Convert.FromBase64String(data).Decompress());
    public static byte[] Compress(this byte[] data)
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
            return destinationStream.ToArray();

    public static byte[] Decompress(this byte[] data)
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
            return destinationStream.ToArray();
    public static void CompressTo(this Stream stream, Stream outputStream)
        using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))

    public static void DecompressTo(this Stream stream, Stream outputStream)
        using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))

How to hide elements without having them take space on the page?

above my knowledge it is possible in 4 ways

  1. HTML<button style="display:none;"></button>
  2. CSS #buttonId{ display:none; }
  3. jQuery $('#buttonId').prop('display':'none'); & $("#buttonId").css('opacity', 0);

Using a cursor with dynamic SQL in a stored procedure

Another option in SQL Server is to do all of your dynamic querying into table variable in a stored proc, then use a cursor to query and process that. As to the dreaded cursor debate :), I have seen studies that show that in some situations, a cursor can actually be faster if properly set up. I use them myself when the required query is too complex, or just not humanly (for me ;) ) possible.

How can I catch an error caused by mail()?

According to, use:


Which will return an array of the last error generated. You can access the [message] element to display the error.

Calling a Function defined inside another function in Javascript

You are not calling the function inner, just defining it.

function outer() { 
    function inner() {

    inner(); //Call the inner function


How to multiply values using SQL

You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.

SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

What is the best way to declare global variable in Vue.js?

a vue3 replacement of this answer:

// Vue3

const app = Vue.createApp({})
app.config.globalProperties.$hostname = 'http://localhost:3000'

app.component('a-child-component', {
  mounted() {
    console.log(this.$hostname) // 'http://localhost:3000'

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at for more details:

Include another HTML file in a HTML file

Expanding lolo's answer from above, here is a little more automation if you have to include a lot of files. Use this JS code:

$(function () {
  var includes = $('[data-include]')
  $.each(includes, function () {
    var file = 'views/' + $(this).data('include') + '.html'

And then to include something in the html:

<div data-include="header"></div>
<div data-include="footer"></div>

Which would include the file views/header.html and views/footer.html.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

I used the following two steps which I found in the comments/posts linked in the other answers:

Step one: Convert the x.509 cert and key to a pkcs12 file

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root

Note: Make sure you put a password on the pkcs12 file - otherwise you'll get a null pointer exception when you try to import it. (In case anyone else had this headache). (Thanks jocull!)

Note 2: You might want to add the -chain option to preserve the full certificate chain. (Thanks Mafuba)

Step two: Convert the pkcs12 file to a Java keystore

keytool -importkeystore \
        -deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
        -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
        -alias [some-alias]


OPTIONAL Step zero: Create self-signed certificate

openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt


Open file in a relative location in Python

This code works fine:

import os

def readFile(filename):
    filehandle = open(filename)

fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename

Connecting to via command line

Using Linux or OSx, do what Sorin recommended but use port 465 instead. 25 is the generic SMTP port, but not what GMail uses. Also, I don't believe you want to use -starttls smtp

openssl s_client -connect

You should get lots of information on the SSL session and the response:

220 ...

Type in


and you'll receive:

250 at your service

From there it is not quite as straightforward as just sending SMTP messages because Gmail has protections in place to ensure you only send emails appearing to be from accounts that actually belong to you. Instead of typing in "Helo", use "Ehlo". I don't know much about SMTP so I cannot explain the difference, and don't have time to research much. Perhaps someone with more knowledge can explain.

Then, type "auth login" and you will receive the following:

334 VXNlcm5hbWU6

This is essentially the word "Username" encoded in Base 64. Using a Base 64 encoder such as this one, encode your user name and enter it. Do the same for your password, which is requested next. You should see:

235 2.7.0 Accepted

And that's it, you're logged in.

There is one more oddity to overcome if you're using OSx or Linux terminals. Just pressing the "ENTER" key does not apparently result in a CRLF which SMTP needs to end a message. You have to use "CTRL+V+ENTER". So, this should look like the following:

250 2.0.0 OK

if, elif, else statement issues in Bash

I would recommend you having a look at the basics of conditioning in bash.

The symbol "[" is a command and must have a whitespace prior to it. If you don't give whitespace after your elif, the system interprets elif[ as a a particular command which is definitely not what you'd want at this time.



In short, edit your code segment to:

elif [ "$seconds" -gt 0 ]

You'd be fine with no compilation errors. Your final code segment should look like this:

if [ "$seconds" -eq 0 ];then
    elif [ "$seconds" -gt 0 ]
       $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
       echo "Unknown parameter"

How to keep the local file or the remote file during merge using Git and the command line?

For the line-end thingie, refer to man git-merge:


Be sure to add autocrlf = false and/or safecrlf = false to the windows clone (.git/config)

Using git mergetool

If you configure a mergetool like this:

git config mergetool.cp.cmd '/bin/cp -v "$REMOTE" "$MERGED"'
git config mergetool.cp.trustExitCode true

Then a simple

git mergetool --tool=cp
git mergetool --tool=cp -- paths/to/files.txt
git mergetool --tool=cp -y -- paths/to/files.txt # without prompting

Will do the job

Using simple git commands

In other cases, I assume

git checkout HEAD -- path/to/myfile.txt

should do the trick

Edit to do the reverse (because you screwed up):

git checkout remote/branch_to_merge -- path/to/myfile.txt

How do you count the elements of an array in java

  1. Your code won't compile, it should be int [] theArray = new int[20];;
  2. You can get the array length as theArray.length;
  3. For primitive types, the array will be initialized with the default values (0 for int).
  4. You can make it Integer [] theArray = new Integer[20]; and then count initialized members as this code does:

    public int count(Object [] array) {
        int c = 0;
        for(Object el: array) { if(el != null) c++; }
            return c;

Please note that this answer isn't about why you may need this and what is the best way to do what you want.

Setting a system environment variable from a Windows batch file?

If you set a variable via SETX, you cannot use this variable or its changes immediately. You have to restart the processes that want to use it.

Use the following sequence to directly set it in the setting process too (works for me perfectly in scripts that do some init stuff after setting global variables):

SET XYZ=test

Redirecting Output from within Batch file

I know this is an older post, but someone will stumble across it in a Google search and it also looks like some questions the OP asked in comments weren't specifically addressed. Also, please go easy on me since this is my first answer posted on SO. :)

To redirect the output to a file using a dynamically generated file name, my go-to (read: quick & dirty) approach is the second solution offered by @dbenham. So for example, this:

@echo off
> filename_prefix-%DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log (
echo Your Name Here
echo Beginning Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log
REM do some stuff here
echo Your Name Here
echo Ending Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log

Will create a file like what you see in this screenshot of the file in the target directory

That will contain this output:

Your Name Here
Beginning Date/Time: 2016-09-16_141048.log
Your Name Here
Ending Date/Time: 2016-09-16_141048.log

Also keep in mind that this solution is locale-dependent, so be careful how/when you use it.

Make TextBox uneditable

Enabled="false" in aspx page

Get paragraph text inside an element


  <li onclick="myfunction(this)">
    <p>This Text</p>


function myfunction(foo) {
    var elem = foo.getElementsByTagName('p');
    var TextInsideLi = elem[0].innerHTML;

How to disable an Android button?

If you need to disable button add this line of code.

Button button = findViewById(

And enable button , just add this line


Happy coding :D

Redirecting exec output to a buffer or file

You could also use the linux sh command and pass it a command that includes the redirection:

string cmd = "/bin/ls > " + filepath;

execl("/bin/sh", "sh", "-c", cmd.c_str(), 0);

Pandas convert dataframe to array of tuples

Here's a vectorized approach (assuming the dataframe, data_set to be defined as df instead) that returns a list of tuples as shown:

>>> df.set_index(['data_date'])[['data_1', 'data_2']].to_records().tolist()


[(datetime.datetime(2012, 2, 17, 0, 0), 24.75, 25.03),
 (datetime.datetime(2012, 2, 16, 0, 0), 25.0, 25.07),
 (datetime.datetime(2012, 2, 15, 0, 0), 24.99, 25.15),
 (datetime.datetime(2012, 2, 14, 0, 0), 24.68, 25.05),
 (datetime.datetime(2012, 2, 13, 0, 0), 24.62, 24.77),
 (datetime.datetime(2012, 2, 10, 0, 0), 24.38, 24.61)]

The idea of setting datetime column as the index axis is to aid in the conversion of the Timestamp value to it's corresponding datetime.datetime format equivalent by making use of the convert_datetime64 argument in DF.to_records which does so for a DateTimeIndex dataframe.

This returns a recarray which could be then made to return a list using .tolist

More generalized solution depending on the use case would be:

df.to_records().tolist()                              # Supply index=False to exclude index

How to align content of a div to the bottom

All these answers and none worked for me... I'm no flexbox expert, but this was reasonably easy to figure out, it is simple and easy to understand and use. To separate something from the rest of the content, insert an empty div and let it grow to fill the space.

.myContainer {
  display: flex;
  height: 250px;
  flex-flow: column;

.filler {
  flex: 1 1;

<div class="myContainer">
  <div class="filler"></div>

This reacts as expected when the bottom content is not fixed sized also when the container is not fixed sized.

How can I check whether an array is null / empty?

ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty

Filter Java Stream to 1 and only 1 element

I went with the direct-approach and just implemented the thing:

public class CollectSingle<T> implements Collector<T, T, T>, BiConsumer<T, T>, Function<T, T>, Supplier<T> {
T value;

public Supplier<T> supplier() {
    return this;

public BiConsumer<T, T> accumulator() {
    return this;

public BinaryOperator<T> combiner() {
    return null;

public Function<T, T> finisher() {
    return this;

public Set<Characteristics> characteristics() {
    return Collections.emptySet();

@Override //accumulator
public void accept(T ignore, T nvalue) {
    if (value != null) {
        throw new UnsupportedOperationException("Collect single only supports single element, "
                + value + " and " + nvalue + " found.");
    value = nvalue;

@Override //supplier
public T get() {
    value = null; //reset for reuse
    return value;

@Override //finisher
public T apply(T t) {
    return value;


with the JUnit test:

public class CollectSingleTest {

public void collectOne( ) {
    List<Integer> lst = new ArrayList<>();
    Integer o = new CollectSingle<>());

@Test(expected = UnsupportedOperationException.class)
public void failOnTwo( ) {
    List<Integer> lst = new ArrayList<>();
    Integer o = new CollectSingle<>());


This implementation not threadsafe.

Unicode character for "X" cancel / close?

× &#215; or &times; (same thing) U+00D7 multiplication sign

× same character with a strong font weight

? &#10799; U+2A2F Gibbs product

? &#10006; U+2716 heavy multiplication sign

There's also an emoji ❌ if you support it. If you don't you just saw a square = &#10060;

I also made this simple code example on Codepen when I was working with a designer who asked me to show her what it would look like when I asked if I could replace your close button with a coded version rather than an image.

  <li class="ele">
    <div class="x large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop large"><b></b><b></b><b></b><b></b></div>
    <div class="x t large"><b></b><b></b><b></b><b></b></div>
    <div class="x shift large"><b></b><b></b><b></b><b></b></div>
  <li class="ele">
    <div class="x medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop medium"><b></b><b></b><b></b><b></b></div>
    <div class="x t medium"><b></b><b></b><b></b><b></b></div>
    <div class="x shift medium"><b></b><b></b><b></b><b></b></div>

  <li class="ele">
    <div class="x small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop small"><b></b><b></b><b></b><b></b></div>
    <div class="x t small"><b></b><b></b><b></b><b></b></div>
    <div class="x shift small"><b></b><b></b><b></b><b></b></div>
    <div class="x small grow"><b></b><b></b><b></b><b></b></div>

  <li class="ele">
    <div class="x switch"><b></b><b></b><b></b><b></b></div>

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

Use the collate clause in your query:

LEFT JOIN C tO_C on tA.FieldName = 'CID' AND tA.oldValue COLLATE Latin1_General_CI_AS = tO_C.Name  

I may not have the syntax exactly right (check BOL), but you can do this to change the collation on-the-fly for the query - you may need to add the clause for each join.

edit: I realized this was not quite right - the collate clause goes after the field you need to change - in this example I changed the collation on the tA.oldValue field.

How do you kill all current connections to a SQL Server 2005 database?

In MS SQL Server Management Studio on the object explorer, right click on the database. In the context menu that follows select 'Tasks -> Take Offline'

Fetch API request timeout?

Building on Endless' excellent answer, I created a helpful utility function.

const fetchTimeout = (url, ms, { signal, ...options } = {}) => {
    const controller = new AbortController();
    const promise = fetch(url, { signal: controller.signal, ...options });
    if (signal) signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return promise.finally(() => clearTimeout(timeout));
  1. If the timeout is reached before the resource is fetched then the fetch is aborted.
  2. If the resource is fetched before the timeout is reached then the timeout is cleared.
  3. If the input signal is aborted then the fetch is aborted and the timeout is cleared.
const controller = new AbortController();

document.querySelector("button.cancel").addEventListener("click", () => controller.abort());

fetchTimeout("example.json", 5000, { signal: controller.signal })
    .then(response => response.json())
    .catch(error => {
        if ( === "AbortError") {
            // fetch aborted either due to timeout or due to user clicking the cancel button
        } else {
            // network error or json parsing error

Hope that helps.

Advantages of std::for_each over for loop

Aside from readability and performance, one aspect commonly overlooked is consistency. There are many ways to implement a for (or while) loop over iterators, from:

for (C::iterator iter = c.begin(); iter != c.end(); iter++) {


C::iterator iter = c.begin();
C::iterator end = c.end();
while (iter != end) {

with many examples in between at varying levels of efficiency and bug potential.

Using for_each, however, enforces consistency by abstracting away the loop:

for_each(c.begin(), c.end(), do_something);

The only thing you have to worry about now is: do you implement the loop body as function, a functor, or a lambda using Boost or C++0x features? Personally, I'd rather worry about that than how to implement or read a random for/while loop.

Android SDK Manager gives "Failed to fetch URL" error when selecting repository

Open Android SDK Manager and open menu Tools->Options

in Proxy Setting Part Set your proxy and ok

'ssh-keygen' is not recognized as an internal or external command

for all windows os

cd C:\Program Files (x86)\Git\bin

C++ "was not declared in this scope" compile error

As the compiler says, grid was not declared in the scope of your function :) "Scope" basically means a set of curly braces. Every variable is limited to the scope in which it is declared (it cannot be accessed outside that scope). In your case, you're declaring the grid variable in your main() function and trying to use it in nonrecursivecountcells(). You seem to be passing it as the argument colors however, so I suggest you just rename your uses of grid in nonrecursivecountcells() to colors. I think there may be something wrong with trying to pass the array that way, too, so you should probably investigate passing it as a pointer (unless someone else says something to the contrary).

Executing periodic actions in Python

This will insert a 10 second sleep in between every call to foo(), which is approximately what you asked for should the call complete quickly.

import time

while True:

To do other things while your foo() is being called in a background thread

import time
import sys
import threading

def foo():
    sys.stdout.write('({}) foo\n'.format(time.ctime()))

def foo_target():
    while True:

t = threading.Thread(target=foo_target)
t.daemon = True
print('doing other things...')

What is the JUnit XML format specification that Hudson supports?

There are multiple schemas for "JUnit" and "xUnit" results.

Please note that there are several versions of the schema in use by the Jenkins xunit-plugin (the current latest version is junit-10.xsd which adds support for Erlang/OTP Junit format).

Some testing frameworks as well as "xUnit"-style reporting plugins also use their own secret sauce to generate "xUnit"-style reports, those may not use a particular schema (please read: they try to but the tools may not validate against any one schema). Python unittests in Jenkins? gives a quick comparison of several of these libraries and slight differences between the xml reports generated.

Convert an image (selected by path) to base64 string

Based on top voted answer, updated for C# 8. Following can be used out of the box. Added explicit System.Drawing before Image as one might be using that class from other namespace defaultly.

public static string ImagePathToBase64(string path)
    using System.Drawing.Image image = System.Drawing.Image.FromFile(path);
    using MemoryStream m = new MemoryStream();
    image.Save(m, image.RawFormat);
    byte[] imageBytes = m.ToArray();
    tring base64String = Convert.ToBase64String(imageBytes);
    return base64String;

Error: Specified cast is not valid. (SqlManagerUI)

Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?


if it gives error like:

Msg 3241, Level 16, State 13, Line 2 The media family on device 'd:\alibaba.bak' is incorrectly formed. SQL Server cannot process this media family. Msg 3013, Level 16, State 1, Line 2 VERIFY DATABASE is terminating abnormally.

Check it further:


BackupName is "* INCOMPLETE *", Position is "1", other fields are "NULL".

Means either your backup is corrupt or taken from newer version.

Get the client's IP address in

In 2.0: you can use:


works with transports: ['websocket']

Increment variable value by 1 ( shell programming)

You can try this :


Press Keyboard keys using a batch file

Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)

The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.

@if (@CodeSection == @Batch) @then

@echo off

rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"

rem Start the other program in the same Window
start "" /B cmd

%SendKeys% "echo off{ENTER}"

set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"

set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 > NUL
%SendKeys% "{UP}"

set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 > NUL
%SendKeys% "{ENTER}"

%SendKeys% "exit{ENTER}"

goto :EOF


// JScript section

var WshShell = WScript.CreateObject("WScript.Shell");

For a list of key names for SendKeys, see:

For example:


For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs

How to install a node.js module without using npm?

Download the code from github into the node_modules directory

var moduleName = require("<name of directory>")

that should do it.

if the module has dependancies and has a package.json, open the module and enter npm install.

Hope this helps

What is the difference between state and props in React?

For parent-child communication, simply pass props.

Use state to store the data your current page needs in your controller-view.

Use props to pass data & event handlers down to your child components.

These lists should help guide you when working with data in your components.


  • are immutable
    • which lets React do fast reference checks
  • are used to pass data down from your view-controller
    • your top level component
  • have better performance
    • use this to pass data to child components


  • should be managed in your view-controller
    • your top level component
  • is mutable
  • has worse performance
  • should not be accessed from child components
    • pass it down with props instead

For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. Flux pattern is one of the possible ways to arrange this. -

What Components Should Have State?

Most of your components should simply take some data from props and render it. However, sometimes you need to respond to user input, a server request or the passage of time. For this you use state.

Try to keep as many of your components as possible stateless. By doing this you'll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application.

A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props. The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way. -

What Should Go in State?

State should contain data that a component's event handlers may change to trigger a UI update. In real apps this data tends to be very small and JSON-serializable. When building a stateful component, think about the minimal possible representation of its state, and only store those properties in this.state. Inside of render() simply compute any other information you need based on this state. You'll find that thinking about and writing applications in this way tends to lead to the most correct application, since adding redundant or computed values to state means that you need to explicitly keep them in sync rather than rely on React computing them for you. -

Syntax for a for loop in ruby

Ruby's enumeration loop syntax is different:

collection.each do |item|

This reads as "a call to the 'each' method of the array object instance 'collection' that takes block with 'blockargument' as argument". The block syntax in Ruby is 'do ... end' or '{ ... }' for single line statements.

The block argument '|item|' is optional but if provided, the first argument automatically represents the looped enumerated item.

String delimiter in string.split method

Split uses regex, and the pipe char | has special meaning in regex, so you need to escape it. There are a few ways to do this, but here's the simplest:

String[] tokens = line.split("\\|\\|");

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:


but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

Batch file script to zip files

I know its too late but if you still wanna try

for /d %%X in (*) do (for /d %%a in (%%X) do ( "C:\Program Files\7-Zip\7z.exe" a -tzip "" ".\%%a\" ))

here * is the current folder. for more options try this link

Unable to connect to any of the specified mysql hosts. C# MySQL

Update your connection string as shown below (without port variable as well):

MysqlConn.ConnectionString = "Server=;Database=patholabs;Uid=pankaj;Pwd=master;"

Hope this helps...

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

FROM downloads

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

FROM downloads

How to subtract n days from current date in java?

this will subtract ten days of the current date (before Java 8):

int x = -10;
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, x);
Date tenDaysAgo = cal.getTime();

If you're using Java 8 you can make use of the new Date & Time API (

LocalDate tenDaysAgo =;

For converting the new to the old types and vice versa see: Converting between java.time.LocalDateTime and java.util.Date

How to iterate object in JavaScript?

Use dot notation and/or bracket notation to access object properties and for loops to iterate arrays:

var d, i;

for (i = 0; i <; i++) {
  d =[i];
  alert( + ' ' +;

You can also iterate arrays using loops; however, properties added to Array.prototype may show through, and you may not necessarily get array elements in their correct order, or even in any consistent order.

React Native fixed footer

One could achieve something similar in react native with position: absolute

let footerStyle = {
  position: 'absolute',
  bottom: 0,

There are a few things to keep in mind though.

  1. absolute positions the element relative to its parent.
  2. You might have to set the width and hight of the element manually.
  3. Width and hight will change when orientation changes. This has to be managed manually

A practical style definition would look something like this:

import { Dimensions } from 'react-native';

var screenWidth = Dimensions.get('window').width; //full screen width

let footerStyle = {
  position: 'absolute',
  bottom: 0,
  width: screenWidth,
  height: 60

Powershell: count members of a AD group

If you cannot utilize the ActiveDirectory Module or the Get-ADGroupMember cmdlet, you can do it with the LDAP "in chain"-matching rule:

$GroupDN = "CN=MyGroup,OU=Groups,DC=mydomain,DC=tld"
$LDAPFilter = "(&(objectClass=user)(objectCategory=Person)(memberOf:1.2.840.113556.1.4.1941:=$GroupDN))"

# Ideally using an instance of adsisearcher here:
Get-ADObject -LDAPFilter $LDAPFilter

See MSDN for additional LDAP matching rules implemented in Active Directory

Have border wrap around text

Not sure, if that's what you want, but you could make the inner div an inline-element. This way the border should be wrapped only around the text. Even better than that is to use an inline-element for your title.

Solution 1

<div id="page" style="width: 600px;">
    <div id="title" style="display: inline; border...">Title</div>

Solution 2

<div id="page" style="width: 600px;">
    <span id="title" style="border...">Title</span>

Edit: Strange, SO doesn't interpret my code-examples correctly as block, so I had to use inline-code-method.

How to sort by two fields in Java?

Use Comparator and then put objects into Collection, then Collections.sort();

class Person {

    String fname;
    String lname;
    int age;

    public Person() {

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String getFname() {
        return fname;

    public void setFname(String fname) {
        this.fname = fname;

    public String getLname() {
        return lname;

    public void setLname(String lname) {
        this.lname = lname;

    public Person(String fname, String lname, int age) {
        this.fname = fname;
        this.lname = lname;
        this.age = age;

    public String toString() {
        return fname + "," + lname + "," + age;

public class Main{

    public static void main(String[] args) {
        List<Person> persons = new java.util.ArrayList<Person>();
        persons.add(new Person("abc3", "def3", 10));
        persons.add(new Person("abc2", "def2", 32));
        persons.add(new Person("abc1", "def1", 65));
        persons.add(new Person("abc4", "def4", 10));
        Collections.sort(persons, new Comparator<Person>() {

            public int compare(Person t, Person t1) {
                return t.getAge() - t1.getAge();


How to unset a JavaScript variable?

If you are implicitly declaring the variable without var, the proper way would be to use delete foo.

However after you delete it, if you try to use this in an operation such as addition a ReferenceError will be thrown because you can't add a string to an undeclared, undefined identifier. Example:

x = 5;
delete x
alert('foo' + x )
// ReferenceError: x is not defined

It may be safer in some situations to assign it to false, null, or undefined so it's declared and won't throw this type of error.

foo = false

Note that in ECMAScript null, false, undefined, 0, NaN, or '' would all evaluate to false. Just make sure you dont use the !== operator but instead != when type checking for booleans and you don't want identity checking (so null would == false and false == undefined).

Also note that delete doesn't "delete" references but just properties directly on the object, e.g.:

bah = {}, foo = {}; bah.ref = foo;

delete bah.ref;
alert( [bah.ref, foo ] )
// ,[object Object] (it deleted the property but not the reference to the other object)

If you have declared a variable with var you can't delete it:

(function() {
    var x = 5;
    alert(delete x)
    // false

In Rhino:

js> var x
js> delete x

Nor can you delete some predefined properties like Math.PI:

js> delete Math.PI

There are some odd exceptions to delete as with any language, if you care enough you should read:

How open PowerShell as administrator from the run window

Yes, it is possible to run PowerShell through the run window. However, it would be burdensome and you will need to enter in the password for computer. This is similar to how you will need to set up when you run cmd:

runas /user:(ComputerName)\(local admin) powershell.exe

So a basic example would be:

runas /user:MyLaptop\[email protected]  powershell.exe

You can find more information on this subject in Runas.

However, you could also do one more thing :

  • 1: `Windows+R`
  • 2: type: `powershell`
  • 3: type: `Start-Process powershell -verb runAs`

then your system will execute the elevated powershell.

What's "P=NP?", and why is it such a famous question?

To give the simplest answer I can think of:

Suppose we have a problem that takes a certain number of inputs, and has various potential solutions, which may or may not solve the problem for given inputs. A logic puzzle in a puzzle magazine would be a good example: the inputs are the conditions ("George doesn't live in the blue or green house"), and the potential solution is a list of statements ("George lives in the yellow house, grows peas, and owns the dog"). A famous example is the Traveling Salesman problem: given a list of cities, and the times to get from any city to any other, and a time limit, a potential solution would be a list of cities in the order the salesman visits them, and it would work if the sum of the travel times was less than the time limit.

Such a problem is in NP if we can efficiently check a potential solution to see if it works. For example, given a list of cities for the salesman to visit in order, we can add up the times for each trip between cities, and easily see if it's under the time limit. A problem is in P if we can efficiently find a solution if one exists.

(Efficiently, here, has a precise mathematical meaning. Practically, it means that large problems aren't unreasonably difficult to solve. When searching for a possible solution, an inefficient way would be to list all possible potential solutions, or something close to that, while an efficient way would require searching a much more limited set.)

Therefore, the P=NP problem can be expressed this way: If you can verify a solution for a problem of the sort described above efficiently, can you find a solution (or prove there is none) efficiently? The obvious answer is "Why should you be able to?", and that's pretty much where the matter stands today. Nobody has been able to prove it one way or another, and that bothers a lot of mathematicians and computer scientists. That's why anybody who can prove the solution is up for a million dollars from the Claypool Foundation.

We generally assume that P does not equal NP, that there is no general way to find solutions. If it turned out that P=NP, a lot of things would change. For example, cryptography would become impossible, and with it any sort of privacy or verifiability on the Internet. After all, we can efficiently take the encrypted text and the key and produce the original text, so if P=NP we could efficiently find the key without knowing it beforehand. Password cracking would become trivial. On the other hand, there's whole classes of planning problems and resource allocation problems that we could solve effectively.

You may have heard the description NP-complete. An NP-complete problem is one that is NP (of course), and has this interesting property: if it is in P, every NP problem is, and so P=NP. If you could find a way to efficiently solve the Traveling Salesman problem, or logic puzzles from puzzle magazines, you could efficiently solve anything in NP. An NP-complete problem is, in a way, the hardest sort of NP problem.

So, if you can find an efficient general solution technique for any NP-complete problem, or prove that no such exists, fame and fortune are yours.

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target

So to copy the file /etc/hosts from the server as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

Browser detection in JavaScript?

Here's how to detect browsers in 2016, including Microsoft Edge, Safari 10 and detection of Blink:

// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
isChrome = !! && !!;
// Blink engine detection
isBlink = (isChrome || isOpera) && !!window.CSS;

The beauty of this approach is that it relies on browser engine properties, so it covers even derivative browsers, such as Yandex or Vivaldi, which are practically compatible with the major browsers whose engines they use. The exception is Opera, which relies on user agent sniffing, but today (i.e. ver. 15 and up) even Opera is itself only a shell for Blink.

CRC32 C or C++ implementation

I am the author of the source code at the specified link. While the intention of the source code license is not clear (it will be later today), the code is in fact open and free for use in your free or commercial applications with no strings attached.

File changed listener in Java

I've written a log file monitor before, and I found that the impact on system performance of polling the attributes of a single file, a few times a second, is actually very small.

Java 7, as part of NIO.2 has added the WatchService API

The WatchService API is designed for applications that need to be notified about file change events.

isset in jQuery?

function el(id) {
  return document.getElementById(id);

if (el('one') || el('two') || el('three')) { 

} else if (el('four')) {

How do I create a GUI for a windows application using C++?

I strongly prefer simply using Microsoft Visual Studio and writing a native Win32 app.

For a GUI as simple as the one that you describe, you could simply create a Dialog Box and use it as your main application window. The default application created by the Win32 Project wizard in Visual Studio actually pops a window, so you can replace that window with your Dialog Box and replace the WndProc with a similar (but simpler) DialogProc.

The question, then, is one of tools and cost. The Express Edition of Visual C++ does everything you want except actually create the Dialog Template resource. For this, you could either code it in the RC file by hand or in memory by hand. Related SO question: Windows API Dialogs without using resource files.

Or you could try one of the free resource editors that others have recommended.

Finally, the Visual Studio 2008 Standard Edition is a costlier option but gives you an integrated resource editor.

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist,, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

Android: how to make keyboard enter button say "Search" and handle its click?

by XML:

        android:inputType="text" />

By Java:

    InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    in.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Socket.IO handling disconnect event

For those like @sha1 wondering why the OP's code doesn't work -

OP's logic for deleting player at server side is in the handler for DelPlayer event, and the code that emits this event (DelPlayer) is in inside disconnected event callback of client.

The server side code that emits this disconnected event is inside the disconnect event callback which is fired when the socket loses connection. Since the socket already lost connection, disconnected event doesn't reach the client.

Accepted solution executes the logic on disconnect event at server side, which is fired when the socket disconnects, hence works.

Get the index of a certain value in an array in PHP

array_search should work fine, just tested this and it returns the keys as expected:

$list = array('string1', 'string2', 'string3');
echo "Key = ".array_search('string1', $list);
echo " Key = ".array_search('string2', $list);
echo " Key = ".array_search('string3', $list);

Or for the index, you could use

$list = array('string1', 'string2', 'string3');
echo "Index = ".array_search('string1', array_merge($list));
echo " Index = ".array_search('string2', array_merge($list));
echo " Index = ".array_search('string3', array_merge($list));

How to set time to a date object in java

Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")

Get Android Phone Model programmatically

The following strings are all of use when you want to retrieve manufacturer, name of the device, and/or the model:

String manufacturer = Build.MANUFACTURER;
String brand        = Build.BRAND;
String product      = Build.PRODUCT;
String model        = Build.MODEL;

Closing pyplot windows

Please use

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

How to find my Subversion server version number?

For Subversion 1.7 and above, the server doesn't provide a footer that indicates the server version. But you can run the following command to gain the version from the response headers

$ curl -s -D -
HTTP/1.1 401 Authorization Required
Date: Wed, 09 Jan 2013 03:01:43 GMT
Server: Apache/2.2.9 (Unix) DAV/2 SVN/1.7.4

Note that this also works on Subversion servers where you don't have authorization to access.

T-test in Pandas

I simplify the code a little bit.

from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

My BIOS VT-X was on, but I had to turn PAE/NX off to get the VM to run.

Maven version with a property

See the Maven - Users forum 'version' contains an expression but should be a constant. Better way to add a new version?:

here is why this is a bad plan.

the pom that gets deployed will not have the property value resolved, so anyone depending on that pom will pick up the dependency as being the string uninterpolated with the ${ } and much hilarity will ensue in your build process.

in maven 2.1.0 and/or 2.2.0 an attempt was made to deploy poms with resolved properties... this broke more than expected, which is why those two versions are not recommended, 2.2.1 being the recommended 2.x version.

Exercises to improve my Java programming skills

My recommendation is to solve problems that you're interested in, writing code that might be useful to you.

Java is a huge box. It's got a lot of computer science inside: graphics, scientific computing, relational databases, user interfaces for desktop and web, messaging and queuing, multi-threading, security, and more. Each area has their own "beginner problem". Which one do you mean?

How do you define "beginner problem"? Maybe you're having trouble because you aren't narrowing your search enough.

If your imagination is lacking, your best bet is to Google something like "java beginner practice problems" and investigate what you get back.

Or start with Sun's on-line Java tutorial and work you way all the way through it. You'll know a fair amount about Java when you're done.

How to parse a JSON file in swift?

This answer was last revised for Swift 5.3 and iOS 14.4 SDK.

Given some already obtained JSON data, you can use JSONDecoder to decode it into your Decodable model (or a collection of models).

let data: Data = /* obtain your JSON data */
let model = try JSONDecoder().decode(Model.self, from: data)

Such model must conform to the Decodable protocol and contain correct mapping between properties and JSON dictionary keys. As an example, consider the following JSON array containing search results of cities beginning with "Wa".

        "id": 123,
        "city": "Washington",
        "region": "D.C.",
        "country": "United States"
        "id": 456,
        "city": "Warsaw",
        "region": "Mazowieckie",
        "country": "Poland"

For that, you need to create a model that contains the correct properties of correct types. If you're using a web API, its documentation will be of great help here.

struct SearchResult: Decodable {
    let id: Int
    let city: String
    let region: String
    let country: String

Then decode the data with JSONDecoder:

let results = try JSONDecoder().decode([SearchResult].self, from: data)

Given a new array of decoded search results, call one of UITableView's functions to reload its data. Note that the decode function can throw an error which you must somehow handle.

To learn more about decoding custom types in Swift and more advanced usage of the Codable APIs, I recommend checking out this documentation article.

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

in my case adding <clear /> just after <connectionStrings> worked like charm

Removing elements with in JavaScript

I just wrote array intersection that correctly handles also duplicates

// array intersection that correctly handles also duplicates_x000D_
const intersection = (a1, a2) => {_x000D_
  const cnt = new Map();_x000D_ => cnt[el] = el in cnt ? cnt[el] + 1 : 1);_x000D_
  return a1.filter(el => el in cnt && 0 < cnt[el]--);_x000D_
const l = console.log;_x000D_
l(intersection('1234'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12344'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('1234'.split``, '33456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12334'.split``, '33456'.split``)); // [ '3', '3', '4' ]

"Input string was not in a correct format."

You might be trying to access a control inside a control, maybe a GridView or DetailsView.

Try using something like this:

empsalary = Convert.ToInt32(((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text);

How do I insert datetime value into a SQLite database?

The format you need is:

'2007-01-01 10:00:00'

i.e. yyyy-MM-dd HH:mm:ss

If possible, however, use a parameterised query as this frees you from worrying about the formatting details.

How do I create a ListView with rounded corners in Android?

There are different ways to achieve it. The latest approach is using CardView for each ListItem component. Here are some steps.

  1. Create a layout resource file; let's name it "listitem.xml
  2. Copy and paste the under enclosed Listitem.xml layout body into it.
  3. Create RowItem class for each listitem data; later you will instantiate this to assign values for each list item. Check Code below, RowItem.class.
  4. Create a custom ListAdapter; let's name it ListAdapter.class, and inflate this (#1) list item layout for each list item (Check the second code snippet for this one)
  5. Set this adapter (#3) the way you set default adapters inside an activity the listview belongs to. maybe the only difference would be you first have to instantiate RowItem class with values and add RowItem object to your adapter then notify your adapter that the data is changed.
<?xml version="1.0" encoding="utf-8"?>

                    <LinearLayout android:layout_width="wrap_content"
                            android:text="Main Heading"
                            android:textStyle="bold" />
                            android:text="Sub Heading"


public class RowItem {
    private String heading;
    private String subHeading;
    private int smallImageName;
    private String datetime;
    private int count;

    public void setHeading( String theHeading ) {
        this.heading = theHeading;

    public String getHeading() {
        return this.heading;
    public void setSubHeading( String theSubHeading ) {

        this.subHeading = theSubHeading;


    public String getSubHeading( ) {

        return this.subHeading;


    public void setSmallImageName(int smallName) {

        this.smallImageName = smallName;


    public int getSmallImageName() {

        return this.smallImageName;


    public void setDate(String datetime) {
        this.datetime = datetime;

    public String getDate() {
        return this.datetime;

    public void setCount(int count) {
        this.count = count;

    public int getCount() {
        return this.count;


Sample ListAdapter

public class ListAdapter extends BaseAdapter {
    private ArrayList<RowItem> singleRow;
    private LayoutInflater thisInflater;

    public ListAdapter(Context context, ArrayList<RowItem> aRow){

        this.singleRow = aRow;
        thisInflater = ( LayoutInflater.from(context) );
    public int getCount() {
        return singleRow.size();    }

    public Object getItem(int position) {
        return singleRow.get( position );    }

    public long getItemId(int position) {
        return position;

    public View getView(int position, View view, ViewGroup parent) {

        if (view == null) {
            view = thisInflater.inflate( R.layout.mylist2, parent, false );
            //set listview objects here

            TextView titleText = (TextView) view.findViewById(;
            RowItem currentRow = (RowItem) getItem(position);
            titleText.setText( currentRow.getHeading() );

        return view;

//        LayoutInflater inflater=.getLayoutInflater();
//        View rowView=inflater.inflate(R.layout.mylist, null,true);

//        titleText.setText(maintitle[position]);
//        subtitleText.setText(subtitle[position]);

//        return null;


Create an application setup in visual studio 2013

As of Visual Studio 2012, Microsoft no longer provides the built-in deployment package. If you wish to use this package, you will need to use VS2010.

In 2013 you have several options:

  • InstallShield
  • WiX
  • Roll your own

In my projects I create my own installers from scratch, which, since I do not use Windows Installer, have the advantage of being super fast, even on old machines.

Open S3 object as a string with Boto3

I had a problem to read/parse the object from S3 because of .get() using Python 2.7 inside an AWS Lambda.

I added json to the example to show it became parsable :)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

NOTE (for python 2.7): My object is all ascii, so I don't need .decode('utf-8')

NOTE (for python 3.6+): We moved to python 3.6 and discovered that read() now returns bytes so if you want to get a string out of it, you must use:

j = json.loads(obj['Body'].read().decode('utf-8'))

How to Set Focus on JTextField?

While yourTextField.requestFocus() is A solution, it is not the best since in the official Java documentation this is discourage as the method requestFocus() is platform dependent.

The documentation says:

Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow().

Use yourJTextField.requestFocusInWindow() instead.

Pandas: Convert Timestamp to

Assume time column is in timestamp integer msec format

1 day = 86400000 ms

Here you go:

day_divider = 86400000

df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format

df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format

Using "If cell contains" in VBA excel

Find a cell containing the word TOTAL then to enter a dash in the cell below it.

Solution: This solution uses the Find method of the Range object, as it seems appropriate to use it rather than brute force (For…Next loop). For explanation and details about the method see Range.Find method (Excel)

In order to provide flexibility the Find method is wrapped in this function:

Function Range_ƒFind_Action(sWhat As String, rTrg As Range) As Boolean

sWhat: contains the string to search for
rTrg: is the range to be searched

The function returns True if any match is found, otherwise it returns False

Additionally, every time the function finds a match it passes the resulting range to the procedure Range_Find_Action to execute the required action, (i.e. "enter a dash in the cell below it"). The "required action" is in a separated procedure to allow for customization and flexibility.

This is how the function is called:

This test is searching for "total" to show the effect of the MatchCase:=False. The match can be made case sensitive by changing it to MatchCase:=True

Sub Range_Find_Action_TEST()
Dim sWhat As String, rTrg As Range
Dim sMsgbdy As String
    sWhat = "total"                                             'String to search for (update as required)
    Rem Set rTrg = ThisWorkbook.Worksheets("Sht(0)").UsedRange  'Range to Search (use this to search all used cells)
    Set rTrg = ThisWorkbook.Worksheets("Sht(0)").Rows(6)        'Range to Search (update as required)
    sMsgbdy = IIf(Range_ƒFind_Action(sWhat, rTrg), _
        "Cells found were updated successfully", _
        "No cells were found.")
    MsgBox sMsgbdy, vbInformation, "Range_ƒFind_Action"
    End Sub

This is the Find function

Function Range_ƒFind_Action(sWhat As String, rTrg As Range) As Boolean
Dim rCll As Range, s1st As String
    With rTrg

        Rem Set First Cell Found
        Set rCll = .Find(What:=sWhat, After:=.Cells(1), _
            LookIn:=xlFormulas, LookAt:=xlPart, _
            SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)

        Rem Validate First Cell
        If rCll Is Nothing Then Exit Function
        s1st = rCll.Address

        Rem Perform Action
        Call Range_Find_Action(rCll)

            Rem Find Other Cells
            Set rCll = .FindNext(After:=rCll)
            Rem Validate Cell vs 1st Cell
            If rCll.Address <> s1st Then Call Range_Find_Action(rCll)

        Loop Until rCll.Address = s1st

    End With

    Rem Set Results
    Range_ƒFind_Action = True

    End Function

This is the Action procedure

Sub Range_Find_Action(rCll)
    rCll.Offset(1).Value2 = Chr(167)    'Update as required - Using `§` instead of "-" for visibilty purposes
    End Sub

enter image description here

How to add spacing between columns?

Bootstrap col slightly use some spaces both left and right. I have just added a block element like div and set border for the differences. also adding some extra padding or margin in that extra div will work perfectly..

<link href="" rel="stylesheet"/>


<div class="container">
    <div class="row">
        <div class="col-6 ">
            <div class="border border-danger ">
                <h2 class="text-center">1</h2>
        <div class="col-6">
            <div class="border border-warning">
                <h2 class="text-center">2</h2>

What is the correct syntax for 'else if'?

since olden times, the correct syntax for if/else if in Python is elif. By the way, you can use dictionary if you have alot of if/

if not a in d: print("3a")
else: print (d[a])

For msw, example of executing functions using dictionary.

def print_one(arg=None):
    print "one"

def print_two(num):
    print "two %s" % num

execfunctions = { 1 : (print_one, ['**arg'] ) , 2 : (print_two , ['**arg'] )}
except KeyError,e:
    print "Invalid option: ",e

except KeyError,e:
    print "Invalid option: ",e

jQuery validation plugin: accept only alphabetical characters?

 $('.AlphabetsOnly').keypress(function (e) {
        var regex = new RegExp(/^[a-zA-Z\s]+$/);
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        else {
            return false;

How to load a text file into a Hive table stored as sequence files

You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.

Start with a tab delimited file:

% cat /tmp/input.txt
a       b
a2      b2

create a sequence file

hive> create table test_sq(k string, v string) stored as sequencefile;

try to load; as expected, this will fail:

hive> load data local inpath '/tmp/input.txt' into table test_sq;

But with this table:

hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;

The load works just fine:

hive> load data local inpath '/tmp/input.txt' into table test_t;
hive> select * from test_t;
a       b
a2      b2

Now load into the sequence table from the text table:

insert into table test_sq select * from test_t;

Can also do load/insert with overwrite to replace all.

Best practices for adding .gitignore file for Python projects?

One question is if you also want to use git for the deploment of your projects. If so you probably would like to exclude your local sqlite file from the repository, same probably applies to file uploads (mostly in your media folder). (I'm talking about django now, since your question is also tagged with django)

Django Forms: if not valid, show form with error message

UPDATE: Added a more detailed description of the formset errors.

Form.errors combines all field and non_field_errors. Therefore you can simplify the html to this:


    {% load form_tags %}

    {% if form.errors %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">
            {% for key, value in form.errors.items %}
                <span class="fieldWrapper">
                    {{ key }}:{{ value }}
            {% endfor %}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
    {% endif %}

If you want to generalise it you can create a list_errors.html which you include in every form template. It handles form and formset errors:

    {% if form.errors %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">

            {% for key, value in form.errors.items %}
                <span class="fieldWrapper">
                    {{ key }}:{{ value }}
            {% endfor %}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
    {% elif formset.total_error_count %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">
            {% if formset.non_form_errors %}
                {{ formset.non_form_errors }}
            {% endif %}
            {% for form in formset.forms %}
                {% if form.errors %}
                    Form number {{ forloop.counter }}:
                    <ul class="errorlist">
                    {% for key, error in form.errors.items %}
                            <ul class="errorlist">
                    {% endfor %}
                {% endif %}
            {% endfor %}


    {% endif %}

from django import template

register = template.Library()

def get_label(a_dict, key):
    return getattr(a_dict.get(key), 'label', 'No label')

register.filter("get_label", get_label)

One caveat: In contrast to forms Formset.errors does not include non_field_errors.

Can I fade in a background image (CSS: background-image) with jQuery?

With modern browser i prefer a much lightweight approach with a bit of Js and CSS3...

transition: background 300ms ease-in 200ms;

Look at this demo:

How to create the pom.xml for a Java project with Eclipse

To create POM.XML file in Eclipse:

  1. Install M2E plugin (

  2. Right click on project -> Configure -> Convert to Maven Project

How to pass table value parameters to stored procedure from .net code


   public static DataTable ToTableValuedParameter<T, TProperty>(this IEnumerable<T> list, Func<T, TProperty> selector)
        var tbl = new DataTable();
        tbl.Columns.Add("Id", typeof(T));

        foreach (var item in list)


        return tbl;


Jackson - best way writes a java list to a json array

In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.

List<Apartment> aptList =  new ArrayList<Apartment>();
    Apartment aptmt = null;
    for(int i=0;i<5;i++){
         aptmt= new Apartment();
         aptmt.setAptName("Apartment Name : ArrowHead Ranch");

Running Python in PowerShell?

As far as I have understood your question, you have listed two issues.


You are not able to execute the Python scripts by double clicking the Python file in Windows.


The script runs too fast to be seen by the human eye.


Add input() in the bottom of your script and then try executing it with double click. Now the cmd will be open until you close it.


print("Hello World")


./ issue


Use Tab to autocomplete the filenames rather than manually typing the filename with ./ autocomplete automatically fills all this for you.


CD into the directory in which .py files are present and then assume the filename is then type python te and then press Tab, it will be automatically converted to python ./

Creating an array from a text file in Bash

Use mapfile or read -a

Always check your code using shellcheck. It will often give you the correct answer. In this case SC2207 covers reading a file that either has space separated or newline separated values into an array.

Don't do this

array=( $(mycommand) )

Files with values separated by newlines

mapfile -t array < <(mycommand)

Files with values separated by spaces

IFS=" " read -r -a array <<< "$(mycommand)"

The shellcheck page will give you the rationale why this is considered best practice.

Difference between java.exe and javaw.exe

The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window

Refreshing data in RecyclerView and keeping its scroll position

 mMessageAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        public void onChanged() {
            mLayoutManager.smoothScrollToPosition(mMessageRecycler, null, mMessageAdapter.getItemCount());

The solution here is to keep on scrolling recyclerview when new message comes.

The onChanged() method detects the action performed on recyclerview.

How do you check if a variable is an array in JavaScript?

Via Crockford:

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
        } else {
            s = 'null';
    return s;

The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window. That page has a much more sophisticated version if this is insufficient.

Location of sqlite database on the device

You can find your created database, named <your-database-name>



Pull it out using File explorer and rename it to have .db3 extension to use it in SQLiteExplorer

Use File explorer of DDMS to navigate to emulator directory.

npm install gives error "can't find a package.json file"

I'm not sure what you're trying to do here:

npm install alone in your home directory shouldn't do much -- it's not the root of a node app, so there's nothing to install, since there's no package.json.

There are two possible solutions:

1) cd to a node app and run npm install there. OR

2) if you're trying to install something as a command to use in the shell (You don't have a node application), npm install -g packagename. -g flag tells it to install in global namespace.

How to get a pixel's x,y coordinate color from an image?

Building on Jeff's answer, your first step would be to create a canvas representation of your PNG. The following creates an off-screen canvas that is the same width and height as your image and has the image drawn on it.

var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

After that, when a user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to acquire the pixel:

var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

Because you are only grabbing one pixel, pixelData is a four entry array containing the pixel's R, G, B, and A values. For alpha, anything less than 255 represents some level of transparency with 0 being fully transparent.

Here is a jsFiddle example: I used jQuery for convenience in all of this, but it is by no means required.

Note: getImageData falls under the browser's same-origin policy to prevent data leaks, meaning this technique will fail if you dirty the canvas with an image from another domain or (I believe, but some browsers may have solved this) SVG from any domain. This protects against cases where a site serves up a custom image asset for a logged in user and an attacker wants to read the image to get information. You can solve the problem by either serving the image from the same server or implementing Cross-origin resource sharing.

Create a new Ruby on Rails application using MySQL instead of SQLite

You should use the switch -D instead of -d because it will generate two apps and mysql with no documentation folders.

  rails -D mysql project_name  (less than version 3)

  rails new project_name -D mysql (version 3 and up)

Alternatively you just use the --database option.

Which keycode for escape key with jQuery

Your best bet is

$(document).keyup(function(e) { 
    if (e.which === 13) $('.save').click();   // enter 
    if (e.which === 27) $('.cancel').click(); // esc   

    /* OPTIONAL: Only if you want other elements to ignore event */


  • which is more preferable than keyCode because it is normalized
  • keyup is more preferable than keydown because keydown may occur multiple times if user keeps it pressed.
  • Do not use keypress unless you want to capture actual characters.

Interestingly Bootstrap uses keydown and keyCode in its dropdown component (as of 3.0.2)! I think it's probably poor choice there.

Related snippet from JQuery doc

While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, .keypress() may be a better choice.

Other item of interest: JavaScript Keypress Library

Get Max value from List<myType>

Okay, so if you don't have LINQ, you could hard-code it:

public int FindMaxAge(List<MyType> list)
    if (list.Count == 0)
        throw new InvalidOperationException("Empty list");
    int maxAge = int.MinValue;
    foreach (MyType type in list)
        if (type.Age > maxAge)
            maxAge = type.Age;
    return maxAge;

Or you could write a more general version, reusable across lots of list types:

public int FindMaxValue<T>(List<T> list, Converter<T, int> projection)
    if (list.Count == 0)
        throw new InvalidOperationException("Empty list");
    int maxValue = int.MinValue;
    foreach (T item in list)
        int value = projection(item);
        if (value > maxValue)
            maxValue = value;
    return maxValue;

You can use this with:

// C# 2
int maxAge = FindMaxValue(list, delegate(MyType x) { return x.Age; });

// C# 3
int maxAge = FindMaxValue(list, x => x.Age);

Or you could use LINQBridge :)

In each case, you can return the if block with a simple call to Math.Max if you want. For example:

foreach (T item in list)
    maxValue = Math.Max(maxValue, projection(item));

How to specify HTTP error code?

Express deprecated res.send(body, status).

Use res.status(status).send(body) instead

Can you 'exit' a loop in PHP?

You can use the break keyword.

In Python, can I call the main() of an imported module?

Martijen's answer makes sense, but it was missing something crucial that may seem obvious to others but was hard for me to figure out.

In the version where you use argparse, you need to have this line in the main body.

args = parser.parse_args(args)

Normally when you are using argparse just in a script you just write

args = parser.parse_args()

and parse_args find the arguments from the command line. But in this case the main function does not have access to the command line arguments, so you have to tell argparse what the arguments are.

Here is an example

import argparse
import sys

def x(x_center, y_center):
    print "X center:", x_center
    print "Y center:", y_center

def main(args):
    parser = argparse.ArgumentParser(description="Do something.")
    parser.add_argument("-x", "--xcenter", type=float, default= 2, required=False)
    parser.add_argument("-y", "--ycenter", type=float, default= 4, required=False)
    args = parser.parse_args(args)
    x(args.xcenter, args.ycenter)

if __name__ == '__main__':

Assuming you named this To run it you can either do any of these from the command line

python ./ -x 8
python ./ -x 8 -y 2
python ./ 

which returns respectively

X center: 8.0
Y center: 4


X center: 8.0
Y center: 2.0


X center: 2
Y center: 4

Or if you want to run from another python script you can do

import mytest

which returns

X center: 7.0
Y center: 6.0

How do I check if a C++ string is an int?

Ok, the way I see it you have 3 options.

1: If you simply wish to check whether the number is an integer, and don't care about converting it, but simply wish to keep it as a string and don't care about potential overflows, checking whether it matches a regex for an integer would be ideal here.

2: You can use boost::lexical_cast and then catch a potential boost::bad_lexical_cast exception to see if the conversion failed. This would work well if you can use boost and if failing the conversion is an exceptional condition.

3: Roll your own function similar to lexical_cast that checks the conversion and returns true/false depending on whether it's successful or not. This would work in case 1 & 2 doesn't fit your requirements.

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

Remove the Debug permissions on the Device, with the cell phone connected, then put them back, and ask if you want to allow the PC to have debug, accept and ready permissions: D

What is the difference between statically typed and dynamically typed languages?

The terminology "dynamically typed" is unfortunately misleading. All languages are statically typed, and types are properties of expressions (not of values as some think). However, some languages have only one type. These are called uni-typed languages. One example of such a language is the untyped lambda calculus.

In the untyped lambda calculus, all terms are lambda terms, and the only operation that can be performed on a term is applying it to another term. Hence all operations always result in either infinite recursion or a lambda term, but never signal an error.

However, were we to augment the untyped lambda calculus with primitive numbers and arithmetic operations, then we could perform nonsensical operations, such adding two lambda terms together: (?x.x) + (?y.y). One could argue that the only sane thing to do is to signal an error when this happens, but to be able to do this, each value has to be tagged with an indicator that indicates whether the term is a lambda term or a number. The addition operator will then check that indeed both arguments are tagged as numbers, and if they aren't, signal an error. Note that these tags are not types, because types are properties of programs, not of values produced by those programs.

A uni-typed language that does this is called dynamically typed.

Languages such as JavaScript, Python, and Ruby are all uni-typed. Again, the typeof operator in JavaScript and the type function in Python have misleading names; they return the tags associated with the operands, not their types. Similarly, dynamic_cast in C++ and instanceof in Java do not do type checks.

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

sqlplus "/as sysdba"
alter system disable restricted session;

or maybe

shutdown abort;

or maybe

lsnrctl stop

lsnrctl start

Pythonic way to check if a list is sorted or not

Although I don't think there is a guarantee for that the sorted built-in calls its cmp function with i+1, i, it does seem to do so for CPython.

So you could do something like:

def my_cmp(x, y):
   cmpval = cmp(x, y)
   if cmpval < 0:
      raise ValueError
   return cmpval

def is_sorted(lst):
      sorted(lst, cmp=my_cmp)
      return True
   except ValueError:
      return False

print is_sorted([1,2,3,5,6,7])
print is_sorted([1,2,5,3,6,7])

Or this way (without if statements -> EAFP gone wrong? ;-) ):

def my_cmp(x, y):
   assert(x >= y)
   return -1

def is_sorted(lst):
      sorted(lst, cmp=my_cmp)
      return True
   except AssertionError:
      return False

Check if a Python list item contains a string inside another string

I did a search, which requires you to input a certain value, then it will look for a value from the list which contains your input:

my_list = ['abc-123',

imp = raw_input('Search item: ')

for items in my_list:
    val = items
    if any(imp in val for items in my_list):

Try searching for 'abc'.

Laravel Query Builder where max id

For Laravel ^5


I used it is short and best;

How can I trim beginning and ending double quotes from a string?

public String removeDoubleQuotes(String request) {
    return request.replace("\"", "");

UTF-8 encoded html pages show ? (questions marks) instead of characters

The problem is the charset that is being used by apache to serve the pages. I work with Linux, so I don't know anything about XAMPP. I had the same problem too, what I did to solve the problem was to add the charset to the charset config file (It is commented by default).

In my case I have it in /etc/apache2/conf.d/charset but, since you're using Windows the location is different. So I'm giving you this like an idea of how to solve it.

At the end, my charset config file is like this:

# Read the documentation before enabling AddDefaultCharset.
# In general, it is only a good idea if you know that all your files
# have this encoding. It will override any encoding given in the files
# in meta http-equiv or xml encoding tags.

AddDefaultCharset UTF-8

I hope it helps.

Binding ComboBox SelectedItem using MVVM

I had a similar problem where the SelectedItem-binding did not update when I selected something in the combobox. My problem was that I had to set UpdateSourceTrigger=PropertyChanged for the binding.

<ComboBox ItemsSource="{Binding SalesPeriods}" 
          SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />

Programmatically obtain the phone number of the Android phone

Sometimes, below code returns null or blank string.

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

With below permission

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{""},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
        // This is the phoneNumber
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();

You will need to add these two permissions.

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />

Hope this helps, Thanks!

How do you overcome the HTML form nesting limitation?

HTML5 has an idea of "form owner" - the "form" attribute for input elements. It allows to emulate nested forms and will solve the issue.

Select every Nth element in CSS

Try this


Is try-catch like error handling possible in ASP Classic?

There are two approaches, you can code in JScript or VBScript which do have the construct or you can fudge it in your code.

Using JScript you'd use the following type of construct:

<script language="jscript" runat="server">
try  {
catch(exception) {
finally {

In your ASP code you fudge it by using on error resume next at the point you'd have a try and checking err.Number at the point of a catch like:

' Turn off error Handling
On Error Resume Next

'Code here that you want to catch errors from

' Error Handler
If Err.Number <> 0 Then
   ' Error Occurred - Trap it
   On Error Goto 0 ' Turn error handling back on for errors in your handling block
   ' Code to cope with the error here
End If
On Error Goto 0 ' Reset error handling.


MYSQL query between two timestamps

SELECT * FROM `orders` WHERE `order_date_time`  BETWEEN 1534809600 AND 1536718364

How to view the Folder and Files in GAC?

I'm a day late and a dollar short on this one. If you want to view the folder structure of the GAC in Windows Explorer, you can do this by using the registry:

  1. Launch regedit.
  2. Navigate to HKLM\Software\Microsoft\Fusion
  3. Add a DWORD called DisableCacheViewer and set the value to 1.

For a temporary view, you can substitute a drive for the folder path, which strips away the special directory properties.

  1. Launch a Command Prompt at your account's privilege level.
  2. Type SUBST Z: C:\Windows\assembly
    • Z can be any free drive letter.
  3. Open My Computer and look in the new substitute directory.
  4. To remove the virtual drive from Command Prompt, type SUBST Z: /D

As for why you'd want to do something like this, I've used this trick to compare GAC'd DLLs between different machines to make sure they're truly the same.

Best way to check that element is not present using Selenium WebDriver with java

Unable to comment to The Meteor Test Manual, since I have no rep, but I wanted to provide an example that took me quite awhile to figure out:

Assert.assertEquals(0, wd.findElements(By.locator("locator")).size());

This assertion verifies that there are no matching elements in the DOM and returns the value of Zero, so the assertion passes when the element is not present. Also it would fail if it was present.

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

This works for me:

File file = ...;
byte[] data = new byte[(int) file.length()];
try {
    new FileInputStream(file).read(data);
} catch (Exception e) {

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.

Online tutorials


Character Classes

Escape Sequences


(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")





Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

Downloading a large file using curl

You can use this function, which creates a tempfile in the filesystem and returns the path to the downloaded file if everything worked fine:

function getFileContents($url)
    // Workaround: Save temp file
    $img = tempnam(sys_get_temp_dir(), 'pdf-');
    $img .= '.' . pathinfo($url, PATHINFO_EXTENSION);

    $fp = fopen($img, 'w+');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    $result = curl_exec($ch);


    return $result ? $img : false;

UICollectionView auto scroll to cell at IndexPath

I've found that scrolling in viewWillAppear may not work reliably because the collection view hasn't finished it's layout yet; you may scroll to the wrong item.

I've also found that scrolling in viewDidAppear will cause a momentary flash of the unscrolled view to be visible.

And, if you scroll every time through viewDidLayoutSubviews, the user won't be able to manually scroll because some collection layouts cause subview layout every time you scroll.

Here's what I found works reliably:

Objective C :

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    // If we haven't done the initial scroll, do it once.
    if (!self.initialScrollDone) {
        self.initialScrollDone = YES;

        [self.collectionView scrollToItemAtIndexPath:self.myInitialIndexPath
                                    atScrollPosition:UICollectionViewScrollPositionRight animated:NO];

Swift :

 override func viewWillLayoutSubviews() {


      if (!self.initialScrollDone) {

         self.initialScrollDone = true
         self.testNameCollectionView.scrollToItem(at:selectedIndexPath, at: .centeredHorizontally, animated: true)


How to call a RESTful web service from Android?

This is an sample restclient class

public class RestClient
    public enum RequestMethod
    public int responseCode=0;
    public String message;
    public String response;
    public void Execute(RequestMethod method,String url,ArrayList<NameValuePair> headers,ArrayList<NameValuePair> params) throws Exception
        switch (method)
            case GET:
                // add parameters
                String combinedParams = "";
                if (params!=null)
                    combinedParams += "?";
                    for (NameValuePair p : params)
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if (combinedParams.length() > 1)
                            combinedParams += "&" + paramString;
                            combinedParams += paramString;
                HttpGet request = new HttpGet(url + combinedParams);
                // add headers
                if (headers!=null)
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                executeRequest(request, url);
            case POST:
                HttpPost request = new HttpPost(url);
                // add headers
                if (headers!=null)
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                if (params!=null)
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                executeRequest(request, url);
    private ArrayList<NameValuePair> addCommonHeaderField(ArrayList<NameValuePair> _header)
        _header.add(new BasicNameValuePair("Content-Type","application/x-www-form-urlencoded"));
        return _header;
    private void executeRequest(HttpUriRequest request, String url)
        HttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse;
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();
            HttpEntity entity = httpResponse.getEntity();

            if (entity != null)
                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);
        catch (Exception e)
        { }

    private static String convertStreamToString(InputStream is)
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");
        catch (IOException e)
        { }
        return sb.toString();

How to use If Statement in Where Clause in SQL?

You have to use CASE Statement/Expression

Select * from Customer
WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
    (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
     CASE @Value
         WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL) 
         WHEN 3 THEN (CASE WHEN I.RecurringCharge like 
                               '%'+cast(@Total as varchar(50))+'%' 
                     or @Total is NULL )

How to retry after exception?

Do a while True inside your for loop, put your try code inside, and break from that while loop only when your code succeeds.

for i in range(0,100):
    while True:
            # do stuff
        except SomeSpecificException:

Difference between malloc and calloc?

The calloc() function that is declared in the <stdlib.h> header offers a couple of advantages over the malloc() function.

  1. It allocates memory as a number of elements of a given size, and
  2. It initializes the memory that is allocated so that all bits are zero.

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:


If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):

foo = Foo()
bar = 'Hello World!'

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Use a LIKE statement on SQL Server XML Datatype

You should be able to do this quite easily:

FROM WebPageContent 
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'

The .value method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.

Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:

  • create a stored function which gets the XML and returns the value you're looking for as a VARCHAR()
  • define a new computed field on your table which calls this function, and make it a PERSISTED column

With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).


Making a POST call instead of GET using urllib2

Have a read of the urllib Missing Manual. Pulled from there is the following simple example of a POST request.

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age'  : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)

As suggested by @Michael Kent do consider requests, it's great.

EDIT: This said, I do not know why passing data to urlopen() does not result in a POST request; It should. I suspect your server is redirecting, or misbehaving.

.htaccess not working apache

In WampServer Open WampServer Tray icon ----> Apache ---> Apache Modules --->rewrite_module

What's the difference between implementation and compile in Gradle?

Brief Solution:

The better approach is to replace all compile dependencies with implementation dependencies. And only where you leak a module’s interface, you should use api. That should cause a lot less recompilation.

 dependencies {
         implementation fileTree(dir: 'libs', include: ['*.jar'])
         implementation ''
         implementation ''
         // …
         testImplementation 'junit:junit:4.12'
         androidTestImplementation('', {
             exclude group: '', module: 'support-annotations'

Explain More:

Before Android Gradle plugin 3.0: we had a big problem which is one code change causes all modules to be recompiled. The root cause for this is that Gradle doesn’t know if you leak the interface of a module through another one or not.

After Android Gradle plugin 3.0: the latest Android Gradle plugin now requires you to explicitly define if you leak a module’s interface. Based on that it can make the right choice on what it should recompile.

As such the compile dependency has been deprecated and replaced by two new ones:

  • api: you leak the interface of this module through your own interface, meaning exactly the same as the old compile dependency

  • implementation: you only use this module internally and does not leak it through your interface

So now you can explicitly tell Gradle to recompile a module if the interface of a used module changes or not.

Courtesy of Jeroen Mols blog

MySQL Delete all rows from table and reset ID to zero

If table has foreign keys then I always use following code:

SET FOREIGN_KEY_CHECKS = 0; -- disable a foreign keys check
SET AUTOCOMMIT = 0; -- disable autocommit
START TRANSACTION; -- begin transaction

DELETE FROM table_name;
-- or
TRUNCATE table_name;
-- or
DROP TABLE table_name;
CREATE TABLE table_name ( ... );

SET FOREIGN_KEY_CHECKS = 1; -- enable a foreign keys check
COMMIT;  -- make a commit

But difference will be in execution time. Look at above Sorin's answer.

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

The list returned by Arrays.asList() might be immutable. Could you try

List<String> list = new ArrayList(Arrays.asList(split));

Help needed with Median If in Excel

one solution could be to find a way of pulling the numbers from the string and placing them in a column of just numbers the using the =MEDIAN() function giving the new number column as the range

How do I determine k when using k-means clustering?

You can choose the number of clusters by visually inspecting your data points, but you will soon realize that there is a lot of ambiguity in this process for all except the simplest data sets. This is not always bad, because you are doing unsupervised learning and there's some inherent subjectivity in the labeling process. Here, having previous experience with that particular problem or something similar will help you choose the right value.

If you want some hint about the number of clusters that you should use, you can apply the Elbow method:

First of all, compute the sum of squared error (SSE) for some values of k (for example 2, 4, 6, 8, etc.). The SSE is defined as the sum of the squared distance between each member of the cluster and its centroid. Mathematically:


If you plot k against the SSE, you will see that the error decreases as k gets larger; this is because when the number of clusters increases, they should be smaller, so distortion is also smaller. The idea of the elbow method is to choose the k at which the SSE decreases abruptly. This produces an "elbow effect" in the graph, as you can see in the following picture:

enter image description here

In this case, k=6 is the value that the Elbow method has selected. Take into account that the Elbow method is an heuristic and, as such, it may or may not work well in your particular case. Sometimes, there are more than one elbow, or no elbow at all. In those situations you usually end up calculating the best k by evaluating how well k-means performs in the context of the particular clustering problem you are trying to solve.

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.

If you add / before /n, it should work, you need to escape new line character.

"Hello there //n start coding"

The result should be as following

Hello there
start coding

How do I revert all local changes in Git managed project to previous state?


GIT=$(git rev-parse --show-toplevel)
cd $GIT/..
rm -rf $GIT
git clone ...
  • ? Deletes local, non-pushed commits
  • ? Reverts changes you made to tracked files
  • ? Restores tracked files you deleted
  • ? Deletes files/dirs listed in .gitignore (like build files)
  • ? Deletes files/dirs that are not tracked and not in .gitignore
  • You won't forget this approach
  • Wastes bandwidth

Following are other commands I forget daily.

Clean and reset

git clean --force -d -x
git reset --hard
  • ? Deletes local, non-pushed commits
  • ? Reverts changes you made to tracked files
  • ? Restores tracked files you deleted
  • ? Deletes files/dirs listed in .gitignore (like build files)
  • ? Deletes files/dirs that are not tracked and not in .gitignore


git clean --force -d -x
  • ? Deletes local, non-pushed commits
  • ? Reverts changes you made to tracked files
  • ? Restores tracked files you deleted
  • ? Deletes files/dirs listed in .gitignore (like build files)
  • ? Deletes files/dirs that are not tracked and not in .gitignore


git reset --hard
  • ? Deletes local, non-pushed commits
  • ? Reverts changes you made to tracked files
  • ? Restores tracked files you deleted
  • ? Deletes files/dirs listed in .gitignore (like build files)
  • ? Deletes files/dirs that are not tracked and not in .gitignore


Test case for confirming all the above (use bash or sh):

mkdir project
cd project
git init
echo '*.built' > .gitignore
echo 'CODE' > a.sourceCode
mkdir b
echo 'CODE' > b/b.sourceCode
cp -r b c
git add .
git commit -m 'Initial checkin'
echo 'NEW FEATURE' >> a.sourceCode
cp a.sourceCode a.built
rm -rf c
echo 'CODE' > 'd.sourceCode'

See also

  • git revert to make new commits that undo prior commits
  • git checkout to go back in time to prior commits (may require running above commands first)
  • git stash same as git reset above, but you can undo it

Reading a UTF8 CSV file with Python

Using as Alex Martelli suggested proved to be useful to me.

import codecs

delimiter = ';'
reader ="your_filename.csv", 'r', encoding='utf-8')
for line in reader:
    row = line.split(delimiter)
    # do something with your row ...

ADB Driver and Windows 8.1

The most complete answer I have found is here:

I'm copying the complete answer below.

Installing Android ADB driver in Windows 8.1 64-bit when all else fails

For some reason I just couldn't get my machine to recognize Xperia J in Windows 8.1 64-bit. Even after installing latest Sony PC Companion (2.10.174). Device Manager kept showing yellow exclamation mark to an 'Android'.

Here's the solution, but I don't promise it will work on your device!

1. Find out your device's VID and PID

Open Device Manager, right-click that Android with yellow exclamation mark and click Properties. Go to Details tab. In Property, select Hardware Ids. Right-click the value and click Copy. Paste the value somewhere.

2. Download Android USB Driver

Run Android SDK Manager. Expand Extras, tick Google USB Driver, click Install packages. After installation, look for the driver location by hovering mouse over Google USB Driver. The location will appear in the tooltip.

3. Modify android_winusb.inf

Go to the usb driver location, for example in the above picture it is c:\Android\android-studio\sdk\extras\google\usb_driver Make a backup copy of android_winusb.inf Open android_winusb.inf with a text editor. Notepad is fine but Notepad++ is better, it will syntax highlight the inf file! Look for [Google.NTx86], and insert a line with your device's hardware ID that you copied above, for example


; ... other existing lines

;SONY Sony Xperia J
%CompositeAdbInterface% = USB_Install, USB\VID_0FCE&PID_6188&MI_01

Look for [Google.NTamd86], and insert the same lines, for example:


; ... other existing lines

;SONY Sony Xperia J
%CompositeAdbInterface% = USB_Install, USB\VID_0FCE&PID_6188&MI_01

Save the file.

4. Disable driver signing

Run Command Prompt as an administrator Paste and run the following commands:

bcdedit -set loadoptions DISABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING ON

Restart Windows.

5. Install driver

Open Device Manager, right-click that Android with yellow exclamation mark and click Update Driver Software. Click Browse my computer for driver software. Enter or browse to the folder containing android_winusb.inf, eg: C:\Android\android-studio\sdk\extras\google\usb_driver Click Next. The driver will install. Run adb devices to confirm your device is working fine.

6. Re-enable driver signing

Run Command Prompt as an administrator Paste and run the following commands:

bcdedit -set loadoptions ENABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING OFF

Restart Windows. Run adb devices to reconfirm!

How does strcmp() work?

Here is my version, written for small microcontroller applications, MISRA-C compliant. The main aim with this code was to write readable code, instead of the one-line goo found in most compiler libs.

int8_t strcmp (const uint8_t* s1, const uint8_t* s2)
  while ( (*s1 != '\0') && (*s1 == *s2) )

  return (int8_t)( (int16_t)*s1 - (int16_t)*s2 );

Note: the code assumes 16 bit int type.

How to Reload ReCaptcha using JavaScript?

if you are using new recaptcha 2.0 use this: for code behind:

ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "$.getScript(\"\", function () {});", true);

for simple javascript

<script>$.getScript(\"\", function () {});</script>

Redirect Windows cmd stdout and stderr to a single file

Background info from MSKB

While the accepted answer to this question is correct, it really doesn't do much to explain why it works, and since the syntax is not immediately clear I did a quick google to find out what was actually going on. In the hopes that this information is helpful to others, I'm posting it here.

Taken from MS Support KB 110930.

From MSKB110930

Redirecting Error Messages from Command Prompt: STDERR/STDOUT


When redirecting output from an application using the '>' symbol, error messages still print to the screen. This is because error messages are often sent to the Standard Error stream instead of the Standard Out stream.

Output from a console (Command Prompt) application or command is often sent to two separate streams. The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the ">" symbol, you are only redirecting STDOUT. In order to redirect STDERR you have to specify '2>' for the redirection symbol. This selects the second output stream which is STDERR.


The command dir (where does not exist) will display the following output:

Volume in drive F is Candy Cane Volume Serial Number is 34EC-0876

File Not Found

If you redirect the output to the NUL device using dir > nul, you will still see the error message part of the output, like this:

File Not Found

To redirect (only) the error message to NUL, use the following command:

dir 2> nul

Or, you can redirect the output to one place, and the errors to another.

dir > output.msg 2> output.err

You can print the errors and standard output to a single file by using the "&1" command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:

dir 1> output.msg 2>&1

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,


could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                        return Boolean.class;
        JScrollPane scrollPane = new JScrollPane(table);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setLocation(150, 150);

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

Adding CSRFToken to Ajax request

This worked for me (using jQuery 2.1)

$(document).ajaxSend(function(elm, xhr, s){
    if (s.type == "POST") { +="&":""; += "_token=" + $('#csrf-token').val();

or this:

$(document).ajaxSend(function(elm, xhr, s){
    if (s.type == "POST") {
        xhr.setRequestHeader('x-csrf-token', $('#csrf-token').val());

(where #csrf-token is the element containing the token)

Difference between jQuery’s .hide() and setting CSS to display: none

See there is no difference if you use basic hide method. But jquery provides various hide method which give effects to the element. Refer below link for detailed explanation: Effects for Hide in Jquery

jQuery UI accordion that keeps multiple sections open?

Pretty simple:

<script type="text/javascript">
    (function($) {
        $(function() {
            $("#accordion > div").accordion({ header: "h3", collapsible: true });

<div id="accordion">
        <h3><a href="#">First</a></h3>
        <div>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</div>
        <h3><a href="#">Second</a></h3>
        <div>Phasellus mattis tincidunt nibh.</div>
        <h3><a href="#">Third</a></h3>
        <div>Nam dui erat, auctor a, dignissim quis.</div>

How to run python script with elevated privilege on windows

  1. make a batch file
  2. add python.exe "(your py file here)" with the quotation marks
  3. save the batch file
  4. right click, then click run as administrator

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

2 column div layout: right column with fixed width, left fluid

See , this is exactly what you need (example 4 there).

<div id="container">
    <div id="content">
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.  Phasellus varius eleifend tellus. Suspendisse potenti. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Nulla facilisi. Sed wisi lectus, placerat nec, mollis quis, posuere eget, arcu.</p>
        <p class="last">Donec euismod. Praesent mauris mi, adipiscing non, mollis eget, adipiscing ac, erat. Integer nonummy mauris sit amet metus. In adipiscing, ligula ultrices dictum vehicula, eros turpis lacinia libero, sed aliquet urna diam sed tellus. Etiam semper sapien eget metus.</p>

<div id="sidebar">
        <li>link one</li>
        <li>link two</li>

#container {
    width: 100%;
    background: #f1f2ea url(background.gif) repeat-y right;
    float: left;
    margin-right: -200px;
#content {
    background: #f1f2ea;
    margin-right: 200px;
#sidebar {
    width: 200px;
    float: right;

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

Add elements in first arraylist

ArrayList<String> firstArrayList = new ArrayList<String>();


Add elements in second arraylist

ArrayList<String> secondArrayList = new ArrayList<String>();


Add first arraylist's elements in second arraylist


Assign new combine arraylist and add all elements from both arraylists

ArrayList<String> comboArrayList = new ArrayList<String>(firstArrayList);

Assign new Set for remove duplicate entries from arraylist

Set<String> setList = new LinkedHashSet<String>(comboArrayList);

Sorting arraylist




Keras model.summary() result - Understanding the # of Parameters

Number of parameters is the amount of numbers that can be changed in the model. Mathematically this means number of dimensions of your optimization problem. For you as a programmer, each of this parameters is a floating point number, which typically takes 4 bytes of memory, allowing you to predict the size of this model once saved.

This formula for this number is different for each neural network layer type, but for Dense layer it is simple: each neuron has one bias parameter and one weight per input: N = n_neurons * ( n_inputs + 1).