Programs & Examples On #Crt

For issues relating to utilizing the C runtime library.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

This error is usually caused by the missing Visual C++ Redistributable file, which is a required dependency for most of the application on Windows Computer.

Download Visual C++ Redistributable from here and install it. After installing this, Reboot the system.

Link: Visual C++ Redistributable

How to convert .crt to .pem

You can do this conversion with the OpenSSL library

http://www.openssl.org/

Windows binaries can be found here:

http://www.slproweb.com/products/Win32OpenSSL.html

Once you have the library installed, the command you need to issue is:

openssl x509 -in mycert.crt -out mycert.pem -outform PEM

How to compress an image via Javascript in the browser?

I had an issue with the downscaleImage() function posted above by @daniel-allen-langdon in that the image.width and image.height properties are not available immediately because the image load is asynchronous.

Please see updated TypeScript example below that takes this into account, uses async functions, and resizes the image based on the longest dimension rather than just the width

function getImage(dataUrl: string): Promise<HTMLImageElement> 
{
    return new Promise((resolve, reject) => {
        const image = new Image();
        image.src = dataUrl;
        image.onload = () => {
            resolve(image);
        };
        image.onerror = (el: any, err: ErrorEvent) => {
            reject(err.error);
        };
    });
}

export async function downscaleImage(
        dataUrl: string,  
        imageType: string,  // e.g. 'image/jpeg'
        resolution: number,  // max width/height in pixels
        quality: number   // e.g. 0.9 = 90% quality
    ): Promise<string> {

    // Create a temporary image so that we can compute the height of the image.
    const image = await getImage(dataUrl);
    const oldWidth = image.naturalWidth;
    const oldHeight = image.naturalHeight;
    console.log('dims', oldWidth, oldHeight);

    const longestDimension = oldWidth > oldHeight ? 'width' : 'height';
    const currentRes = longestDimension == 'width' ? oldWidth : oldHeight;
    console.log('longest dim', longestDimension, currentRes);

    if (currentRes > resolution) {
        console.log('need to resize...');

        // Calculate new dimensions
        const newSize = longestDimension == 'width'
            ? Math.floor(oldHeight / oldWidth * resolution)
            : Math.floor(oldWidth / oldHeight * resolution);
        const newWidth = longestDimension == 'width' ? resolution : newSize;
        const newHeight = longestDimension == 'height' ? resolution : newSize;
        console.log('new width / height', newWidth, newHeight);

        // Create a temporary canvas to draw the downscaled image on.
        const canvas = document.createElement('canvas');
        canvas.width = newWidth;
        canvas.height = newHeight;

        // Draw the downscaled image on the canvas and return the new data URL.
        const ctx = canvas.getContext('2d')!;
        ctx.drawImage(image, 0, 0, newWidth, newHeight);
        const newDataUrl = canvas.toDataURL(imageType, quality);
        return newDataUrl;
    }
    else {
        return dataUrl;
    }

}

ValueError: could not convert string to float: id

This error is pretty verbose:

ValueError: could not convert string to float: id

Somewhere in your text file, a line has the word id in it, which can't really be converted to a number.

Your test code works because the word id isn't present in line 2.


If you want to catch that line, try this code. I cleaned your code up a tad:

#!/usr/bin/python

import os, sys
from scipy import stats
import numpy as np

for index, line in enumerate(open('data2.txt', 'r').readlines()):
    w = line.split(' ')
    l1 = w[1:8]
    l2 = w[8:15]

    try:
        list1 = map(float, l1)
        list2 = map(float, l2)
    except ValueError:
        print 'Line {i} is corrupt!'.format(i = index)'
        break

    result = stats.ttest_ind(list1, list2)
    print result[1]

Anaconda / Python: Change Anaconda Prompt User Path

Just Type the Drive Location you want to work with: This worked for me! For example you want to change to D drive in windows:

D:\

If you want to change to particular folder in the drive:

cd D:\Newfolder

Unable to execute dex: Multiple dex files define

I had same problem. I had to delete the .apk file and then it worked.

How to use the start command in a batch file?

I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?

Basically, you use the /B and /C options:

START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1

ERROR: Sonar server 'http://localhost:9000' can not be reached

If you use SonarScanner CLI with Docker, you may have this error because the SonarScanner container can not access to the Sonar UI container.

Note that you will have the same error with a simple curl from another container:

docker run --rm byrnedo/alpine-curl 127.0.0.1:9000
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused

The solution is to connect the SonarScanner container to the same docker network of your sonar instance, for instance with --network=host:

docker run --network=host -e SONAR_HOST_URL='http://127.0.0.1:9000' --user="$(id -u):$(id -g)" -v "$PWD:/usr/src" sonarsource/sonar-scanner-cli

(other parameters of this command comes from the SonarScanner CLI documentation)

Truncate number to two decimal places without rounding

I opted to write this instead to manually remove the remainder with strings so I don't have to deal with the math issues that come with numbers:

num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf("."))+3); //With 3 exposing the hundredths place
Number(num); //If you need it back as a Number

This will give you "15.77" with num = 15.7784514;

Java Spring - How to use classpath to specify a file location?

From an answer of @NimChimpsky in similar question:

Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();

Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/ into the classpath).

Note that Resource have a method to get a java.io.File so you can also use:

Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());

How to list the properties of a JavaScript object?

The solution work on my cases and cross-browser:

var getKeys = function(obj) {
    var type = typeof  obj;
    var isObjectType = type === 'function' || type === 'object' || !!obj;

    // 1
    if(isObjectType) {
        return Object.keys(obj);
    }

    // 2
    var keys = [];
    for(var i in obj) {
        if(obj.hasOwnProperty(i)) {
            keys.push(i)
        }
    }
    if(keys.length) {
        return keys;
    }

    // 3 - bug for ie9 <
    var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');
    if(hasEnumbug) {
        var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
            'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

        var nonEnumIdx = nonEnumerableProps.length;

        while (nonEnumIdx--) {
            var prop = nonEnumerableProps[nonEnumIdx];
            if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                keys.push(prop);
            }
        }

    }

    return keys;
};

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

You're almost there. Simply use:

//form[@id='myform']//input[@type='submit']

The // shortcut can also be used inside an expression.

Counting the number of non-NaN elements in a numpy ndarray in Python

Quick-to-write alterantive

Even though is not the fastest choice, if performance is not an issue you can use:

sum(~np.isnan(data)).

Performance:

In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop

In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop

In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop

How to truncate milliseconds off of a .NET DateTime

Less obvious but more than 2 times faster :

// 10000000 runs

DateTime d = DateTime.Now;

// 484,375ms
d = new DateTime((d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);

// 1296,875ms
d = d.AddMilliseconds(-d.Millisecond);

Shortest distance between a point and a line segment

the accepted answer does not work (e.g. distance between 0,0 and (-10,2,10,2) should be 2).

here's code that works:

   def dist2line2(x,y,line):
     x1,y1,x2,y2=line
     vx = x1 - x
     vy = y1 - y
     ux = x2-x1
     uy = y2-y1
     length = ux * ux + uy * uy
     det = (-vx * ux) + (-vy * uy) #//if this is < 0 or > length then its outside the line segment
     if det < 0:
       return (x1 - x)**2 + (y1 - y)**2
     if det > length:
       return (x2 - x)**2 + (y2 - y)**2
     det = ux * vy - uy * vx
     return det**2 / length
   def dist2line(x,y,line): return math.sqrt(dist2line2(x,y,line))

Android, How to create option Menu

Replace return super.onCreateOptionsMenu(menu); with return true; in your onCreateOptionsMenu method This will help

And you should also have the onCreate method in your activity

"SMTP Error: Could not authenticate" in PHPMailer

It was the selinux issue. I just updated the below given part in /etc/selinux/config file SELINUX=permissive (it was SELINUX=enforcing before). then just reboot the system by giving reboot Now the mail goes without any hassle. Configuration

From Email Address : [[email protected]]
From Name : [your domain name]
SMTP Host   : smtp.gmail.com
Type of Encryption : SSL
SMTP Port : 465
SMTP Authentication  : YES
Username : [your mail id]
Password : [your password]

How to write an XPath query to match two attributes?

Sample XML:

<X>
<Y ATTRIB1=attrib1_value ATTRIB2=attrib2_value/>
</X>

string xPath="/" + X + "/" + Y +
"[@" + ATTRIB1 + "='" + attrib1_value + "']" +
"[@" + ATTRIB2 + "='" + attrib2_value + "']"

XPath Testbed: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

Using wire or reg with input or output in Verilog

The Verilog code compiler you use will dictate what you have to do. If you use illegal syntax, you will get a compile error.

An output must also be declared as a reg only if it is assigned using a "procedural assignment". For example:

output reg a;
always @* a = b;

There is no need to declare an output as a wire.

There is no need to declare an input as a wire or reg.

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

How to sum up an array of integers in C#

Using foreach would be shorter code, but probably do exactly the same steps at runtime after JIT optimization recognizes the comparison to Length in the for-loop controlling expression.

How do I get the total number of unique pairs of a set in the database?

I was solving this algorithm and get stuck with the pairs part.

This explanation help me a lot https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/

So to calculate the sum of series of numbers:

n(n+1)/2

But you need to calculate this

1 + 2 + ... + (n-1)

So in order to get this you can use

n(n+1)/2 - n

that is equal to

n(n-1)/2

Launch an app from within another (iPhone)

In Swift 4.1 and Xcode 9.4.1

I have two apps 1)PageViewControllerExample and 2)DelegateExample. Now i want to open DelegateExample app with PageViewControllerExample app. When i click open button in PageViewControllerExample, DelegateExample app will be opened.

For this we need to make some changes in .plist files for both the apps.

Step 1

In DelegateExample app open .plist file and add URL Types and URL Schemes. Here we need to add our required name like "myapp".

enter image description here

Step 2

In PageViewControllerExample app open .plist file and add this code

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>myapp</string>
</array>

Now we can open DelegateExample app when we click button in PageViewControllerExample.

//In PageViewControllerExample create IBAction
@IBAction func openapp(_ sender: UIButton) {

    let customURL = URL(string: "myapp://")
    if UIApplication.shared.canOpenURL(customURL!) {

        //let systemVersion = UIDevice.current.systemVersion//Get OS version
        //if Double(systemVersion)! >= 10.0 {//10 or above versions
            //print(systemVersion)
            //UIApplication.shared.open(customURL!, options: [:], completionHandler: nil)
        //} else {
            //UIApplication.shared.openURL(customURL!)
        //}

        //OR

        if #available(iOS 10.0, *) {
            UIApplication.shared.open(customURL!, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(customURL!)
        }
    } else {
         //Print alert here
    }
}

Can I use Homebrew on Ubuntu?

as of august 2020 (works for kali linux as well)

sh -c "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/install/master/install.sh)"

export brew=/home/linuxbrew/.linuxbrew/bin

test -d ~/.linuxbrew && eval $(~/.linuxbrew/bin/brew shellenv)

test -d /home/linuxbrew/.linuxbrew && eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)

test -r ~/.profile && echo "eval \$($(brew --prefix)/bin/brew shellenv)" >>~/.profile     // for ubuntu and debian

Unity 2d jumping script

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

Using putty to scp from windows to Linux

You can use PSCP to copy files from Windows to Linux.

  1. Download PSCP from putty.org
  2. Open cmd in the directory with pscp.exe file
  3. Type command pscp source_file user@host:destination_file

Reference

How do I import an existing Java keystore (.jks) file into a Java installation?

You can bulk import all aliases from one keystore to another:

keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks

Detecting iOS / Android Operating system

One can use navigator.platform to get the operating system on which browser is installed.

function getPlatform() {
   var platform = ["Win32", "Android", "iOS"];

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

       if (navigator.platform.indexOf(platform[i]) >- 1) {

           return platform[i];
       }
   }
}

getPlatform();

Calculating how many days are between two dates in DB2?

It seems like one closing brace is missing at ,right(a2.chdlm,2)))) from sysibm.sysdummy1 a1,

So your Query will be

select days(current date) - days(date(select concat(concat(concat(concat(left(a2.chdlm,4),'-'),substr(a2.chdlm,4,2)),'-'),right(a2.chdlm,2)))) from sysibm.sysdummy1 a1, chcart00 a2 where chstat = '05';

php codeigniter count rows

Use this code:

$this->db->where(['id'=>2])->from("table name")->count_all_results();

or

$this->db->from("table name")->count_all_results();

Multiple Java versions running concurrently under Windows

It should be possible changing setting the JAVA_HOME environment variable differently for specific applications.

When starting from the command line or from a batch script you can use set JAVA_HOME=C:\...\j2dskXXX to change the JAVA_HOME environment.

It is possible that you also need to change the PATH environment variable to use the correct java binary. To do this you can use set PATH=%JAVA_HOME%\bin;%PATH%.

Can I simultaneously declare and assign a variable in VBA?

In some cases the whole need for declaring a variable can be avoided by using With statement.

For example,

    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogSaveAs)
    If fd.Show Then
        'use fd.SelectedItems(1)
    End If

this can be rewritten as

    With Application.FileDialog(msoFileDialogSaveAs)
      If .Show Then
        'use .SelectedItems(1)
      End If
    End With

Reverse order of foreach list items

You can use usort function to create own sorting rules

PHP Configuration: It is not safe to rely on the system's timezone settings

Please modify your index.php as follows:

require_once($yii);
$app = Yii::createWebApplication($config);
Yii::app()->setTimeZone('UTC');
$app->run();

What does the PHP error message "Notice: Use of undefined constant" mean?

You should quote your array keys:

$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']);

As is, it was looking for constants called department, name, email, message, etc. When it doesn't find such a constant, PHP (bizarrely) interprets it as a string ('department', etc). Obviously, this can easily break if you do defined such a constant later (though it's bad style to have lower-case constants).

Constructors in Go

There are some equivalents of constructors for when the zero values can't make sensible default values or for when some parameter is necessary for the struct initialization.

Supposing you have a struct like this :

type Thing struct {
    Name  string
    Num   int
}

then, if the zero values aren't fitting, you would typically construct an instance with a NewThing function returning a pointer :

func NewThing(someParameter string) *Thing {
    p := new(Thing)
    p.Name = someParameter
    p.Num = 33 // <- a very sensible default value
    return p
}

When your struct is simple enough, you can use this condensed construct :

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33}
}

If you don't want to return a pointer, then a practice is to call the function makeThing instead of NewThing :

func makeThing(name string) Thing {
    return Thing{name, 33}
}

Reference : Allocation with new in Effective Go.

SQL-Server: The backup set holds a backup of a database other than the existing

Before doing anything else, confirm if your backup is Full or Differential. If you're trying to create a new database out of a differential backup, no matter what you do you will encounter the error.

How to encrypt and decrypt file in Android?

Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.

I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.

Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.

If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.

Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes() but use String.getBytes(StandardCharsets.UTF_8).

To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.

Be warned that CipherInputStream may not report BadPaddingException, this includes BadPaddingException generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.

Why does Firebug say toFixed() is not a function?

That is because Low is a string.

.toFixed() only works with a number.


Try doing:

Low = parseFloat(Low).toFixed(..);

How do I add a newline to a TextView in Android?

If you debug, you will see that the string is actually "\ \r\ \n" or "\ \n", ie, it is escaped. So if you massage that string, to get rid of the extra \, you will have your solution. This is true especially if you are reading from a database.

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

You can also change the index name in column definitions within a create_table block (such as you get from the migration generator).

create_table :studies do |t|
  t.references :user, index: {:name => "index_my_shorter_name"}
end

How to write an ArrayList of Strings into a text file?

If you want to serialize the ArrayList object to a file so you can read it back in again later use ObjectOuputStream/ObjectInputStream writeObject()/readObject() since ArrayList implements Serializable. It's not clear to me from your question if you want to do this or just write each individual item. If so then Andrey's answer will do that.

Case insensitive 'in'

To have it in one line, this is what I did:

if any(([True if 'MICHAEL89' in username.upper() else False for username in USERNAMES])):
    print('username exists in list')

I didn't test it time-wise though. I am not sure how fast/efficient it is.

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

How do I obtain the frequencies of each value in an FFT?

I have used the following:

public static double Index2Freq(int i, double samples, int nFFT) {
  return (double) i * (samples / nFFT / 2.);
}

public static int Freq2Index(double freq, double samples, int nFFT) {
  return (int) (freq / (samples / nFFT / 2.0));
}

The inputs are:

  • i: Bin to access
  • samples: Sampling rate in Hertz (i.e. 8000 Hz, 44100Hz, etc.)
  • nFFT: Size of the FFT vector

MySQL: Fastest way to count number of rows

I handled tables for the German Government with sometimes 60 million records.

And we needed to know many times the total rows.

So we database programmers decided that in every table is record one always the record in which the total record numbers is stored. We updated this number, depending on INSERT or DELETE rows.

We tried all other ways. This is by far the fastest way.

How to position the form in the center screen?

Change this:

public FrameForm() { 
    initComponents(); 
}

to this:

public FrameForm() {
    initComponents();
    this.setLocationRelativeTo(null);
}

how to set width for PdfPCell in ItextSharp

try this code I think it is more optimal.

HeaderRow is used to repeat the header of the table for each new page automatically

        BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
        iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

        PdfPTable table = new PdfPTable(10) { HorizontalAlignment = Element.ALIGN_CENTER, WidthPercentage = 100, HeaderRows = 2 };
        table.SetWidths(new float[] { 2f, 6f, 6f, 3f, 5f, 8f, 5f, 5f, 5f, 5f });
        table.AddCell(new PdfPCell(new Phrase("SER.\nNO.", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("TYPE OF SHIPPING", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("ORDER NO.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("QTY.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DISCHARGE PPORT", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DESCRIPTION OF GOODS", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("LINE DOC. RECL DATE", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("CLEARANCE DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("CUSTOM PERMIT NO.", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DISPATCH DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("AWB/BL NO.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("COMPLEX NAME", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("G. W. Kgs.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DESTINATION", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("OWNER DOC. RECL DATE", times)) { GrayFill = 0.95f });

How to create a popup windows in javafx

Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.

ImportError: No module named 'encodings'

I was facing the same problem under Windows7. The error message looks like that:

Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x000011f4 (most recent call first):

I have installed python 2.7(uninstalled now), and I checked "Add Python to environment variables in Advanced Options" while installing python 3.6. It comes out that the Environment Variable "PYTHONHOME" and "PYTHONPATH" is still python2.7.

Finally I solved it by modify "PYTHONHOME" to python3.6 install path and remove variable "PYTHONPATH".

java.lang.RuntimeException: Uncompilable source code - what can cause this?

Just check the packaging, the simplest answer I can provide is that your package has been mislabeled (within a class).

Also, you may have some weird characters. Try white-flushing the code in a Notepad (or Gedit) and then pasting it into a newly created class with your IDE.

Is there a way to make Firefox ignore invalid ssl-certificates?

Try Add Exception: FireFox -> Tools -> Advanced -> View Certificates -> Servers -> Add Exception.

Reading a huge .csv file

what worked for me was and is superfast is

import pandas as pd
import dask.dataframe as dd
import time
t=time.clock()
df_train = dd.read_csv('../data/train.csv', usecols=[col1, col2])
df_train=df_train.compute()
print("load train: " , time.clock()-t)

Another working solution is:

import pandas as pd 
from tqdm import tqdm

PATH = '../data/train.csv'
chunksize = 500000 
traintypes = {
'col1':'category',
'col2':'str'}

cols = list(traintypes.keys())

df_list = [] # list to hold the batch dataframe

for df_chunk in tqdm(pd.read_csv(PATH, usecols=cols, dtype=traintypes, chunksize=chunksize)):
    # Can process each chunk of dataframe here
    # clean_data(), feature_engineer(),fit()

    # Alternatively, append the chunk to list and merge all
    df_list.append(df_chunk) 

# Merge all dataframes into one dataframe
X = pd.concat(df_list)

# Delete the dataframe list to release memory
del df_list
del df_chunk

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

Adding items to end of linked list

The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.

public class LinkedList {
    Node head;

    public static class Node{
        int data;
        Node next;

        Node(int item){
            data = item;
            next = null;
        }
    }
    public static void main(String args[]){
        LinkedList ll = new LinkedList();
        ll.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(3);
        Node fourth = new Node(4);

        ll.head.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = null;

        ll.printList();
        System.out.println("Add element 100 to the last");
        ll.addLast(100);
        ll.printList();
    }
    public void printList(){
        Node t = head;
        while(n != null){
            System.out.println(t.data);
            t = t.next;
        }

    }

    public void addLast(int item){
        Node new_item = new Node(item);
        if(head == null){
            head = new_item;
            return;
        }
        new_item.next = null;

        Node last = head;
        Node temp = null;
        while(last != null){
            if(last != null)
                temp = last;
            last = last.next;
        }   

        temp.next = new_item;   
        return;
    }
}

Downloading a large file using curl

when curl is used to download a large file then CURLOPT_TIMEOUT is the main option you have to set for.

CURLOPT_RETURNTRANSFER has to be true in case you are getting file like pdf/csv/image etc.

You may find the further detail over here(correct url) Curl Doc

From that page:

curl_setopt($request, CURLOPT_TIMEOUT, 300); //set timeout to 5 mins

curl_setopt($request, CURLOPT_RETURNTRANSFER, true); // true to get the output as string otherwise false

Synchronous Requests in Node.js

You should take a look at library called async

and try to use async.series call for your problem.

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Recently, I explored the possibilities to parameterize the folder to scan through and the place where the result of recursive scan will be stored. At the end, I also did summarize the number of folders scanned and number of files inside as well. Sharing it with community in case it may help other developers.

    ##Script Starts
    #read folder to scan and file location to be placed

    $whichFolder = Read-Host -Prompt 'Which folder to Scan?'  
    $whereToPlaceReport = Read-Host -Prompt 'Where to place Report'
    $totalFolders = 1
    $totalFiles = 0

    Write-Host "Process started..."

    #IMP separator ? : used as a file in window cannot contain this special character in the file name

    #Get Foldernames into Variable for ForEach Loop
    $DFSFolders = get-childitem -path $whichFolder | where-object {$_.Psiscontainer -eq "True"} |select-object name ,fullName

    #Below Logic for Main Folder
    $mainFiles = get-childitem -path "C:\Users\User\Desktop" -file
    ("Folder Path" + "?" + "Folder Name" + "?" + "File Name " + "?"+ "File Length" )| out-file "$whereToPlaceReport\Report.csv" -Append

    #Loop through folders in main Directory
    foreach($file in $mainFiles)
    {

    $totalFiles = $totalFiles + 1
    ("C:\Users\User\Desktop" + "?" + "Main Folder" + "?"+ $file.name + "?" + $file.length ) | out-file "$whereToPlaceReport\Report.csv" -Append
    }


    foreach ($DFSfolder in $DFSfolders)
    {
    #write the folder name in begining
    $totalFolders = $totalFolders + 1

    write-host " Reading folder C:\Users\User\Desktop\$($DFSfolder.name)"
    #$DFSfolder.fullName | out-file "C:\Users\User\Desktop\PoC powershell\ok2.csv" -Append
    #For Each Folder obtain objects in a specified directory, recurse then filter for .sft file type, obtain the filename, then group, sort and eventually show the file name and total incidences of it.

    $files = get-childitem -path "$whichFolder\$($DFSfolder.name)" -recurse

    foreach($file in $files)
    {
    $totalFiles = $totalFiles + 1
    ($DFSfolder.fullName + "?" + $DFSfolder.name + "?"+ $file.name + "?" + $file.length ) | out-file "$whereToPlaceReport\Report.csv" -Append
    }

    }


    # If running in the console, wait for input before closing.
    if ($Host.Name -eq "ConsoleHost")
    {

    Write-Host "" 
    Write-Host ""
    Write-Host ""

    Write-Host  "                            **Summary**"  -ForegroundColor Red
    Write-Host  "                            ------------" -ForegroundColor Red

    Write-Host  "                           Total Folders Scanned = $totalFolders "  -ForegroundColor Green
    Write-Host  "                           Total Files   Scanned = $totalFiles "     -ForegroundColor Green

    Write-Host "" 
    Write-Host "" 
        Write-Host "I have done my Job,Press any key to exit" -ForegroundColor white
        $Host.UI.RawUI.FlushInputBuffer()   # Make sure buffered input doesn't "press a key" and skip the ReadKey().
        $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
    }

##Output

enter image description here

##Bat Code to run above powershell command

@ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";

Remove characters from C# string

Sounds like an ideal application for RegEx -- an engine designed for fast text manipulation. In this case:

Regex.Replace("He\"ll,o Wo'r.ld", "[@,\\.\";'\\\\]", string.Empty)

How to detect if user select cancel InputBox VBA Excel

Following example uses InputBox method to validate user entry to unhide sheets: Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.

Sub unhidesheet()

Dim ws As Worksheet
Dim pw As String

pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then

   Exit Sub
ElseIf pw = NullString Then
   Exit Sub
ElseIf pw = 123456 Then
    For Each ws In ThisWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next
End If
End Sub

@ variables in Ruby on Rails

A tutorial about What is Variable Scope? presents some details quite well, just enclose the related here.


+------------------+----------------------+
| Name Begins With |    Variable Scope    |
+------------------+----------------------+
| $                | A global variable    |
| @                | An instance variable |
| [a-z] or _       | A local variable     |
| [A-Z]            | A constant           |
| @@               | A class variable     |
+------------------+----------------------+

Prevent jQuery UI dialog from setting focus to first textbox

In my opinion this solution is very nice:

$("#dialog").dialog({
    open: function(event, ui) {
        $("input").blur();
    }
});

Found here: unable-to-remove-autofocus-in-ui-dialog

How to automatically generate N "distinct" colors?

This questions appears in quite a few SO discussions:

Different solutions are proposed, but none are optimal. Luckily, science comes to the rescue

Arbitrary N

The last 2 will be free via most university libraries / proxies.

N is finite and relatively small

In this case, one could go for a list solution. A very interesting article in the subject is freely available:

There are several color lists to consider:

  • Boynton's list of 11 colors that are almost never confused (available in the first paper of the previous section)
  • Kelly's 22 colors of maximum contrast (available in the paper above)

I also ran into this Palette by an MIT student. Lastly, The following links may be useful in converting between different color systems / coordinates (some colors in the articles are not specified in RGB, for instance):

For Kelly's and Boynton's list, I've already made the conversion to RGB (with the exception of white and black, which should be obvious). Some C# code:

public static ReadOnlyCollection<Color> KellysMaxContrastSet
{
    get { return _kellysMaxContrastSet.AsReadOnly(); }
}

private static readonly List<Color> _kellysMaxContrastSet = new List<Color>
{
    UIntToColor(0xFFFFB300), //Vivid Yellow
    UIntToColor(0xFF803E75), //Strong Purple
    UIntToColor(0xFFFF6800), //Vivid Orange
    UIntToColor(0xFFA6BDD7), //Very Light Blue
    UIntToColor(0xFFC10020), //Vivid Red
    UIntToColor(0xFFCEA262), //Grayish Yellow
    UIntToColor(0xFF817066), //Medium Gray

    //The following will not be good for people with defective color vision
    UIntToColor(0xFF007D34), //Vivid Green
    UIntToColor(0xFFF6768E), //Strong Purplish Pink
    UIntToColor(0xFF00538A), //Strong Blue
    UIntToColor(0xFFFF7A5C), //Strong Yellowish Pink
    UIntToColor(0xFF53377A), //Strong Violet
    UIntToColor(0xFFFF8E00), //Vivid Orange Yellow
    UIntToColor(0xFFB32851), //Strong Purplish Red
    UIntToColor(0xFFF4C800), //Vivid Greenish Yellow
    UIntToColor(0xFF7F180D), //Strong Reddish Brown
    UIntToColor(0xFF93AA00), //Vivid Yellowish Green
    UIntToColor(0xFF593315), //Deep Yellowish Brown
    UIntToColor(0xFFF13A13), //Vivid Reddish Orange
    UIntToColor(0xFF232C16), //Dark Olive Green
};

public static ReadOnlyCollection<Color> BoyntonOptimized
{
    get { return _boyntonOptimized.AsReadOnly(); }
}

private static readonly List<Color> _boyntonOptimized = new List<Color>
{
    Color.FromArgb(0, 0, 255),      //Blue
    Color.FromArgb(255, 0, 0),      //Red
    Color.FromArgb(0, 255, 0),      //Green
    Color.FromArgb(255, 255, 0),    //Yellow
    Color.FromArgb(255, 0, 255),    //Magenta
    Color.FromArgb(255, 128, 128),  //Pink
    Color.FromArgb(128, 128, 128),  //Gray
    Color.FromArgb(128, 0, 0),      //Brown
    Color.FromArgb(255, 128, 0),    //Orange
};

static public Color UIntToColor(uint color)
{
    var a = (byte)(color >> 24);
    var r = (byte)(color >> 16);
    var g = (byte)(color >> 8);
    var b = (byte)(color >> 0);
    return Color.FromArgb(a, r, g, b);
}

And here are the RGB values in hex and 8-bit-per-channel representations:

kelly_colors_hex = [
    0xFFB300, # Vivid Yellow
    0x803E75, # Strong Purple
    0xFF6800, # Vivid Orange
    0xA6BDD7, # Very Light Blue
    0xC10020, # Vivid Red
    0xCEA262, # Grayish Yellow
    0x817066, # Medium Gray

    # The following don't work well for people with defective color vision
    0x007D34, # Vivid Green
    0xF6768E, # Strong Purplish Pink
    0x00538A, # Strong Blue
    0xFF7A5C, # Strong Yellowish Pink
    0x53377A, # Strong Violet
    0xFF8E00, # Vivid Orange Yellow
    0xB32851, # Strong Purplish Red
    0xF4C800, # Vivid Greenish Yellow
    0x7F180D, # Strong Reddish Brown
    0x93AA00, # Vivid Yellowish Green
    0x593315, # Deep Yellowish Brown
    0xF13A13, # Vivid Reddish Orange
    0x232C16, # Dark Olive Green
    ]

kelly_colors = dict(vivid_yellow=(255, 179, 0),
                    strong_purple=(128, 62, 117),
                    vivid_orange=(255, 104, 0),
                    very_light_blue=(166, 189, 215),
                    vivid_red=(193, 0, 32),
                    grayish_yellow=(206, 162, 98),
                    medium_gray=(129, 112, 102),

                    # these aren't good for people with defective color vision:
                    vivid_green=(0, 125, 52),
                    strong_purplish_pink=(246, 118, 142),
                    strong_blue=(0, 83, 138),
                    strong_yellowish_pink=(255, 122, 92),
                    strong_violet=(83, 55, 122),
                    vivid_orange_yellow=(255, 142, 0),
                    strong_purplish_red=(179, 40, 81),
                    vivid_greenish_yellow=(244, 200, 0),
                    strong_reddish_brown=(127, 24, 13),
                    vivid_yellowish_green=(147, 170, 0),
                    deep_yellowish_brown=(89, 51, 21),
                    vivid_reddish_orange=(241, 58, 19),
                    dark_olive_green=(35, 44, 22))

For all you Java developers, here are the JavaFX colors:

// Don't forget to import javafx.scene.paint.Color;

private static final Color[] KELLY_COLORS = {
    Color.web("0xFFB300"),    // Vivid Yellow
    Color.web("0x803E75"),    // Strong Purple
    Color.web("0xFF6800"),    // Vivid Orange
    Color.web("0xA6BDD7"),    // Very Light Blue
    Color.web("0xC10020"),    // Vivid Red
    Color.web("0xCEA262"),    // Grayish Yellow
    Color.web("0x817066"),    // Medium Gray

    Color.web("0x007D34"),    // Vivid Green
    Color.web("0xF6768E"),    // Strong Purplish Pink
    Color.web("0x00538A"),    // Strong Blue
    Color.web("0xFF7A5C"),    // Strong Yellowish Pink
    Color.web("0x53377A"),    // Strong Violet
    Color.web("0xFF8E00"),    // Vivid Orange Yellow
    Color.web("0xB32851"),    // Strong Purplish Red
    Color.web("0xF4C800"),    // Vivid Greenish Yellow
    Color.web("0x7F180D"),    // Strong Reddish Brown
    Color.web("0x93AA00"),    // Vivid Yellowish Green
    Color.web("0x593315"),    // Deep Yellowish Brown
    Color.web("0xF13A13"),    // Vivid Reddish Orange
    Color.web("0x232C16"),    // Dark Olive Green
};

the following is the unsorted kelly colors according to the order above.

unsorted kelly colors

the following is the sorted kelly colors according to hues (note that some yellows are not very contrasting)

 sorted kelly colors

String is immutable. What exactly is the meaning?

An immutable object is an object whose state cannot be modified after it is created.

So a = "ABC" <-- immutable object. "a" holds reference to the object. And, a = "DEF" <-- another immutable object, "a" holds reference to it now.

Once you assign a string object, that object can not be changed in memory.

In summary, what you did is to change the reference of "a" to a new string object.

How to add Button over image using CSS?

If I understood correctly, I would change the HTML to something like this:

<div id="shop">
    <div class="content">
        <img src="http://placehold.it/182x121"/> 
        <a href="#">Counter-Strike 1.6 Steam</a>
    </div>
</div>

Then I would be able to use position:absolute and position:relative to force the blue button down.

I have created a jsfiddle: http://jsfiddle.net/y9w99/

python - if not in list

Your code should work, but you can also try:

    if not item in mylist :

Add UIPickerView & a Button in Action sheet - How?

Even though this question is old, I'll quickly mention that I've thrown together an ActionSheetPicker class with a convenience function, so you can spawn an ActionSheet with a UIPickerView in one line. It's based on code from answers to this question.

Edit: It now also supports the use of a DatePicker and DistancePicker.


UPD:

This version is deprecated: use ActionSheetPicker-3.0 instead.

animation

Python conversion between coordinates

Thinking about it in general, I would strongly consider hiding coordinate system behind well-designed abstraction. Quoting Uncle Bob and his book:

class Point(object)
    def setCartesian(self, x, y)
    def setPolar(self, rho, theta)
    def getX(self)
    def getY(self)
    def getRho(self)
    def setTheta(self)

With interface like that any user of Point class may choose convenient representation, no explicit conversions will be performed. All this ugly sines, cosines etc. will be hidden in one place. Point class. Only place where you should care which representation is used in computer memory.

How to delete and recreate from scratch an existing EF Code First database

If you created your database following this tutorial: https://msdn.microsoft.com/en-au/data/jj193542.aspx

... then this might work:

  1. Delete all .mdf and .ldf files in your project directory
  2. Go to View / SQL Server Object Explorer and delete the database from the (localdb)\v11.0 subnode. See also https://stackoverflow.com/a/15832184/2279059

Start an external application from a Google Chrome Extension?

There's an extension for Chrome (SimpleGet) that has a plugin for Windows and Linux that can execute an app with command line parameters.....
http://pinel.cc/
http://code.google.com/p/simple-get/
http://www.chromeextensions.org/other/simple-get/

Eclipse - "Workspace in use or cannot be created, chose a different one."

An additional reason could be that you're pointing to a workspace on a drive that no longer exists, thinking that you're choosing the valid one. For instance, for me the workspace used to exist on the F drive, but now it is on my D drive. Even though I don't have the F drive anymore it is still listed as a workspace I once used during Eclipse startup. When I choose this old workspace Eclipse complains that the workspace is "in use", which is very strange.

Find unused npm packages in package.json

The script from gombosg is much better then npm-check.
I have modified a little bit, so devdependencies in node_modules will also be found.
example sass never used, but needed in sass-loader

#!/bin/bash
DIRNAME=${1:-.}
cd $DIRNAME

FILES=$(mktemp)
PACKAGES=$(mktemp)

# use fd
# https://github.com/sharkdp/fd

function check {
    cat package.json \
        | jq "{} + .$1 | keys" \
        | sed -n 's/.*"\(.*\)".*/\1/p' > $PACKAGES
    echo "--------------------------"
    echo "Checking $1..."
    fd '(js|ts|json)$' -t f > $FILES
    while read PACKAGE
    do
        if [ -d "node_modules/${PACKAGE}" ]; then
            fd  -t f '(js|ts|json)$' node_modules/${PACKAGE} >> $FILES
        fi
        RES=$(cat $FILES | xargs -I {} egrep -i "(import|require|loader|plugins|${PACKAGE}).*['\"](${PACKAGE}|.?\d+)[\"']" '{}' | wc -l)

        if [ $RES = 0 ]
        then
            echo -e "UNUSED\t\t $PACKAGE"
        else
            echo -e "USED ($RES)\t $PACKAGE"
        fi
    done < $PACKAGES
}

check "dependencies"
check "devDependencies"
check "peerDependencies"

Result with original script:

--------------------------
Checking dependencies...
UNUSED           jquery
--------------------------
Checking devDependencies...
UNUSED           @types/jquery
UNUSED           @types/jqueryui
USED (1)         autoprefixer
USED (1)         awesome-typescript-loader
USED (1)         cache-loader
USED (1)         css-loader
USED (1)         d3
USED (1)         mini-css-extract-plugin
USED (1)         postcss-loader
UNUSED           sass
USED (1)         sass-loader
USED (1)         terser-webpack-plugin
UNUSED           typescript
UNUSED           webpack
UNUSED           webpack-cli
USED (1)         webpack-fix-style-only-entries

and the modified:

Checking dependencies...
USED (5)         jquery
--------------------------
Checking devDependencies...
UNUSED           @types/jquery
UNUSED           @types/jqueryui
USED (1)         autoprefixer
USED (1)         awesome-typescript-loader
USED (1)         cache-loader
USED (1)         css-loader
USED (2)         d3
USED (1)         mini-css-extract-plugin
USED (1)         postcss-loader
USED (3)         sass
USED (1)         sass-loader
USED (1)         terser-webpack-plugin
USED (16)        typescript
USED (16)        webpack
USED (2)         webpack-cli
USED (2)         webpack-fix-style-only-entries

Multiple cases in switch statement

One lesser known facet of switch in C# is that it relies on the operator= and since it can be overriden you could have something like this:


string s = foo();

switch (s) {
  case "abc": /*...*/ break;
  case "def": /*...*/ break;
}

Does JavaScript have a built in stringbuilder class?

When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com

How to shuffle an ArrayList

Use this method and pass your array in parameter

Collections.shuffle(arrayList);

This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.

You can now use arraylist which is shuffled.

Easy way to build Android UI?

Not saying this is the best way to go, but its good to have options. Necessitas is a project that ports Qt to android. It is still in its early stages and lacking full features, but for those who know Qt and don't wanna bother with the terrible lack of good tools for Android UI would be wise to at least consider using this.

Use the auto keyword in C++ STL

The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.

Examples:

auto a = 0.0f;  // a is float
auto b = std::vector<int>();  // b is std::vector<int>()

MyType foo()  { return MyType(); }

auto c = foo();  // c is MyType

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

How to properly seed random number generator

I tried the program below and saw different string each time

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func RandomString(count int){
  rand.Seed(time.Now().UTC().UnixNano()) 
  for(count > 0 ){
    x := Random(65,91)
    fmt.Printf("%c",x)
    count--;
  }
}

func Random(min, max int) (int){
 return min+rand.Intn(max-min) 
}

func main() {
 RandomString(12)
}

And the output on my console is

D:\james\work\gox>go run rand.go
JFBYKAPEBCRC
D:\james\work\gox>go run rand.go
VDUEBIIDFQIB
D:\james\work\gox>go run rand.go
VJYDQPVGRPXM

Date Comparison using Java

If for some reason you're intent on using Date objects for your solution, you'll need to do something like this:


    // Convert user input into year, month, and day integers
    Date toDate = new Date(year - 1900, month - 1, day + 1);
    Date currentDate = new Date();
    boolean runThatReport = toDate.after(currentDate);

Shifting the toDate ahead to midnight of the next day will take care of the bug I've whined about in the comments to other answers. But, note that this approach uses a deprecated constructor; any approach relying on Date will use one deprecated method or another, and depending on how you do it may lead to race conditions as well (if you base toDate off of new Date() and then fiddle around with the year, month, and day, for instance). Use Calendar, as described elsewhere.

Conditionally ignoring tests in JUnit 4

In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:

public class CustomRunner extends BlockJUnit4ClassRunner {
    public CTRunner(Class<?> klass) throws initializationError {
        super(klass);
    }

    @Override
    protected boolean isIgnored(FrameworkMethod child) {
        if(shouldIgnore()) {
            return true;
        }
        return super.isIgnored(child);
    }

    private boolean shouldIgnore(class) {
        /* some custom criteria */
    }
}

Angular: date filter adds timezone, how to output UTC?

The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.

Borrowing from this answer, you could do something like this without moment.js:

controller

var app1 = angular.module('app1',[]);

app1.controller('ctrl',['$scope',function($scope){

  var toUTCDate = function(date){
    var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    return _utc;
  };

  var millisToUTCDate = function(millis){
    return toUTCDate(new Date(millis));
  };

    $scope.toUTCDate = toUTCDate;
    $scope.millisToUTCDate = millisToUTCDate;

  }]);

template

<html ng-app="app1">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="ctrl">
      <div>
      utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
      </div>
      <div>
      local {{1400167800 | date:'dd-M-yyyy H:mm'}}
      </div>
    </div>
  </body>

</html>

here's plunker to play with it

See also this and this.

Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.

Splitting a string at every n-th character

You could do it like this:

String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));

which produces:

[123, 456, 789, 0]

The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))

"Line contains NULL byte" in CSV reader (Python)

This will tell you what line is the problem.

import csv

lines = []
with open('output.txt','r') as f:
    for line in f.readlines():
        lines.append(line[:-1])

with open('corrected.csv','w') as correct:
    writer = csv.writer(correct, dialect = 'excel')
    with open('input.csv', 'r') as mycsv:
        reader = csv.reader(mycsv)
        try:
            for i, row in enumerate(reader):
                if row[0] not in lines:
                   writer.writerow(row)
        except csv.Error:
            print('csv choked on line %s' % (i+1))
            raise

Perhaps this from daniweb would be helpful:

I'm getting this error when reading from a csv file: "Runtime Error! line contains NULL byte". Any idea about the root cause of this error?

...

Ok, I got it and thought I'd post the solution. Simply yet caused me grief... Used file was saved in a .xls format instead of a .csv Didn't catch this because the file name itself had the .csv extension while the type was still .xls

How to get element by innerText

To get the filter method from user1106925 working in <=IE11 if needed

You can replace the spread operator with:

[].slice.call(document.querySelectorAll("a"))

and the includes call with a.textContent.match("your search term")

which works pretty neatly:

[].slice.call(document.querySelectorAll("a"))
   .filter(a => a.textContent.match("your search term"))
   .forEach(a => console.log(a.textContent))

Getting coordinates of marker in Google Maps API

var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();

See the google.maps.LatLng docs and google.maps.Marker getPosition().

Why functional languages?

Functional languages use a different paradigm than imperative and object-oriented languages. They use side-effect-free functions as a basic building block in the language. This enables lots of things and makes a lot of things more difficult (or in most cases different from what people are used to).

One of the biggest advantages with functional programming is that the order of execution of side-effect-free functions is not important. For example, in Erlang this is used to enable concurrency in a very transparent way. And because functions in functional languages behave very similar to mathematical functions it's easy to translate those into functional languages. In some cases, this can make code more readable.

Traditionally, one of the big disadvantages of functional programming was also the lack of side effects. It's very difficult to write useful software without IO, but IO is hard to implement without side effects in functions. So most people never got more out of functional programming than calculating a single output from a single input. In modern mixed-paradigm languages like F# or Scala this is easier.

Lots of modern languages have elements from functional programming languages. C# 3.0 has a lot functional programming features and you can do functional programming in Python too. I think the reasons for the popularity of functional programming is mostly because of two reasons: Concurrency is getting to be a real problem in normal programming because we're getting more and more multiprocessor computers; and the languages are getting more accessible.

In Java, how to append a string more efficiently?

You should use the StringBuilder class.

StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append("Some text");
stringBuilder.append("Some text");
stringBuilder.append("Some text");

String finalString = stringBuilder.toString();

In addition, please visit:

Windows equivalent of linux cksum command

In Windows (command prompt) you can use CertUtil, here is the syntax:

CertUtil [Options] -hashfile InFile [HashAlgorithm]

for syntax explanation type in cmd:

CertUtil -hashfile -?

example:

CertUtil -hashfile C:\myFile.txt MD5

default is SHA1 it supports: MD2, MD4, MD5, SHA1, SHA256, SHA384, SHA512. Unfortunately no CRC32 as Unix shell does.

Here is a link if you want to find out more https://technet.microsoft.com/en-us/library/cc732443.aspx#BKMK_menu

What is the best way to redirect a page using React Router?

You also can Redirect within the Route as follows. This is for handle invalid routes.

<Route path='*' render={() => 
     (
       <Redirect to="/error"/>
     )
}/>

$(...).datepicker is not a function - JQuery - Bootstrap

To get rid of the bad looking datepicker you need to add jquery-ui css

<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">

How do I extract Month and Year in a MySQL date and compare them?

While it was discussed in the comments, there isn't an answer containing it yet, so it can be easy to miss. DATE_FORMAT works really well and is flexible to handle many different patterns.

DATE_FORMAT(date,'%Y%m')

To put it in a query:

SELECT DATE_FORMAT(test_date,'%Y%m') AS date FROM test_table;

How can I query a value in SQL Server XML column

You can query the whole tag, or just the specific value. Here I use a wildcard for the xml namespaces.

declare @myDoc xml
set @myDoc = 
'<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://stackoverflow.com">
    <Child>my value</Child>
 </Root>'

select @myDoc.query('/*:Root/*:Child') -- whole tag
select @myDoc.value('(/*:Root/*:Child)[1]', 'varchar(255)') -- only value

Python datetime strptime() and strftime(): how to preserve the timezone information

Try this:

import pytz
import datetime

fmt = '%Y-%m-%d %H:%M:%S %Z'

d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = pytz.timezone('America/New_York').localize(d.strptime(d_string,fmt), is_dst=None)
print(d_string)
print(d2.strftime(fmt))

"Missing return statement" within if / for / while

Any how myMethod() should return a String value .what if your condition is false is myMethod return anything? ans is no so you need to define return null or some string value in false condition

public String myMethod() {
    boolean c=true;
    if (conditions) {
        return "d";
    }
    return null;//or some other string value
}

Java synchronized method lock on object, or method?

From oracle documentation link

Making methods synchronized has two effects:

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads

Have a look at this documentation page to understand intrinsic locks and lock behavior.

This will answer your question: On same object x , you can't call x.addA() and x.addB() at same time when one of the synchronized methods execution is in progress.

How can I get the current stack trace in Java?

Maybe you could try this:

catch(Exception e)
{
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer);
    e.printStackTrace(pw);
    String errorDetail = writer.toString();
}

The string 'errorDetail' contains the stacktrace.

How to set auto increment primary key in PostgreSQL?

Maybe I'm a bit of late to answer this question, but I'm working on this subject at my job :)

I wanted to write column 'a_code' = c1,c2,c3,c4...

Firstly I opened a column with the name ref_id and the type serial. Then I solved my problem with this command:

update myschema.mytable set a_code=cast('c'||"ref_id" as text) 

How to assign pointer address manually in C programming language?

Your code would be like this:

int *p = (int *)0x28ff44;

int needs to be the type of the object that you are referencing or it can be void.

But be careful so that you don't try to access something that doesn't belong to your program.

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

How to write file in UTF-8 format?

//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

I got this line from Cool

How to check if a function exists on a SQL database

I know this thread is old but I just wanted to add this answer for those who believe it's safer to Alter than Drop and Create. The below will Alter the Function if it exists or Create it if doesn't:

  IF NOT EXISTS (SELECT *
               FROM   sys.objects
               WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                      AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
       EXEC('CREATE FUNCTION [dbo].[foo]() RETURNS INT AS BEGIN RETURN 0 END')
  GO
  ALTER FUNCTION [dbo].[foo]
  AS
  ...

How to enable mod_rewrite for Apache 2.2

The first time I struggled with mod_rewrite rules ignoring my traffic, I learned (frustratingly) that I had placed them in the wrong <VirtualHost>, which meant that my traffic would ignore all of them no matter how well-written they were. Make sure this isn't happening to you:

# Change the log location to suit your system. RewriteLog /var/log/apache-rw.log RewriteLogLevel 2

These parameters will activate if you perform a graceful restart of Apache, so you can recycle them in and closely monitor the mod_rewrite behavior. Once your problem is fixed, turn the RewriteLogLevel back down and celebrate.

In 100% of my experience, I've found that the RewriteLog has helped me discover the problem with my rewrite rules. I can't recommend this enough. Good luck in your troubleshooting!

Also, this bookmark is your best friend: http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritelog

How to use RANK() in SQL Server

SELECT contendernum,totals, RANK() OVER (ORDER BY totals ASC) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
 GROUP BY ContenderNum
) AS a

What are the differences between a superkey and a candidate key?

Super key: super key is a set of atttibutes in a relation(table).which can define every tupple in the relation(table) uniquely.

Candidate key: we can say minimal super key is candidate key. Candidate is the smallest sub set of super key. And can uniquely define each and every tupple.

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

You can try this:

SELECT * FROM MYTABLE WHERE DATE BETWEEN '03/10/2014 06:25:00' and '03/12/2010 6:25:00'

How does one generate a random number in Apple's Swift language?

Without arc4Random_uniform() in some versions of Xcode(in 7.1 it runs but doesn't autocomplete for me). You can do this instead.

To generate a random number from 0-5. First

import GameplayKit

Then

let diceRoll = GKRandomSource.sharedRandom().nextIntWithUpperBound(6)

Merge a Branch into Trunk

Do an svn update in the trunk, note the revision number.

From the trunk:

svn merge -r<revision where branch was cut>:<revision of trunk> svn://path/to/branch/branchName

You can check where the branch was cut from the trunk by doing an svn log

svn log --stop-on-copy

Find the IP address of the client in an SSH session

I'm getting the following output from who -m --ips on Debian 10:

root pts/0 Dec 4 06:45 123.123.123.123

Looks like a new column was added, so {print $5} or "take 5th column" attempts don't work anymore.

Try this:

who -m --ips | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'

Source:

Where do I find the Instagram media ID of a image

Try the solution from this question: How can I get an direct Instagram link from a twitter entity?

You can get just the image by appending /media/ to the URL. Using your

You can even specify a size,

One of t (thumbnail), m (medium), l (large). Defaults to m.

So for a thumbnail: http://instagr.am/p/QC8hWKL_4K/media/?size=t

Error: JAVA_HOME is not defined correctly executing maven

We open a terminal and look for the location of java:

manuel@zonademanel:~ ? whereis java

java: /usr/bin/java /etc/java /usr/bin/X11/java /usr/share/java /usr/share/man/man1/java.1.gz

What we are looking for is /usr/bin/java continue on the command line to find the absolute path , as this is only a symbolic link.

manuel@zonademanel:~ ? ls -lah /usr/bin/java

lrwxrwxrwx 1 root root 22 may 19 2015 /usr/bin/java -> /etc/alternatives/java

manuel@zonademanel:~ ? ls -lah /etc/alternatives/java

lrwxrwxrwx 1 root root 39 dic 7 11:52 /etc/alternatives/java -> /usr/lib/jvm/java-8-oracle/jre/bin/java

I modified my /etc/environment file with the following values

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/java-8-oracle/jre/bin" JAVA_HOME="/usr/lib/jvm/java-8-oracle/jre"

If I do not want to relogin I can reload the changes with:

source /etc/environment 

??And run mvn -version correctly

manuel@zonademanel:~ ? mvn -version

Apache Maven 3.0.5
Maven home: /usr/share/maven
Java version: 1.8.0_77, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-oracle/jre
Default locale: es_MX, platform encoding: UTF-8
OS name: "linux", version: "3.16.0-70-generic", arch: "amd64", family: "unix"

How to properly add include directories with CMake

Add include_directories("/your/path/here").

This will be similar to calling gcc with -I/your/path/here/ option.

Make sure you put double quotes around the path. Other people didn't mention that and it made me stuck for 2 days. So this answer is for people who are very new to CMake and very confused.

How do I check if a string is a number (float)?

The input may be as follows:

a="50" b=50 c=50.1 d="50.1"


1-General input:

The input of this function can be everything!

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c) and binary (e.g. 0b10100111001) notation is not allowed.

is_numeric function

import ast
import numbers              
def is_numeric(obj):
    if isinstance(obj, numbers.Number):
        return True
    elif isinstance(obj, str):
        nodes = list(ast.walk(ast.parse(obj)))[1:]
        if not isinstance(nodes[0], ast.Expr):
            return False
        if not isinstance(nodes[-1], ast.Num):
            return False
        nodes = nodes[1:-1]
        for i in range(len(nodes)):
            #if used + or - in digit :
            if i % 2 == 0:
                if not isinstance(nodes[i], ast.UnaryOp):
                    return False
            else:
                if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                    return False
        return True
    else:
        return False

test:

>>> is_numeric("54")
True
>>> is_numeric("54.545")
True
>>> is_numeric("0x45")
True

is_float function

Finds whether the given variable is float. float strings consist of optional sign, any number of digits, ...

import ast

def is_float(obj):
    if isinstance(obj, float):
        return True
    if isinstance(obj, int):
        return False
    elif isinstance(obj, str):
        nodes = list(ast.walk(ast.parse(obj)))[1:]
        if not isinstance(nodes[0], ast.Expr):
            return False
        if not isinstance(nodes[-1], ast.Num):
            return False
        if not isinstance(nodes[-1].n, float):
            return False
        nodes = nodes[1:-1]
        for i in range(len(nodes)):
            if i % 2 == 0:
                if not isinstance(nodes[i], ast.UnaryOp):
                    return False
            else:
                if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                    return False
        return True
    else:
        return False

test:

>>> is_float("5.4")
True
>>> is_float("5")
False
>>> is_float(5)
False
>>> is_float("5")
False
>>> is_float("+5.4")
True

what is ast?


2- If you are confident that the variable content is String:

use str.isdigit() method

>>> a=454
>>> a.isdigit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'isdigit'
>>> a="454"
>>> a.isdigit()
True

3-Numerical input:

detect int value:

>>> isinstance("54", int)
False
>>> isinstance(54, int)
True
>>> 

detect float:

>>> isinstance("45.1", float)
False
>>> isinstance(45.1, float)
True

Find if current time falls in a time range

Some good answers here but none cover the case of your start time being in a different day than your end time. If you need to straddle the day boundary, then something like this may help:

TimeSpan start = TimeSpan.Parse("22:00"); // 10 PM
TimeSpan end = TimeSpan.Parse("02:00");   // 2 AM
TimeSpan now = DateTime.Now.TimeOfDay;

if (start <= end)
{
    // start and stop times are in the same day
    if (now >= start && now <= end)
    {
        // current time is between start and stop
    }
}
else
{
    // start and stop times are in different days
    if (now >= start || now <= end)
    {
       // current time is between start and stop
    }
}

Note that in this example the time boundaries are inclusive and that this still assumes less than a 24-hour difference between start and stop.

Set specific precision of a BigDecimal

You can use setScale() e.g.

double d = ...
BigDecimal db = new BigDecimal(d).setScale(12, BigDecimal.ROUND_HALF_UP);

How to get the Enum Index value in C#

One reason that the designers c# might have chosen to NOT have enums auto convert was to prevent accidentally mixing different enum types...

e.g. this is bad code followed by a good version
enum ParkingLevel { GroundLevel, FirstFloor};
enum ParkingFacing { North, East, South, West }
void Test()
{
    var parking = ParkingFacing.North; // NOT A LEVEL
    // WHOOPS at least warning in editor/compile on calls
    WhichLevel(parking); 

    // BAD  wrong type of index, no warning
    var info = ParkinglevelArray[ (int)parking ];
}


// however you can write this, looks complicated 
// but avoids using casts every time AND stops miss-use
void Test()
{
  ParkingLevelManager levels = new ParkingLevelManager();
  // assign info to each level
  var parking = ParkingFacing.North;

  // Next line wrong mixing type 
  // but great you get warning in editor or at compile time      
  var info=levels[parking];

  // and.... no cast needed for correct use
  var pl = ParkingLevel.GroundLevel;
  var infoCorrect=levels[pl];

}
class ParkingLevelInfo { /*...*/ }
class ParkingLevelManager
{
    List<ParkingLevelInfo> m_list;
    public ParkingLevelInfo this[ParkingLevel x] 
 { get{ return m_list[(int)x]; } }}

iPad WebApp Full Screen in Safari

This only works after you save a bookmark to the app to the home screen. Not if you just browse to the site normally.

JQuery, Spring MVC @RequestBody and JSON - making it work together

If you do not want to configure the message converters yourself, you can use either @EnableWebMvc or <mvc:annotation-driven />, add Jackson to the classpath and Spring will give you both JSON, XML (and a few other converters) by default. Additionally, you will get some other commonly used features for conversion, formatting and validation.

isPrime Function for Python Language

It was an exercise in codecademy and that's how i passed it below...

def is_prime(x):  

    # If number(x) is evenly divided by following dividers then number(x) is not prime

    divider = [2, 3, 5, 7]

    # An empty list to be able to check whether number(x) is evenly divided:

    remainder = []

    # exceptions for numbers 1,2,3,5,7:
    if x < 2:
        return False
    if x in divider:
        return True
    else:
        for nums in divider:
            remainder.append(x % nums)
        if 0 in remainder:
            return False
        else:
            return True

How to show disable HTML select option in by default?

use

<option selected="true" disabled="disabled">Choose Tagging</option>    

How do you do a ‘Pause’ with PowerShell 2.0?

In addition to Michael Sorens' answer:

<6> ReadKey in a new process

Start-Process PowerShell {[void][System.Console]::ReadKey($true)} -Wait -NoNewWindow
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE.

How to create a <style> tag with Javascript?

This function will inject css whenever you call the function appendStyle like this:
appendStyle('css you want to inject')

This works by injecting a style node into the head of the document. This is a similar technique to what is commonly used to lazy-load JavaScript. It works consistently in most modern browsers.

_x000D_
_x000D_
appendStyle = function (content) {_x000D_
  style = document.createElement('STYLE');_x000D_
  style.type = 'text/css';_x000D_
  style.appendChild(document.createTextNode(content));_x000D_
  document.head.appendChild(style);_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
</head>_x000D_
<body>_x000D_
  <h1>Lorem Ipsum</h1>_x000D_
  <p>dolar sit amet</p>_x000D_
  <button onclick='appendStyle("body { background-color: #ff0000;}h1 { font-family: Helvetica, sans-serif; font-variant: small-caps; letter-spacing: 3px; color: #ff0000; background-color: #000000;}p { font-family: Georgia, serif; font-size: 14px; font-style: normal; font-weight: normal; color: #000000; background-color: #ffff00;}")'>Press me to inject CSS!</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

You can also lazy-load external CSS files by using the following snippet:

_x000D_
_x000D_
appendExternalStyle = function (content) {_x000D_
  link = document.createElement('LINK');_x000D_
  link.rel = 'stylesheet';_x000D_
  link.href = content;_x000D_
  link.type = 'text/css';_x000D_
  document.head.appendChild(link);_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <style>_x000D_
    html {_x000D_
      font-family: sans-serif;_x000D_
      font-display: swap;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <h1>Lorem Ipsum</h1>_x000D_
  <p>dolar sit amet</p>_x000D_
  <button onclick='appendExternalStyle("data:text/css;base64,OjotbW96LXNlbGVjdGlvbntjb2xvcjojZmZmIWltcG9ydGFudDtiYWNrZ3JvdW5kOiMwMDB9OjpzZWxlY3Rpb257Y29sb3I6I2ZmZiFpbXBvcnRhbnQ7YmFja2dyb3VuZDojMDAwfWgxe2ZvbnQtc2l6ZToyZW19Ym9keSxodG1se2NvbG9yOnJnYmEoMCwwLDAsLjc1KTtmb250LXNpemU6MTZweDtmb250LWZhbWlseTpMYXRvLEhlbHZldGljYSBOZXVlLEhlbHZldGljYSxzYW5zLXNlcmlmO2xpbmUtaGVpZ2h0OjEuNjd9YnV0dG9uLGlucHV0e292ZXJmbG93OnZpc2libGV9YnV0dG9uLHNlbGVjdHstd2Via2l0LXRyYW5zaXRpb24tZHVyYXRpb246LjFzO3RyYW5zaXRpb24tZHVyYXRpb246LjFzfQ==")'>press me to inject css!</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

React JSX: selecting "selected" on selected <select> option

With React 16.8. We can do this with hooks like the following example

Codesandbox link

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const options = [
    "Monty Python and the Holy Grail",
    "Monty Python's Life of Brian",
    "Monty Python's The Meaning of Life"
  ];
  const filmsByTati = [
    {
      id: 1,
      title: "Jour de fête",
      releasedYear: 1949
    },
    {
      id: 2,
      title: "Play time",
      releasedYear: 1967
    },
    {
      id: 3,
      releasedYear: 1958,
      title: "Mon Oncle"
    }
  ];
  const [selectedOption, setSelectedOption] = useState(options[0]);
  const [selectedTatiFilm, setSelectedTatiFilm] = useState(filmsByTati[0]);
  return (
    <div className="App">
      <h1>Select Example</h1>
      <select
        value={selectedOption}
        onChange={(e) => setSelectedOption(e.target.value)}
      >
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
      <span>Selected option: {selectedOption}</span>

      <select
        value={selectedTatiFilm}
        onChange={(e) =>
          setSelectedTatiFilm(
            filmsByTati.find(film => (film.id == e.target.value))
          )
        }
      >
        {filmsByTati.map((film) => (
          <option key={film.id} value={film.id}>
            {film.title}
          </option>
        ))}
      </select>
      <span>Selected option: {selectedTatiFilm.title}</span>
    </div>
  );
}

File Upload in WebView

hifarrer's full solution is very helpful to me.

but, I met many other problems - supporting other mime type, listing capture devices(camera, video, audio recoder), opening capture device immediately(ex: <input accept="image/*;capture"> )...

So, I made a solution that works exactly same as default web browser app.

I used android-4.4.3_r1/src/com/android/browser/UploadHandler.java. (thanks to Rupert Rawnsley )

package org.mospi.agatenativewebview;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.PluginState;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = (WebView) findViewById(R.id.webView1);

        initWebView(webView);
        webView.loadUrl("http://google.com"); // TODO input your url

    }

    private final static Object methodInvoke(Object obj, String method, Class<?>[] parameterTypes, Object[] args) {
        try {
            Method m = obj.getClass().getMethod(method, new Class[] { boolean.class });
            m.invoke(obj, args);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private void initWebView(WebView webView) {

        WebSettings settings = webView.getSettings();

        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setSupportZoom(true);
        // settings.setPluginsEnabled(true);
        methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
        // settings.setPluginState(PluginState.ON);
        methodInvoke(settings, "setPluginState", new Class[] { PluginState.class }, new Object[] { PluginState.ON });
        // settings.setPluginsEnabled(true);
        methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
        // settings.setAllowUniversalAccessFromFileURLs(true);
        methodInvoke(settings, "setAllowUniversalAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });
        // settings.setAllowFileAccessFromFileURLs(true);
        methodInvoke(settings, "setAllowFileAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });

        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.clearHistory();
        webView.clearFormData();
        webView.clearCache(true);

        webView.setWebChromeClient(new MyWebChromeClient());
        // webView.setDownloadListener(downloadListener);
    }

    UploadHandler mUploadHandler;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (requestCode == Controller.FILE_SELECTED) {
            // Chose a file from the file picker.
            if (mUploadHandler != null) {
                mUploadHandler.onResult(resultCode, intent);
            }
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }

    class MyWebChromeClient extends WebChromeClient {
        public MyWebChromeClient() {

        }

        private String getTitleFromUrl(String url) {
            String title = url;
            try {
                URL urlObj = new URL(url);
                String host = urlObj.getHost();
                if (host != null && !host.isEmpty()) {
                    return urlObj.getProtocol() + "://" + host;
                }
                if (url.startsWith("file:")) {
                    String fileName = urlObj.getFile();
                    if (fileName != null && !fileName.isEmpty()) {
                        return fileName;
                    }
                }
            } catch (Exception e) {
                // ignore
            }

            return title;
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            String newTitle = getTitleFromUrl(url);

            new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            }).setCancelable(false).create().show();
            return true;
            // return super.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {

            String newTitle = getTitleFromUrl(url);

            new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            }).setCancelable(false).create().show();
            return true;

            // return super.onJsConfirm(view, url, message, result);
        }

        // Android 2.x
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // Android 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg, "", "filesystem");
        }

        // Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadHandler = new UploadHandler(new Controller());
            mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
        }

        // Android 4.4, 4.4.1, 4.4.2
        // openFileChooser function is not called on Android 4.4, 4.4.1, 4.4.2,
        // you may use your own java script interface or other hybrid framework.          

        // Android 5.0.1
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            String acceptTypes[] = fileChooserParams.getAcceptTypes();

            String acceptType = "";
            for (int i = 0; i < acceptTypes.length; ++ i) {
                if (acceptTypes[i] != null && acceptTypes[i].length() != 0)
                    acceptType += acceptTypes[i] + ";";
            }
            if (acceptType.length() == 0)
                acceptType = "*/*";

            final ValueCallback<Uri[]> finalFilePathCallback = filePathCallback;

            ValueCallback<Uri> vc = new ValueCallback<Uri>() {

                @Override
                public void onReceiveValue(Uri value) {

                    Uri[] result;
                    if (value != null)
                        result = new Uri[]{value};
                    else
                        result = null;

                    finalFilePathCallback.onReceiveValue(result);

                }
            };

            openFileChooser(vc, acceptType, "filesystem");


            return true;
       }
    };

    class Controller {
        final static int FILE_SELECTED = 4;

        Activity getActivity() {
            return MainActivity.this;
        }
    }

    // copied from android-4.4.3_r1/src/com/android/browser/UploadHandler.java
    //////////////////////////////////////////////////////////////////////

    /*
     * Copyright (C) 2010 The Android Open Source Project
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    // package com.android.browser;
    //
    // import android.app.Activity;
    // import android.content.ActivityNotFoundException;
    // import android.content.Intent;
    // import android.net.Uri;
    // import android.os.Environment;
    // import android.provider.MediaStore;
    // import android.webkit.ValueCallback;
    // import android.widget.Toast;
    //
    // import java.io.File;
    // import java.util.Vector;
    //
    // /**
    // * Handle the file upload callbacks from WebView here
    // */
    // public class UploadHandler {

    class UploadHandler {
        /*
         * The Object used to inform the WebView of the file to upload.
         */
        private ValueCallback<Uri> mUploadMessage;
        private String mCameraFilePath;
        private boolean mHandled;
        private boolean mCaughtActivityNotFoundException;
        private Controller mController;
        public UploadHandler(Controller controller) {
            mController = controller;
        }
        String getFilePath() {
            return mCameraFilePath;
        }
        boolean handled() {
            return mHandled;
        }
        void onResult(int resultCode, Intent intent) {
            if (resultCode == Activity.RESULT_CANCELED && mCaughtActivityNotFoundException) {
                // Couldn't resolve an activity, we are going to try again so skip
                // this result.
                mCaughtActivityNotFoundException = false;
                return;
            }
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
                    : intent.getData();
            // As we ask the camera to save the result of the user taking
            // a picture, the camera application does not return anything other
            // than RESULT_OK. So we need to check whether the file we expected
            // was written to disk in the in the case that we
            // did not get an intent returned but did get a RESULT_OK. If it was,
            // we assume that this result has came back from the camera.
            if (result == null && intent == null && resultCode == Activity.RESULT_OK) {
                File cameraFile = new File(mCameraFilePath);
                if (cameraFile.exists()) {
                    result = Uri.fromFile(cameraFile);
                    // Broadcast to the media scanner that we have a new photo
                    // so it will be added into the gallery for the user.
                    mController.getActivity().sendBroadcast(
                            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
                }
            }
            mUploadMessage.onReceiveValue(result);
            mHandled = true;
            mCaughtActivityNotFoundException = false;
        }
        void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            final String imageMimeType = "image/*";
            final String videoMimeType = "video/*";
            final String audioMimeType = "audio/*";
            final String mediaSourceKey = "capture";
            final String mediaSourceValueCamera = "camera";
            final String mediaSourceValueFileSystem = "filesystem";
            final String mediaSourceValueCamcorder = "camcorder";
            final String mediaSourceValueMicrophone = "microphone";
            // According to the spec, media source can be 'filesystem' or 'camera' or 'camcorder'
            // or 'microphone' and the default value should be 'filesystem'.
            String mediaSource = mediaSourceValueFileSystem;
            if (mUploadMessage != null) {
                // Already a file picker operation in progress.
                return;
            }
            mUploadMessage = uploadMsg;
            // Parse the accept type.
            String params[] = acceptType.split(";");
            String mimeType = params[0];
            if (capture.length() > 0) {
                mediaSource = capture;
            }
            if (capture.equals(mediaSourceValueFileSystem)) {
                // To maintain backwards compatibility with the previous implementation
                // of the media capture API, if the value of the 'capture' attribute is
                // "filesystem", we should examine the accept-type for a MIME type that
                // may specify a different capture value.
                for (String p : params) {
                    String[] keyValue = p.split("=");
                    if (keyValue.length == 2) {
                        // Process key=value parameters.
                        if (mediaSourceKey.equals(keyValue[0])) {
                            mediaSource = keyValue[1];
                        }
                    }
                }
            }
            //Ensure it is not still set from a previous upload.
            mCameraFilePath = null;
            if (mimeType.equals(imageMimeType)) {
                if (mediaSource.equals(mediaSourceValueCamera)) {
                    // Specified 'image/*' and requested the camera, so go ahead and launch the
                    // camera directly.
                    startActivity(createCameraIntent());
                    return;
                } else {
                    // Specified just 'image/*', capture=filesystem, or an invalid capture parameter.
                    // In all these cases we show a traditional picker filetered on accept type
                    // so launch an intent for both the Camera and image/* OPENABLE.
                    Intent chooser = createChooserIntent(createCameraIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(imageMimeType));
                    startActivity(chooser);
                    return;
                }
            } else if (mimeType.equals(videoMimeType)) {
                if (mediaSource.equals(mediaSourceValueCamcorder)) {
                    // Specified 'video/*' and requested the camcorder, so go ahead and launch the
                    // camcorder directly.
                    startActivity(createCamcorderIntent());
                    return;
               } else {
                    // Specified just 'video/*', capture=filesystem or an invalid capture parameter.
                    // In all these cases we show an intent for the traditional file picker, filtered
                    // on accept type so launch an intent for both camcorder and video/* OPENABLE.
                    Intent chooser = createChooserIntent(createCamcorderIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(videoMimeType));
                    startActivity(chooser);
                    return;
                }
            } else if (mimeType.equals(audioMimeType)) {
                if (mediaSource.equals(mediaSourceValueMicrophone)) {
                    // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
                    // recorder.
                    startActivity(createSoundRecorderIntent());
                    return;
                } else {
                    // Specified just 'audio/*',  capture=filesystem of an invalid capture parameter.
                    // In all these cases so go ahead and launch an intent for both the sound
                    // recorder and audio/* OPENABLE.
                    Intent chooser = createChooserIntent(createSoundRecorderIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(audioMimeType));
                    startActivity(chooser);
                    return;
                }
            }
            // No special handling based on the accept type was necessary, so trigger the default
            // file upload chooser.
            startActivity(createDefaultOpenableIntent());
        }
        private void startActivity(Intent intent) {
            try {
                mController.getActivity().startActivityForResult(intent, Controller.FILE_SELECTED);
            } catch (ActivityNotFoundException e) {
                // No installed app was able to handle the intent that
                // we sent, so fallback to the default file upload control.
                try {
                    mCaughtActivityNotFoundException = true;
                    mController.getActivity().startActivityForResult(createDefaultOpenableIntent(),
                            Controller.FILE_SELECTED);
                } catch (ActivityNotFoundException e2) {
                    // Nothing can return us a file, so file upload is effectively disabled.
                    Toast.makeText(mController.getActivity(), R.string.uploads_disabled,
                            Toast.LENGTH_LONG).show();
                }
            }
        }
        private Intent createDefaultOpenableIntent() {
            // Create and return a chooser with the default OPENABLE
            // actions including the camera, camcorder and sound
            // recorder where available.
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(),
                    createSoundRecorderIntent());
            chooser.putExtra(Intent.EXTRA_INTENT, i);
            return chooser;
        }
        private Intent createChooserIntent(Intent... intents) {
            Intent chooser = new Intent(Intent.ACTION_CHOOSER);
            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
            chooser.putExtra(Intent.EXTRA_TITLE,
                    mController.getActivity().getResources()
                            .getString(R.string.choose_upload));
            return chooser;
        }
        private Intent createOpenableIntent(String type) {
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(type);
            return i;
        }
        private Intent createCameraIntent() {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File externalDataDir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM);
            File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
                    File.separator + "browser-photos");
            cameraDataDir.mkdirs();
            mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
                    System.currentTimeMillis() + ".jpg";
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
            return cameraIntent;
        }
        private Intent createCamcorderIntent() {
            return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        }
        private Intent createSoundRecorderIntent() {
            return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        }
    }
}

additional string resoruce of res/values/string.xml :

<string name="uploads_disabled">File uploads are disabled.</string>
<string name="choose_upload">Choose file for upload</string>

If you are using proguard, you may need below option in proguard-project.txt :

-keepclassmembers class * extends android.webkit.WebChromeClient {
   public void openFileChooser(...);
}

UPDATE #1 (2015.09.09)

adds code for Android 5.0.1 compatability.

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

Padding zeros to the left in postgreSQL

You can use the rpad and lpad functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use ::char or ::text to cast them:

SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
       LPAD(numcol::text, 3, '0'), -- Zero-pads to the left up to the length of 3
FROM   my_table

How to copy text programmatically in my Android app?

@FlySwat already gave the correct answer, I am just sharing the complete answer:

Use ClipboardManager.setPrimaryClip (http://developer.android.com/reference/android/content/ClipboardManager.html) method:

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip); 

Where label is a User-visible label for the clip data and text is the actual text in the clip. According to official docs.

It is important to use this import:

import android.content.ClipboardManager;

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

I didn't know, but found the question interesting. So I dug in the android code... Thanks open-source :)

The screen you show is DateTimeSettings. The checkbox "Use network-provided values" is associated to the shared preference String KEY_AUTO_TIME = "auto_time"; and also to Settings.System.AUTO_TIME

This settings is observed by an observed called mAutoTimeObserver in the 2 network ServiceStateTrackers: GsmServiceStateTracker and CdmaServiceStateTracker.

Both implementations call a method called revertToNitz() when the settings becomes true. Apparently NITZ is the equivalent of NTP in the carrier world.

Bottom line: You can set the time to the value provided by the carrier thanks to revertToNitz(). Unfortunately, I haven't found a mechanism to get the network time. If you really need to do this, I'm afraid, you'll have to copy these ServiceStateTrackers implementations, catch the intent raised by the framework (I suppose), and add a getter to mSavedTime.

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

WordPress Get the Page ID outside the loop

If you by any means searched this topic because of the post page (index page alternative when using static front page), then the right answer is this:

if (get_option('show_on_front') == 'page') {
    $page_id = get_option('page_for_posts');
    echo get_the_title($page_id);
}

(taken from Forrst | Echo WordPress "Posts Page" title - Some code from tammyhart)

Closing Twitter Bootstrap Modal From Angular Controller

You can do it like this:

angular.element('#modal').modal('hide');

How do I update the password for Git?

There is such a confusion on this question, as there is way too much complexity in this question. First MacOS vs. Win10. Then the different auth mechanisms.

I will start a consolidated answer here and probably need some help, if I do not get help, I will keep working on the answer until it is complete, but that will take time.

Windows 10: |

|-- Run this command. You will be prompted on next push/pull to enter username and password:
|      git config --global credential.helper wincred (Thanks to @Andrew Pye)

` MacOS:

|
|-- Using git config to store username and password:
|  git config --global --add user.password
|
|---- first time entry
|  git config --global --add user.password <new_pass>
|
|---- password update
|  git config --global --unset user.password
|  git config --global --add user.password <new_pass>
|
|-- Using keychain:
|  git config --global credential.helper osxkeychain
|
|---- first time entry
|  Terminal will ask you for the username and password. Just enter it, it will be 
|  stored in keychain from then on.
|
|---- password update
|  Open keychain, delete the entry for the repository you are trying to use. 
|  (git remote -v will show you)
|  On next use of git push or something that needs permissions, git will ask for 
|  the credentials, as it can not find them in the keychain anymore.
`

How Does Modulus Divison Work

Maybe the example with an clock could help you understand the modulo.

A familiar use of modular arithmetic is its use in the 12-hour clock, in which the day is divided into two 12 hour periods.

Lets say we have currently this time: 15:00
But you could also say it is 3 pm

This is exactly what modulo does:

15 / 12 = 1, remainder 3

You find this example better explained on wikipedia: Wikipedia Modulo Article

How to convert php array to utf8?

You can use something like this:

<?php
array_walk_recursive(
$array, function (&$value)
{
 $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
);
?>

How to check how many letters are in a string in java?

To answer your questions in a easy way:

    a) String.length();
    b) String.charAt(/* String index */);

converting CSV/XLS to JSON?

See if this helps: Back to CSV - Convert CSV text to Objects; via JSON

This is a blog post published in November 2008 that includes C# code to provide a solution.

From the intro on the blog post:

As Json is easier to read and write then Xml. It follows that CSV (comma seperated values) is easier to read and write then Json. CSV also has tools such as Excel and others that make it easy to work with and create. So if you ever want to create a config or data file for your next app, here is some code to convert CSV to JSON to POCO objects

How do I call a dynamically-named method in Javascript?

you can do it like this:

function MyClass() {
    this.abc = function() {
        alert("abc");
    }
}

var myObject = new MyClass();
myObject["abc"]();

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Here is what I had and what caused my "incomplete type error":

#include "X.h" // another already declared class
class Big {...} // full declaration of class A

class Small : Big {
    Small() {}
    Small(X); // line 6
}
//.... all other stuff

What I did in the file "Big.cpp", where I declared the A2's constructor with X as a parameter is..

Big.cpp

Small::Big(X my_x) { // line 9 <--- LOOK at this !
}

I wrote "Small::Big" instead of "Small::Small", what a dumb mistake.. I received the error "incomplete type is now allowed" for the class X all the time (in lines 6 and 9), which made a total confusion..

Anyways, that is where a mistake can happen, and the main reason is that I was tired when I wrote it and I needed 2 hours of exploring and rewriting the code to reveal it.

How to parse a text file with C#

One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.

public void ImportCsvFile(string filename)
{
    FileInfo file = new FileInfo(filename);

    using (OleDbConnection con = 
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
            file.DirectoryName + "\";
            Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
    {
        using (OleDbCommand cmd = new OleDbCommand(string.Format
                                  ("SELECT * FROM [{0}]", file.Name), con))
        {
            con.Open();

            // Using a DataReader to process the data
            using (OleDbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Process the current reader entry...
                }
            }

            // Using a DataTable to process the data
            using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
            {
                DataTable tbl = new DataTable("MyTable");
                adp.Fill(tbl);

                foreach (DataRow row in tbl.Rows)
                {
                    // Process the current row...
                }
            }
        }
    }
} 

Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.

How do I get the value of a textbox using jQuery?

Noticed your comment about using it for email validation and needing a plugin, the validation plugin may help you, its located at http://bassistance.de/jquery-plugins/jquery-plugin-validation/, it comes with a e-mail rule as well.

Print to standard printer from Python?

This has only been tested on Windows:

You can do the following:

import os

os.startfile("C:/Users/TestFile.txt", "print")

This will start the file, in its default opener, with the verb 'print', which will print to your default printer.Only requires the os module which comes with the standard library

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

Use DATE_FORMAT function to change the format.

SELECT DATE_FORMAT(CURDATE(), '%d/%m/%Y')

SELECT DATE_FORMAT(column_name, '%d/%m/%Y') FROM tablename

Refer DOC for more details

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Use This code ..to change action bar background color. open "res/values/themes.xml" (if not present, create it) and add

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- the theme applied to the application or activity -->
<style name="CustomActionBarTheme"
       parent="@android:style/Theme.Holo.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>
 <!-- ActionBar styles -->
<style name="MyActionBar"
       parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@drawable/actionbar_background</item>
</style>

Note : this code works for android 3.0 and higher versions only

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

How do I exclude all instances of a transitive dependency when using Gradle?

For excluding one or more library globally add the following to your build.gradle

configurations.all {
   exclude group:"org.apache.geronimo.specs", module: "geronimo-servlet_2.5_spec"
   exclude group:"ch.qos.logback", module:"logback-core"
}

Now the exclude block has two properties group and module. For those of you coming from maven background, group is same as groupId and module is same as artifactId. Example: To exclude com.mchange:c3p0:0.9.2.1 following should be exclude block

exclude group:"com.mchange", module:"c3p0"

How can I remove the search bar and footer added by the jQuery DataTables plugin?

A quick and dirty way is to find out the class of the footer and hide it using jQuery or CSS:

$(".dataTables_info").hide();

How to generate access token using refresh token through google drive API?

Using ASP.Net Post call, this worked for me.

StringBuilder getNewToken = new StringBuilder();
getNewToken.Append("https://www.googleapis.com/oauth2/v4/token");                        
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(getNewToken.ToString());
                    var values = new Dictionary<string, string>
                    {
                        { "client_id", <Your Client Id> },
                        { "client_secret", <Your Client Secret> },
                        { "refresh_token", <Your Saved Refresh Token> },
                        { "grant_type", "refresh_token"}
                    };

                    var content = new FormUrlEncodedContent(values);
                    var response = await client.PostAsync(getNewToken.ToString(), content);

How to Load an Assembly to AppDomain with all references recursively?

You need to handle the AppDomain.AssemblyResolve or AppDomain.ReflectionOnlyAssemblyResolve events (depending on which load you're doing) in case the referenced assembly is not in the GAC or on the CLR's probing path.

AppDomain.AssemblyResolve

AppDomain.ReflectionOnlyAssemblyResolve

Usage of sys.stdout.flush() method

Consider the following simple Python script:

import time
import sys

for i in range(5):
    print(i),
    #sys.stdout.flush()
    time.sleep(1)

This is designed to print one number every second for five seconds, but if you run it as it is now (depending on your default system buffering) you may not see any output until the script completes, and then all at once you will see 0 1 2 3 4 printed to the screen.

This is because the output is being buffered, and unless you flush sys.stdout after each print you won't see the output immediately. Remove the comment from the sys.stdout.flush() line to see the difference.

Visual Studio replace tab with 4 spaces?

None of these answer were working for me on my macbook pro. So what i had to do was go to:

Preferences -> Source Code -> Code Formatting -> C# source code.

From here I could change my style and spacing tabs etc. This is the only project i have where the lead developer has different formatting than i do. It was a pain in the butt that my IDE would format my code different than theirs.

What is the difference between Python's list methods append and extend?

An English dictionary defines the words append and extend as:

append: add (something) to the end of a written document.
extend: make larger. Enlarge or expand


With that knowledge, now let's understand

1) The difference between append and extend

append:

  • Appends any Python object as-is to the end of the list (i.e. as a the last element in the list).
  • The resulting list may be nested and contain heterogeneous elements (i.e. list, string, tuple, dictionary, set, etc.)

extend:

  • Accepts any iterable as its argument and makes the list larger.
  • The resulting list is always one-dimensional list (i.e. no nesting) and it may contain heterogeneous elements in it (e.g. characters, integers, float) as a result of applying list(iterable).

2) Similarity between append and extend

  • Both take exactly one argument.
  • Both modify the list in-place.
  • As a result, both returns None.

Example

lis = [1, 2, 3]

# 'extend' is equivalent to this
lis = lis + list(iterable)

# 'append' simply appends its argument as the last element to the list
# as long as the argument is a valid Python object
list.append(object)

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

If you are using debug configuration for maven, use the command

clean install

And skip all the tests.

Merge PDF files with PHP

I've had similar problem in my software. We've wanted to merge several PDF files into one PDF file and submit it to an outer service. We've been using the FPDI solution as shown in Christa's solution.

However, the input PDF's we've been using could be in version higher than 1.7. We've decided to evaluate the FPDI commercial add-on. However, it turned out that some of the documents scanned by our office copier were having malformed indexes, which crashed the commercial FPDI add-on. So we've decided to use Ghostscript solution as in Chauhan's answer.

But then we got some strange metadata in the output PDF properties.

Finally we've decided to join two solutions to get PDF's merged and downgraded by Ghostscript, but the metadata is set by FPDI. We don't know yet how it would work with some advanced formatted pdfs, but for scans we use it works just fine. Here's our class excerpt:

class MergedPDF extends \FPDI
{
    private $documentsPaths = array();

    public function Render()
    {
        $outputFileName = tempnam(sys_get_temp_dir(), 'merged');

        // merge files and save resulting file as PDF version 1.4 for FPDI compatibility
        $cmd = "/usr/bin/gs -q -dNOPAUSE -dBATCH -dCompatibilityLevel=1.4 -sDEVICE=pdfwrite -sOutputFile=$outputFileName";
        foreach ($this->getDocumentsPaths() as $pdfpath) {
            $cmd .= " $pdfpath ";
        }
        $result = shell_exec($cmd);
        $this->SetCreator('Your Software Name');
        $this->setPrintHeader(false);
        $numPages = $this->setSourceFile($outputFileName);
        for ($i = 1; $i <= $numPages; $i++) {
            $tplIdx = $this->importPage($i);
            $this->AddPage();
            $this->useTemplate($tplIdx);
        }

        unlink($outputFileName);

        $content = $this->Output(null, 'S');

        return $content;
    }

    public function getDocumentsPaths()
    {
        return $this->documentsPaths;
    }

    public function setDocumentsPaths($documentsPaths)
    {
        $this->documentsPaths = $documentsPaths;
    }

    public function addDocumentPath($documentPath)
    {
        $this->documentsPaths[] = $documentPath;
    }
}

The usage of this class is as follows:

$pdf = new MergedPDF();
$pdf->setTitle($pdfTitle);
$pdf->addDocumentPath($absolutePath1);
$pdf->addDocumentPath($absolutePath2);
$pdf->addDocumentPath($absolutePath3);
$tempFileName = tempnam(sys_get_temp_dir(), 'merged');
$content = $pdf->Render();
file_put_contents($tempFileName, $content);

Replacing &nbsp; from javascript dom text node

I think when you define a function with "var foo = function() {...};", the function is only defined after that line. In other words, try this:

var replaceHtmlEntites = (function() {
  var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
  var translate = {
    "nbsp": " ",
    "amp" : "&",
    "quot": "\"",
    "lt"  : "<",
    "gt"  : ">"
  };
  return function(s) {
    return ( s.replace(translate_re, function(match, entity) {
      return translate[entity];
    }) );
  }
})();

var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
cleanText = replaceHtmlEntities(text);

Edit: Also, only use "var" the first time you declare a variable (you're using it twice on the cleanText variable).

Edit 2: The problem is the spelling of the function name. You have "var replaceHtmlEntites =". It should be "var replaceHtmlEntities ="

Find a class somewhere inside dozens of JAR files?

A bit late to the party, but nevertheless...

I've been using JarBrowser to find in which jar a particular class is present. It's got an easy to use GUI which allows you to browse through the contents of all the jars in the selected path.

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Some version working

<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

How to disable auto-play for local video in iframe

Try This Code for disable auto play video.

Its Working . Please Vote if your are done with this

<div class="embed-responsive embed-responsive-16by9">
    <video controls="true" class="embed-responsive-item">
      <source src="example.mp4" type="video/mp4" />
    </video>
</div>

Hide header in stack navigator React navigation

You can hide header like this:

<Stack.Screen name="Login" component={Login} options={{headerShown: false}}  />

How to get the 'height' of the screen using jquery

$(window).height();

To set anything in the middle you can use CSS.

<style>
#divCentre 
{ 
    position: absolute;
    left: 50%;
    top: 50%;
    width: 300px;
    height: 400px;
    margin-left: -150px;
    margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>

Why cannot change checkbox color whatever I do?

Can be very simplified like that :

input[type="checkbox"]{
    outline:2px solid red;
    outline-offset: -2px;
}

Works without any plugin :)

ng-if check if array is empty

Verify the length property of the array to be greater than 0:

<p ng-if="post.capabilities.items.length > 0">
   <strong>Topics</strong>: 
   <span ng-repeat="topic in post.capabilities.items">
     {{topic.name}}
   </span>
</p>

Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items"> evaluates always to true, even if the array is empty.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Wildcard string comparison in Javascript

I think you meant something like "*" (star) as a wildcard for example:

  • "a*b" => everything that starts with "a" and ends with "b"
  • "a*" => everything that starts with "a"
  • "*b" => everything that ends with "b"
  • "*a*" => everything that has an "a" in it
  • "*a*b*"=> everything that has an "a" in it, followed by anything, followed by a "b", followed by anything

or in your example: "bird*" => everything that starts with bird

I had a similar problem and wrote a function with RegExp:

_x000D_
_x000D_
//Short code_x000D_
function matchRuleShort(str, rule) {_x000D_
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
  return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);_x000D_
}_x000D_
_x000D_
//Explanation code_x000D_
function matchRuleExpl(str, rule) {_x000D_
  // for this solution to work on any string, no matter what characters it has_x000D_
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
_x000D_
  // "."  => Find a single character, except newline or line terminator_x000D_
  // ".*" => Matches any string that contains zero or more characters_x000D_
  rule = rule.split("*").map(escapeRegex).join(".*");_x000D_
_x000D_
  // "^"  => Matches any string with the following at the beginning of it_x000D_
  // "$"  => Matches any string with that in front at the end of it_x000D_
  rule = "^" + rule + "$"_x000D_
_x000D_
  //Create a regular expression object for matching string_x000D_
  var regex = new RegExp(rule);_x000D_
_x000D_
  //Returns true if it finds a match, otherwise it returns false_x000D_
  return regex.test(str);_x000D_
}_x000D_
_x000D_
//Examples_x000D_
alert(_x000D_
    "1. " + matchRuleShort("bird123", "bird*") + "\n" +_x000D_
    "2. " + matchRuleShort("123bird", "*bird") + "\n" +_x000D_
    "3. " + matchRuleShort("123bird123", "*bird*") + "\n" +_x000D_
    "4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +_x000D_
    "5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +_x000D_
    "6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +_x000D_
    "7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"_x000D_
);
_x000D_
_x000D_
_x000D_


If you want to read more about the used functions:

How can I fill a div with an image while keeping it proportional?

This should do it:

img {    
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
}

How do I conditionally add attributes to React components?

Here is an alternative.

var condition = true;

var props = {
  value: 'foo',
  ...( condition && { disabled: true } )
};

var component = <div { ...props } />;

Or its inline version

var condition = true;

var component = (
  <div
    value="foo"
    { ...( condition && { disabled: true } ) } />
);

Reactjs - Form input validation

import React from 'react';
import {sendFormData} from '../services/';

class Signup extends React.Component{
  constructor(props){
    super(props);
     this.state = {
       isDisabled:true
     }                                                                                                 
     this.submitForm = this.submitForm.bind(this);
  }
  validateEmail(email){
   const pattern = /[a-zA-Z0-9]+[\.]?([a-zA-Z0-9]+)?[\@][a-z]{3,9}[\.][a-z]{2,5}/g;
   const result = pattern.test(email);
   if(result===true){
     this.setState({
       emailError:false,
       email:email
     })
   } else{
     this.setState({
       emailError:true
     })
   }
 }
 handleChange(e){
  const target = e.target;
  const value = target.type === 'checkbox' ? target.checked : target.value;
  const name = target.name;
  this.setState({
    [name]: value
  });
  if(e.target.name==='firstname'){
    if(e.target.value==='' || e.target.value===null ){
      this.setState({
        firstnameError:true
      })
    } else {
      this.setState({
        firstnameError:false,     
        firstName:e.target.value
      })
    }
  }
  if(e.target.name==='lastname'){
    if(e.target.value==='' || e.target.value===null){
      this.setState({
        lastnameError:true
      })
    } else {
      this.setState({
        lastnameError:false,
        lastName:e.target.value
      })
    }
  }
  if(e.target.name==='email'){
   this.validateEmail(e.target.value);
  }
  if(e.target.name==='password'){
    if(e.target.value==='' || e.target.value===null){
      this.setState({
        passwordError:true
      })
    } else {
      this.setState({
        passwordError:false,
        password:e.target.value
      })
    }
 }
 if(this.state.firstnameError===false && this.state.lastnameError===false && 
  this.state.emailError===false && this.state.passwordError===false){
    this.setState({
      isDisabled:false
    })
 }
}
submitForm(e){
  e.preventDefault();
  const data = {
   firstName: this.state.firstName,
   lastName: this.state.lastName,
   email: this.state.email,
   password: this.state.password
  }
  sendFormData(data).then(res=>{
    if(res.status===200){
      alert(res.data);
      this.props.history.push('/');
    }else{

    } 
  });
 }
render(){
return(
  <div className="container">
    <div className="card card-login mx-auto mt-5">
      <div className="card-header">Register here</div>
        <div className="card-body">
            <form id="signup-form">
              <div className="form-group">
                <div className="form-label-group">
                  <input type="text" id="firstname" name="firstname" className="form-control" placeholder="Enter firstname" onChange={(e)=>{this.handleChange(e)}} />
                  <label htmlFor="firstname">firstname</label>
                  {this.state.firstnameError ? <span style={{color: "red"}}>Please Enter some value</span> : ''} 
                </div>
              </div>
              <div className="form-group">
                <div className="form-label-group">
                  <input type="text" id="lastname" name="lastname" className="form-control" placeholder="Enter lastname" onChange={(e)=>{this.handleChange(e)}} />
                  <label htmlFor="lastname">lastname</label>
                  {this.state.lastnameError ? <span style={{color: "red"}}>Please Enter some value</span> : ''}
                </div>
              </div>
              <div className="form-group">
                <div className="form-label-group">
                  <input type="email" id="email" name="email" className="form-control" placeholder="Enter your email" onChange={(e)=>{this.handleChange(e)}} />
                  <label htmlFor="email">email</label>
                  {this.state.emailError ? <span style={{color: "red"}}>Please Enter valid email address</span> : ''}
                </div>
              </div>                
              <div className="form-group">
                <div className="form-label-group">
                  <input type="password" id="password" name="password" className="form-control" placeholder="Password" onChange={(e)=>{this.handleChange(e)}} />
                  <label htmlFor="password">Password</label>
                  {this.state.passwordError ? <span style={{color: "red"}}>Please enter some   value</span> : ''}
                </div>
              </div>                
              <button className="btn btn-primary btn-block" disabled={this.state.isDisabled} onClick={this.submitForm}>Signup</button>
            </form>
        </div>
      </div>
    </div>
  );
 }
}
export default Signup;

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

Scrolling a flexbox with overflowing content

The following CSS changes in bold (plus a bunch of content in the columns to test scrolling) will work. See the result in this Pen.

.content { flex: 1; display: flex; height: 1px; }

.column { padding: 20px; border-right: 1px solid #999; overflow: auto; }

The trick seems to be that a scrollable panel needs to have a height literally set somewhere (in this case, via its parent), not just determined by flexbox. So even height: 1px works. The flex-grow:1 will still size the panel to fit properly.

How to sort a list of lists by a specific index of the inner list?

Itemgetter lets you to sort by multiple criteria / columns:

sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))

List files ONLY in the current directory

You can use os.listdir for this purpose. If you only want files and not directories, you can filter the results using os.path.isfile.

example:

files = os.listdir(os.curdir)  #files and directories

or

files = filter(os.path.isfile, os.listdir( os.curdir ) )  # files only
files = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ] #list comprehension version.

Why dict.get(key) instead of dict[key]?

I will give a practical example in scraping web data using python, a lot of the times you will get keys with no values, in those cases you will get errors if you use dictionary['key'], whereas dictionary.get('key', 'return_otherwise') has no problems.

Similarly, I would use ''.join(list) as opposed to list[0] if you try to capture a single value from a list.

hope it helps.

[Edit] Here is a practical example:

Say, you are calling an API, which returns a JOSN file you need to parse. The first JSON looks like following:

{"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","submitdate_ts":1318794805,"users_id":"2674360","project_id":"1250499"}}

The second JOSN is like this:

{"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","users_id":"2674360","project_id":"1250499"}}

Note that the second JSON is missing the "submitdate_ts" key, which is pretty normal in any data structure.

So when you try to access the value of that key in a loop, can you call it with the following:

for item in API_call:
    submitdate_ts = item["bids"]["submitdate_ts"]

You could, but it will give you a traceback error for the second JSON line, because the key simply doesn't exist.

The appropriate way of coding this, could be the following:

for item in API_call:
    submitdate_ts = item.get("bids", {'x': None}).get("submitdate_ts")

{'x': None} is there to avoid the second level getting an error. Of course you can build in more fault tolerance into the code if you are doing scraping. Like first specifying a if condition

How do I make a semi transparent background?

Although dated, not one answer on this thread can be used universally. Using rgba to create transparent color masks - that doesn't exactly explain how to do so with background images.

My solution works for background images or color backgrounds.

_x000D_
_x000D_
#parent {_x000D_
    font-family: 'Open Sans Condensed', sans-serif;_x000D_
    font-size: 19px;_x000D_
    text-transform: uppercase;_x000D_
    border-radius: 50%;_x000D_
    margin: 20px auto;_x000D_
    width: 125px;_x000D_
    height: 125px;_x000D_
    background-color: #476172;_x000D_
    background-image: url('https://unsplash.it/200/300/?random');_x000D_
    line-height: 29px;_x000D_
    text-align:center;_x000D_
}_x000D_
_x000D_
#content {_x000D_
    color: white;_x000D_
    height: 125px !important;_x000D_
    width: 125px !important;_x000D_
    display: table-cell;_x000D_
    border-radius: 50%;_x000D_
    vertical-align: middle;_x000D_
    background: rgba(0,0,0, .3);_x000D_
}
_x000D_
<h1 id="parent"><a href="" id="content" title="content" rel="home">Example</a></h1>
_x000D_
_x000D_
_x000D_

How to use a dot "." to access members of dictionary?

I recently came across the 'Box' library which does the same thing.

Installation command : pip install python-box

Example:

from box import Box

mydict = {"key1":{"v1":0.375,
                    "v2":0.625},
          "key2":0.125,
          }
mydict = Box(mydict)

print(mydict.key1.v1)

I found it to be more effective than other existing libraries like dotmap, which generate python recursion error when you have large nested dicts.

link to library and details: https://pypi.org/project/python-box/

ALTER COLUMN in sqlite

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.

  1. BEGIN TRANSACTION;
  2. CREATE TEMPORARY TABLE t1_backup(a,b);
  3. INSERT INTO t1_backup SELECT a,b FROM t1;
  4. DROP TABLE t1;
  5. CREATE TABLE t1(a,b);
  6. INSERT INTO t1 SELECT a,b FROM t1_backup;
  7. DROP TABLE t1_backup;
  8. COMMIT

For more detail you can refer the link.

Converting ArrayList to HashMap

[edited]

using your comment about productCode (and assuming product code is a String) as reference...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }

How to Compare two Arrays are Equal using Javascript?

If you comparing 2 arrays but values not in same index, then try this

var array1=[1,2,3,4]
var array2=[1,4,3,2]
var is_equal = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(is_equal)

Depend on a branch or tag using a git URL in a package.json?

From the npm docs:

git://github.com/<user>/<project>.git#<branch>

git://github.com/<user>/<project>.git#feature\/<branch>

As of NPM version 1.1.65, you can do this:

<user>/<project>#<branch>

OWIN Startup Class Missing

Just check that your packages.config file is checked in (when excluded, there will be a red no-entry symbol shown in the explorer). For some bizarre reason mine was excluded and caused this issue.

How can I access a hover state in reactjs?

React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter and onMouseLeave. You then attach them to handlers in your component like so:

<ReactComponent
    onMouseEnter={() => this.someHandler}
    onMouseLeave={() => this.someOtherHandler}
/>

You'll then use some combination of state/props to pass changed state or properties down to your child React components.

Add an image in a WPF button

Try ContentTemplate:

<Button Grid.Row="2" Grid.Column="0" Width="20" Height="20"
        Template="{StaticResource SomeTemplate}">
    <Button.ContentTemplate>
        <DataTemplate>
            <Image Source="../Folder1/Img1.png" Width="20" />
        </DataTemplate>
    </Button.ContentTemplate>
</Button>

A potentially dangerous Request.Path value was detected from the client (*)

The * character is not allowed in the path of the URL, but there is no problem using it in the query string:

http://localhost:3286/Search/?q=test*

It's not an encoding issue, the * character has no special meaning in an URL, so it doesn't matter if you URL encode it or not. You would need to encode it using a different scheme, and then decode it.

For example using an arbitrary character as escape character:

query = query.Replace("x", "xxx").Replace("y", "xxy").Replace("*", "xyy");

And decoding:

query = query.Replace("xyy", "*").Replace("xxy", "y").Replace("xxx", "x");

How to get the current directory in a C program?

Look up the man page for getcwd.

What is the difference between signed and unsigned variables?

Signed variables use one bit to flag whether they are positive or negative. Unsigned variables don't have this bit, so they can store larger numbers in the same space, but only nonnegative numbers, e.g. 0 and higher.

For more: Unsigned and Signed Integers

How to enable curl in xampp?

It should be available in php.ini file. You need to un-comment the line for curl extension:

  ;extension=php_curl.dll
  ^----- remove semi-colon

changing default x range in histogram matplotlib

plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

CSS opacity only to background color, not the text on it?

The easiest solution is to create 3 divs. One that will contain the other 2, the one with transparent background and the one with content. Make the first div's position relative and set the one with transparent background to negative z-index, then adjust the position of the content to fit over the transparent background. This way you won't have issues with absolute positioning.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Select Into functionality only works for PL/SQL Block, when you use Execute immediate , oracle interprets v_query_str as a SQL Query string so you can not use into .will get keyword missing Exception. in example 2 ,we are using begin end; so it became pl/sql block and its legal.

scrollable div inside container

If you put overflow: scroll on a fixed height div, the div will scroll if the contents take up too much space.

Using env variable in Spring Boot's application.properties

Here is a snippet code through a chain of environments properties files are being loaded for different environments.

Properties file under your application resources ( src/main/resources ):-

 1. application.properties
 2. application-dev.properties
 3. application-uat.properties
 4. application-prod.properties

Ideally, application.properties contains all common properties which are accessible for all environments and environment related properties only works on specifies environment. therefore the order of loading these properties files will be in such way -

 application.properties -> application.{spring.profiles.active}.properties.

Code snippet here :-

    import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;

    public class PropertiesUtils {

        public static final String SPRING_PROFILES_ACTIVE = "spring.profiles.active";

        public static void initProperties() {
            String activeProfile = System.getProperty(SPRING_PROFILES_ACTIVE);
            if (activeProfile == null) {
                activeProfile = "dev";
            }
            PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer
                    = new PropertySourcesPlaceholderConfigurer();
            Resource[] resources = new ClassPathResource[]
                    {new ClassPathResource("application.properties"),
                            new ClassPathResource("application-" + activeProfile + ".properties")};
            propertySourcesPlaceholderConfigurer.setLocations(resources);

        }
    }

Rename package in Android Studio

Right-click on the package at the Project Panel.

Choose Refactor -> Rename from the context menu.

How to find the 'sizeof' (a pointer pointing to an array)?

The answer is, "No."

What C programmers do is store the size of the array somewhere. It can be part of a structure, or the programmer can cheat a bit and malloc() more memory than requested in order to store a length value before the start of the array.

How do I convert a dictionary to a JSON String in C#?

Serializing data structures containing only numeric or boolean values is fairly straightforward. If you don't have much to serialize, you can write a method for your specific type.

For a Dictionary<int, List<int>> as you have specified, you can use Linq:

string MyDictionaryToJson(Dictionary<int, List<int>> dict)
{
    var entries = dict.Select(d =>
        string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
    return "{" + string.Join(",", entries) + "}";
}

But, if you are serializing several different classes, or more complex data structures, or especially if your data contains string values, you would be better off using a reputable JSON library that already knows how to handle things like escape characters and line breaks. Json.NET is a popular option.

How do I find out what type each object is in a ArrayList<Object>?

instead of using object.getClass().getName() you can use object.getClass().getSimpleName(), because it returns a simple class name without a package name included.

for instance,

Object[] intArray = { 1 }; 

for (Object object : intArray) { 
    System.out.println(object.getClass().getName());
    System.out.println(object.getClass().getSimpleName());
}

gives,

java.lang.Integer
Integer

Behaviour of increment and decrement operators in Python

Python does not have these operators, but if you really need them you can write a function having the same functionality.

def PreIncrement(name, local={}):
    #Equivalent to ++name
    if name in local:
        local[name]+=1
        return local[name]
    globals()[name]+=1
    return globals()[name]

def PostIncrement(name, local={}):
    #Equivalent to name++
    if name in local:
        local[name]+=1
        return local[name]-1
    globals()[name]+=1
    return globals()[name]-1

Usage:

x = 1
y = PreIncrement('x') #y and x are both 2
a = 1
b = PostIncrement('a') #b is 1 and a is 2

Inside a function you have to add locals() as a second argument if you want to change local variable, otherwise it will try to change global.

x = 1
def test():
    x = 10
    y = PreIncrement('x') #y will be 2, local x will be still 10 and global x will be changed to 2
    z = PreIncrement('x', locals()) #z will be 11, local x will be 11 and global x will be unaltered
test()

Also with these functions you can do:

x = 1
print(PreIncrement('x'))   #print(x+=1) is illegal!

But in my opinion following approach is much clearer:

x = 1
x+=1
print(x)

Decrement operators:

def PreDecrement(name, local={}):
    #Equivalent to --name
    if name in local:
        local[name]-=1
        return local[name]
    globals()[name]-=1
    return globals()[name]

def PostDecrement(name, local={}):
    #Equivalent to name--
    if name in local:
        local[name]-=1
        return local[name]+1
    globals()[name]-=1
    return globals()[name]+1

I used these functions in my module translating javascript to python.

What is the best way to calculate a checksum for a file that is on my machine?

Any MD5 will produce a good checksum to verify the file. Any of the files listed at the bottom of this page will work fine. http://en.wikipedia.org/wiki/Md5sum

How to define custom sort function in javascript?

function msort(arr){
    for(var i =0;i<arr.length;i++){
        for(var j= i+1;j<arr.length;j++){
            if(arr[i]>arr[j]){
                var swap = arr[i];
                arr[i] = arr[j];
                arr[j] = swap;
            }
        }
    }
return arr;
}

Date ticks and rotation in matplotlib

Simply use

ax.set_xticklabels(label_list, rotation=45)

How to know function return type and argument types?

This is how dynamic languages work. It is not always a good thing though, especially if the documentation is poor - anyone tried to use a poorly documented python framework? Sometimes you have to revert to reading the source.

Here are some strategies to avoid problems with duck typing:

  • create a language for your problem domain
  • this will help you to name stuff properly
  • use types to represent concepts in your domain language
  • name function parameters using the domain language vocabulary

Also, one of the most important points:

  • keep data as local as possible!

There should only be a few well-defined and documented types being passed around. Anything else should be obvious by looking at the code: Don't have weird parameter types coming from far away that you can't figure out by looking in the vicinity of the code...

Related, (and also related to docstrings), there is a technique in python called doctests. Use that to document how your methods are expected to be used - and have nice unit test coverage at the same time!

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

I first changed the root password running mysql at a prompt with

mysql -u root -p

Update password:

UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';

Edited line in the file config.inc.php with the new root password:

$cfg['Servers'][$i]['password'] = 'MyNewPass'

Stop and re-start mysql service (in Windows: mysql_stop.bat/mysql_start.bat)

and got phpMyAdmin to work!

EDIT 2017: for MySQL=5.7 use authentication_string in place of Password (see this answer):

UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE User='root';