Programs & Examples On #Typeinfo

How to parse JSON with VBA without external libraries?

Call me simple but I just declared a Variant and split the responsetext from my REST GET on the quote comma quote between each item, then got the value I wanted by looking for the last quote with InStrRev. I'm sure that's not as elegant as some of the other suggestions but it works for me.

         varLines = Split(.responsetext, """,""")
        strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)

How to export a CSV to Excel using Powershell

Ups, I entirely forgot this question. In the meantime I got a solution.
This Powershell script converts a CSV to XLSX in the background

Gimmicks are

  • Preserves all CSV values as plain text like =B1+B2 or 0000001.
    You don't see #Name or anything like that. No autoformating is done.
  • Automatically chooses the right delimiter (comma or semicolon) according to your regional setting
  • Autofit columns

PowerShell Code

### Set input and output path
$inputCSV = "C:\somefolder\input.csv"
$outputXLSX = "C:\somefolder\output.xlsx"

### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($

### Set the delimiter (, or ;) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(5)

### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

### Execute & delete the import query

### Save & close the Workbook as XLSX. Change the output extension for Excel 2003

Converting LastLogon to DateTime format

DateTime.FromFileTime should do the trick:

PS C:\> [datetime]::FromFileTime(129948127853609000)

Monday, October 15, 2012 3:13:05 PM

Then depending on how you want to format it, check out standard and custom datetime format strings.

PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('d MMMM')
15 October
PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('g')
10/15/2012 3:13 PM

If you want to integrate this into your one-liner, change your select statement to this:

... | Select Name, manager, @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}} | ...

Cannot construct instance of - Jackson

For me there was no default constructor defined for the POJOs I was trying to use. creating default constructor fixed it.

public class TeamCode {

    private String value;

    public String getValue() {
        return value;

    **public TeamCode() {

    public TeamCode(String value) {
        this.value = value;

    public String toString() {
        return "TeamCode{" +
                "value='" + value + '\'' +

    public void setValue(String value) {
        this.value = value;


I can't understand why this JAXB IllegalAnnotationException is thrown

In my case, I was able to find the problem by temporarily catching the exception, descending into causes as needed (based on how deep the IllegalAnnotationException was), and calling getErrors() on it.

    try {
        // in my case, this was what gave me an exception
    // I got a WebServiceException caused by another exception, which was caused by the IllegalAnnotationsException
    } catch (WebServiceException e) {
        // Incidentally, I need to call getCause().getCause() on it, and cast to IllegalAnnotationsException before calling getErrors()

Parsing JSON in Excel VBA

Simpler way you can go array.myitem(0) in VB code

my full answer here parse and stringify (serialize)

Use the 'this' object in js

ScriptEngine.AddCode "Object.prototype.myitem=function( i ) { return this[i] } ; "

Then you can go array.myitem(0)

Private ScriptEngine As ScriptControl

Public Sub InitScriptEngine()
    Set ScriptEngine = New ScriptControl
    ScriptEngine.Language = "JScript"
    ScriptEngine.AddCode "Object.prototype.myitem=function( i ) { return this[i] } ; "
    Set foo = ScriptEngine.Eval("(" + "[ 1234, 2345 ]" + ")") ' JSON array
    Debug.Print foo.myitem(1) ' method case sensitive!
    Set foo = ScriptEngine.Eval("(" + "{ ""key1"":23 , ""key2"":2345 }" + ")") ' JSON key value
    Debug.Print foo.myitem("key1") ' WTF

End Sub

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference:

typeid Reference:

C++ static virtual members?

Many say it is not possible, I would go one step further and say it is not meaningfull.

A static member is something that does not relate to any instance, only to the class.

A virtual member is something that does not relate directly to any class, only to an instance.

So a static virtual member would be something that does not relate to any instance or any class.

g++ undefined reference to typeinfo

The previous answers are correct, but this error can also be caused by attempting to use typeid on an object of a class that has no virtual functions. C++ RTTI requires a vtable, so classes that you wish to perform type identification on require at least one virtual function.

If you want type information to work on a class for which you don't really want any virtual functions, make the destructor virtual.

Limit to 2 decimal places with a simple pipe

Well now will be different after angular 5:

{{ number | currency :'GBP':'symbol':'1.2-2' }}

Get spinner selected items text?

use this

import java.util.ArrayList;   
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class dynamic_spinner_main extends Activity {

    private Spinner m_myDynamicSpinner;
    private EditText m_addItemText;
    private ArrayAdapter<CharSequence> m_adapterForSpinner;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

        //grab our UI elements so we can manipulate them (in the case of the Spinner)
        //    or add listeners to them (in the case of the buttons)
        m_myDynamicSpinner = (Spinner)findViewById(;        
        m_addItemText = (EditText)findViewById(;
        Button addButton = (Button)findViewById(;
        Button clearButton = (Button)findViewById(;

        //create an arrayAdapter an assign it to the spinner
        m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
        m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // your code here
                Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
                mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
                System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());

            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here

        //add listener for addButton
        addButton.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {               

        //add listener for addButton
        clearButton.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {

    private void addNewSpinnerItem() {
        CharSequence textHolder = "" + m_addItemText.getText();

    private void clearSpinnerItems() {
        m_adapterForSpinner.add("dummy item");


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

    <EditText android:layout_height="wrap_content" 
    <Button android:layout_height="wrap_content" 
            android:text="Add To Spinner"></Button>
    <Button android:layout_height="wrap_content" 
            android:text="Clear Spinner Items"></Button>
    <Spinner android:layout_height="wrap_content" 

Cannot find vcvarsall.bat when running a Python script

There is a confusing edge case for this on windows. If you follow the advice to install the 2007 windows, and you still get this error when doing python install directly, then it may be that the uses the old version of set up tools.

In particular, the code that points windows towards the right location for the windows installed compiler is in the __init__ method of the setuptools library, which means that you must in your use the setuptools module. Some older call methods directly from distutils.core. If this is the case then the will never find the windows installed compiler. This can be fixed by simply writing import setuptools as the first line of the file.

Reference: Look about half way down for the quote from steve dower:

Setuptools has the code to find the compiler package. We deliberately put it there instead of in distutils to make sure more people would get it. I should probably port the extra check into 2.7.10, but the immediate fix is to import setuptools.

Fail to create Android virtual Device, "No system image installed for this Target"

In order to create an Android Wear emulator you need to follow the instructions below:

  1. If your version of Android SDK Tools is lower than 22.6, you must update

  2. Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.

  3. Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.

Below is the snapshot of what it should look like:


Then you must check the following in order to create a Wearable AVD:

  1. For the Device, select Android Wear Square or Android Wear Round.

  2. For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).

  3. For the CPU/ABI, select Android Wear ARM (armeabi-v7a).

  4. For the Skin, select AndroidWearSquare or AndroidWearRound.

  5. Leave all other options set to their defaults and click OK.


Then you are good to go. For more information you can always refer to the developer site.

JavaScript - populate drop down list with array

Something like this should work:

var dropdown = document.getElementById("dropdown1");
if (dropdown) {
    for (var i=0; i < month.length;++i){    
        addOption(dropdown, month[i], month[i]);

addOption = function(selectbox, text, value) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;

You can refer to this article for more details:

could not extract ResultSet in hibernate

I was using Spring Data JPA with PostgreSql and during UPDATE call it was showing errors-

  • 'could not extract ResultSet' and another one.
  • org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query. (Showing Transactional required.)

Actually, I was missing two required Annotations.

  • @Transactional and
  • @Modifying


@Query(vlaue = " UPDATE DB.TABLE SET Col1 = ?1 WHERE id = ?2 ", nativeQuery = true)
void updateCol1(String value, long id);

What does <value optimized out> mean in gdb?

You need to turn off the compiler optimisation.

If you are interested in a particular variable in gdb, you can delare the variable as "volatile" and recompile the code. This will make the compiler turn off compiler optimization for that variable.

volatile int quantity = 0;

Display open transactions in MySQL

By using this query you can see all open transactions.

List All:


if you want to kill a hang transaction copy transaction id and kill transaction by using this command:

KILL <id>    // e.g KILL 16543

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces


Removes only the leading & trailing spaces.

From Java Doc, "Returns a string whose value is this string, with any leading and trailing whitespace removed."

System.out.println(" D ev  Dum my ".trim());

"D ev Dum my"

replace(), replaceAll()

Replaces all the empty strings in the word,

System.out.println(" D ev  Dum my ".replace(" ",""));

System.out.println(" D ev  Dum my ".replaceAll(" ",""));

System.out.println(" D ev  Dum my ".replaceAll("\\s+",""));





Note: "\s+" is the regular expression similar to the empty space character.

Reference :

Disable sorting for a particular column in jQuery DataTables

"aoColumnDefs" : [   
  'bSortable' : false,  
  'aTargets' : [ 0 ]

Here 0 is the index of the column, if you want multiple columns to be not sorted, mention column index values seperated by comma(,)

Calculate distance between two points in google maps V3

It's Quite easy using Google Distance Matrix service

First step is to activate Distance Matrix service from google API console. it returns distances between a set of locations. And apply this simple function

function initMap() {
        var bounds = new google.maps.LatLngBounds;
        var markersArray = [];

        var origin1 = {lat:23.0203, lng: 72.5562};
        //var origin2 = 'Ahmedabad, India';
        var destinationA = {lat:23.0436503, lng: 72.55008939999993};
        //var destinationB = {lat: 23.2156, lng: 72.6369};

        var destinationIcon = '' +
        var originIcon = '' +
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 55.53, lng: 9.4},
          zoom: 10
        var geocoder = new google.maps.Geocoder;

        var service = new google.maps.DistanceMatrixService;
          origins: [origin1],
          destinations: [destinationA],
          travelMode: 'DRIVING',
          unitSystem: google.maps.UnitSystem.METRIC,
          avoidHighways: false,
          avoidTolls: false
        }, function(response, status) {
          if (status !== 'OK') {
            alert('Error was: ' + status);
          } else {
            var originList = response.originAddresses;
            var destinationList = response.destinationAddresses;
            var outputDiv = document.getElementById('output');
            outputDiv.innerHTML = '';

            var showGeocodedAddressOnMap = function(asDestination) {
              var icon = asDestination ? destinationIcon : originIcon;
              return function(results, status) {
                if (status === 'OK') {
                  markersArray.push(new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    icon: icon
                } else {
                  alert('Geocode was not successful due to: ' + status);

            for (var i = 0; i < originList.length; i++) {
              var results = response.rows[i].elements;
              geocoder.geocode({'address': originList[i]},
              for (var j = 0; j < results.length; j++) {
                geocoder.geocode({'address': destinationList[j]},
                //outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] + ': ' + results[j].distance.text + ' in ' +                    results[j].duration.text + '<br>';
                outputDiv.innerHTML += results[j].distance.text + '<br>';


Where origin1 is your location and destinationA is destindation can add above two or more data.

Rad Full Documentation with an example

html5 - canvas element - Multiple layers

but layer 02, will cover all drawings in layer 01. I used this to show drawing in both layers. use (background-color: transparent;) in style.

    <div style="position: relative;"> _x000D_
      <canvas id="lay01" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 0; background-color: transparent;">_x000D_
      </canvas> _x000D_
      <canvas id="lay02" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 1; background-color: transparent;">_x000D_

Run .jar from batch-file

inside .bat file format


-------set java classpath and give jar location-------- set classpath=%CLASSPATH%;../lib/MoveFiles.jar;

---------mention your fully classified name of java class to run, which was given in jar------ Java com.mits.MoveFiles pause

Can we write our own iterator in Java?

Here is the complete answer to the question.

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

class ListIterator implements Iterator<String>{
    List<String> list;
    int pos = 0;

    public ListIterator(List<String> list) {
        this.list = list;

    public boolean hasNext() {
        while(pos < list.size()){
            if (list.get(pos).startsWith("a"))
                return true;
        return false;


    public String next() {
        if (hasNext())
            return list.get(pos++);
        throw new NoSuchElementException();

public class IteratorTest {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("alice", "bob", "abigail", "charlie");
        ListIterator itr = new ListIterator(list);

            System.out.println(; // prints alice, abigail
  • ListIterator is the iterator for the array which returns the elements that start with 'a'.
  • There is no need for implementing an Iterable interface. But that is a possibility.
  • There is no need to implement this generically.
  • It fully satisfies the contract for hasNext() and next(). ie if hasNext() says there are still elements, next() will return those elements. And if hasNext() says no more elements, it returns a valid NoSuchElementException exception.

How do I get list of all tables in a database using TSQL?

FROM sysobjects sobjects
WHERE sobjects.xtype = 'U'

Here is a list of other object types you can search for as well:

  • AF: Aggregate function (CLR)
  • C: CHECK constraint
  • D: Default or DEFAULT constraint
  • F: FOREIGN KEY constraint
  • L: Log
  • FN: Scalar function
  • FS: Assembly (CLR) scalar-function
  • FT: Assembly (CLR) table-valued function
  • IF: In-lined table-function
  • IT: Internal table
  • P: Stored procedure
  • PC: Assembly (CLR) stored-procedure
  • PK: PRIMARY KEY constraint (type is K)
  • RF: Replication filter stored procedure
  • S: System table
  • SN: Synonym
  • SQ: Service queue
  • TA: Assembly (CLR) DML trigger
  • TF: Table function
  • TR: SQL DML Trigger
  • TT: Table type
  • U: User table
  • UQ: UNIQUE constraint (type is K)
  • V: View
  • X: Extended stored procedure

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

What is the HTML5 equivalent to the align attribute in table cells?

If they're block level elements they won't be affected by text-align: center;. Someone may have set img { display: block; } and that's throwing it out of whack. You can try:

td { text-align: center; }
td * { display: inline; }

and if it looks as desired you should definitely replace * with the desired elements like:

td img, td foo { display: inline; }

Android Reading from an Input stream efficiently

Possibly somewhat faster than Jaime Soriano's answer, and without the multi-byte encoding problems of Adrian's answer, I suggest:

File file = new File("/tmp/myfile");
try {
    FileInputStream stream = new FileInputStream(file);

    int count;
    byte[] buffer = new byte[1024];
    ByteArrayOutputStream byteStream =
        new ByteArrayOutputStream(stream.available());

    while (true) {
        count =;
        if (count <= 0)
        byteStream.write(buffer, 0, count);

    String string = byteStream.toString();
    System.out.format("%d bytes: \"%s\"%n", string.length(), string);
} catch (IOException e) {

Hide axis values but keep axis tick labels in matplotlib

Without a subplots, you can universally remove the ticks like this:


Run a PostgreSQL .sql file using command line arguments

If you are logged in into psql on the Linux shell the command is:

\i fileName.sql

for an absolute path and

\ir filename.sql

for the relative path from where you have called psql.

relative path to CSS file


Absolute: The browser will always interpret / as the root of the hostname. For example, if my site was and I specified /css/images.css then it would search for that at If your project root was actually at /myproject/ it would not find the css file. Therefore, you need to determine where your project folder root is relative to the hostname, and specify that in your href notation.

Relative: If you want to reference something you know is in the same path on the url - that is, if it is in the same folder, for example and, and you know that it will always be this way, you can go against convention and specify a relative path by not putting a leading / in front of your path, for example, css/style.css.

Filesystem Notations: Additionally, you can use standard filesystem notations like ... If you do it would be the same as If you want to reference something that is one directory up from your file, use ../myFile.css.

Your Specific Case

In your case, you have two options:

  • <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
  • <link rel="stylesheet" type="text/css" href="css/styles.css"/>

The first will be more concrete and compatible if you move things around, however if you are planning to keep the file in the same location, and you are planning to remove the /ServletApp/ part of the URL, then the second solution is better.

How to Consolidate Data from Multiple Excel Columns All into One Column

You didn't mention if you are using Excel 2003 or 2007, but you may run into an issue with the # of rows in Excel 2003 being capped at 65,536. If you are using 2007, the limit is 1,048,576.

Also, can I ask what your end goal is for your analysis? If you need to perform many statistical calculations on your data, I would recommend moving out of the Excel environment into something that is more directly suited for data manipulation and analysis, such as R.

There are a variety of options for connecting R to Excel, including

  1. RExcel
  2. RODBC
  3. Other options in the R manual

Regardless of what you choose to use to move data in/out of R, the code to change from wide to long format is pretty trivial. I enjoy the melt() function from the reshape package. That code would look like:

#Fake data, 4 columns, 20k rows
df <- data.frame(foo = rnorm(20000)
    , bar = rlnorm(20000)
    , fee = rnorm(20000)
    , fie = rlnorm(20000)
#Create new object with 1 column, 80k rows
df.m <- melt(df)

From there, you can perform any number of statistical or graphing operations. If you use the RExcel plugin above, you can fire all of this up and run it within Excel itself. The R community is very active and can help address any and all questions you may encounter.

Good luck!

dplyr change many data types

Dplyr across function has superseded _if, _at, and _all. See vignette("colwise").

dat %>% 
mutate(across(all_of(l1), as.factor),
       across(all_of(l2), as.numeric))

Uninstalling an MSI file from the command line without using msiexec

Short answer: you can't. Use MSIEXEC /x

Long answer: When you run the MSI file directly at the command line, all that's happening is that it runs MSIEXEC for you. This association is stored in the registry. You can see a list of associations by (in Windows Explorer) going to Tools / Folder Options / File Types.

For example, you can run a .DOC file from the command line, and WordPad or WinWord will open it for you.

If you look in the registry under HKEY_CLASSES_ROOT\.msi, you'll see that .MSI files are associated with the ProgID "Msi.Package". If you look in HKEY_CLASSES_ROOT\Msi.Package\shell\Open\command, you'll see the command line that Windows actually uses when you "run" a .MSI file.

Filtering a list based on a list of booleans

With numpy:

In [128]: list_a = np.array([1, 2, 4, 6])
In [129]: filter = np.array([True, False, True, False])
In [130]: list_a[filter]

Out[130]: array([1, 4])

or see Alex Szatmary's answer if list_a can be a numpy array but not filter

Numpy usually gives you a big speed boost as well

In [133]: list_a = [1, 2, 4, 6]*10000
In [134]: fil = [True, False, True, False]*10000
In [135]: list_a_np = np.array(list_a)
In [136]: fil_np = np.array(fil)

In [139]: %timeit list(itertools.compress(list_a, fil))
1000 loops, best of 3: 625 us per loop

In [140]: %timeit list_a_np[fil_np]
10000 loops, best of 3: 173 us per loop

VBA Excel - Insert row below with same format including borders and frames

When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.

I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).

I've found three workarounds that don't require copying the formatting from the source row:

  1. Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)

  2. Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:

    • Conditional formatting borders are limited to the thin-weight lines.
    • Works best for sheets where borders are relatively consistent so you don't have to create a bunch of conditional formatting rules.
  3. Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).

Passing a string with spaces as a function argument in bash

Another solution to the issue above is to set each string to a variable, call the function with variables denoted by a literal dollar sign \$. Then in the function use eval to read the variable and output as expected.


  eval string1="$1"
  eval string2="$2"
  eval string3="$3"

  echo "string1 = ${string1}"
  echo "string2 = ${string2}"
  echo "string3 = ${string3}"

var2="second string with spaces"

myFunction "\${var1}" "\${var2}" "\${var3}"

exit 0

Output is then:

    string1 = firstString
    string2 = second string with spaces
    string3 = thirdString

In trying to solve a similar problem to this, I was running into the issue of UNIX thinking my variables were space delimeted. I was trying to pass a pipe delimited string to a function using awk to set a series of variables later used to create a report. I initially tried the solution posted by ghostdog74 but could not get it to work as not all of my parameters were being passed in quotes. After adding double-quotes to each parameter it then began to function as expected.

Below is the before state of my code and fully functioning after state.

Before - Non Functioning Code


# Setup Function To Extract Each Field For The Error Report

  # Retrieves Column ${fieldNumber} From The Pipe Delimited ${detailedString} 
  #   And Strips Leading And Trailing Spaces
  echo ${detailedString} | awk -F '|' -v VAR=${fieldNumber} '{ print $VAR }' | sed 's/^[ \t]*//;s/[ \t]*$//'

while read LINE

  # Below Does Not Work Since There Are Not Quotes Around The 3
  iputId=$(getField "${var1}" 3)

exit 0

After - Functioning Code


# Setup Function To Extract Each Field For The Report

  # Retrieves Column ${fieldNumber} From The Pipe Delimited ${detailedString} 
  #   And Strips Leading And Trailing Spaces
  echo ${detailedString} | awk -F '|' -v VAR=${fieldNumber} '{ print $VAR }' | sed 's/^[ \t]*//;s/[ \t]*$//'

while read LINE

  # Below Now Works As There Are Quotes Around The 3
  iputId=$(getField "${var1}" "3")

exit 0

Looking for a 'cmake clean' command to clear up CMake output

In the case where you pass -D parameters into CMake when generating the build files and don't want to delete the entire build/ directory:

Simply delete the CMakeFiles/ directory inside your build directory.

rm -rf CMakeFiles/
cmake --build .

This causes CMake to rerun, and build system files are regenerated. Your build will also start from scratch.

How to change the server port from 3000?

If you don't have bs-config.json, you can change the port inside the lite-server module. Go to node_modules/lite-server/lib/config-defaults.js in your project, then add the port in "modules.export" like this.

module.export {
    port :8000, // to any available port

Then you can restart the server.

Floating point inaccuracy examples

A cute piece of numerical weirdness may be observed if one converts 9999999.4999999999 to a float and back to a double. The result is reported as 10000000, even though that value is obviously closer to 9999999, and even though 9999999.499999999 correctly rounds to 9999999.

PreparedStatement IN clause alternatives?

There are different alternative approaches that we can use for IN clause in PreparedStatement.

  1. Using Single Queries - slowest performance and resource intensive
  2. Using StoredProcedure - Fastest but database specific
  3. Creating dynamic query for PreparedStatement - Good Performance but doesn't get benefit of caching and PreparedStatement is recompiled every time.
  4. Use NULL in PreparedStatement queries - Optimal performance, works great when you know the limit of IN clause arguments. If there is no limit, then you can execute queries in batch. Sample code snippet is;

        int i = 1;
        for(; i <=ids.length; i++){
            ps.setInt(i, ids[i-1]);
        //set null for remaining ones
        for(; i<=PARAM_SIZE;i++){
            ps.setNull(i, java.sql.Types.INTEGER);

You can check more details about these alternative approaches here.

How to make several plots on a single page using matplotlib?

@doug & FS.'s answer are very good solutions. I want to share the solution for iteration on pandas.dataframe.

import pandas as pd
df=pd.DataFrame([[1, 2], [3, 4], [4, 3], [2, 3]])
fig = plt.figure(figsize=(14,8))
for i in df.columns:

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    return false;

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}



(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:


Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:


This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.

Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
# The new string is obtained by removing the prefix a from string

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

Adjusting HttpWebRequest Connection Timeout in C#

Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.

From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:

I Set:


The connect and post time for the HttpWebRequest took 26ms

but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.

I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.

For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

Open a Web Page in a Windows Batch FIle

Unfortunately, the best method to approach this is to use Internet Explorer as it's a browser that is guaranteed to be on Windows based machines. This will also bring compatibility of other users which might have alternative browsers such as Firefox, Chrome, Opera..etc,

start "iexplore.exe"

Most efficient way to prepend a value to an array

I'm not sure about more efficient in terms of big-O but certainly using the unshift method is more concise:

var a = [1, 2, 3, 4];
a; // => [0, 1, 2, 3, 4]


This jsPerf benchmark shows that unshift is decently faster in at least a couple of browsers, regardless of possibly different big-O performance if you are ok with modifying the array in-place. If you really can't mutate the original array then you would do something like the below snippet, which doesn't seem to be appreciably faster than your solution:

a.slice().unshift(0); // Use "slice" to avoid mutating "a".

[Edit 2]

For completeness, the following function can be used instead of OP's example prependArray(...) to take advantage of the Array unshift(...) method:

function prepend(value, array) {
  var newArray = array.slice();
  return newArray;

var x = [1, 2, 3];
var y = prepend(0, x);
y; // => [0, 1, 2, 3];
x; // => [1, 2, 3];

How to make a redirection on page load in JSF 1.x

FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();

How do you stop tracking a remote branch in Git?

As mentioned in Yoshua Wuyts' answer, using git branch:

git branch --unset-upstream

Other options:

You don't have to delete your local branch.

Simply delete the local branch that is tracking the remote branch:

git branch -d -r origin/<remote branch name>

-r, --remotes tells git to delete the remote-tracking branch (i.e., delete the branch set to track the remote branch). This will not delete the branch on the remote repo!

See "Having a hard time understanding git-fetch"

there's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo

As mentioned in Dobes Vandermeer's answer, you also need to reset the configuration associated to the local branch:

git config --unset branch.<branch>.remote
git config --unset branch.<branch>.merge

Remove the upstream information for <branchname>.
If no branch is specified it defaults to the current branch.

(git 1.8+, Oct. 2012, commit b84869e by Carlos Martín Nieto (carlosmn))

That will make any push/pull completely unaware of origin/<remote branch name>.

How to add an Android Studio project to GitHub

  1. Sign up and create a GitHub account in
  2. Download git from and install it in your system.
  3. Open the project in android studio and go to File -> Settings -> Version Control -> Git.
  4. Click on test button to test "path to Git executables". If successful message is shown everything is ok, else navigate to git.exe from where you installed git and test again.
  5. Go to File -> Settings -> Version Control -> GitHub. Enter your email and password used to create GitHub account and click on OK button.
  6. Then go to VCS -> Import into Version Control -> Share Project on GitHub. Enter Repository name, Description and click Share button.
  7. In the next window check all files inorder to add files for initial commit and click OK.
  8. Now the project will be uploaded to the GitHub repository and when uploading is finished we will get a message in android studio showing "Successfully shared project on GitHub". Click on the link provided in that message to go to GitHub repository.

Using $_POST to get select option value from HTML

Use this way:

$selectOption = $_POST['taskOption'];

But it is always better to give values to your <option> tags.

<select name="taskOption">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>

The difference between Classes, Objects, and Instances

Java (and any other programming language) is modeled in terms of types and values. At the theoretical level, a value is a representation for some quantum of information, and a type is a set of values. When we say value X is an instance of type Y, we are simply saying that X is a member of the set of values that is the type Y.

So that's what the term "instance" really means: it describes a relationship not a thing.

The type system of the Java programming language supports two kinds of types, primitive types and reference types. The reference types are further divided into the classes and array types. A Java object is an instance of a reference type.

An object is a class instance or an array. (JLS 4.3.1)

That's the type theoretic view.

In practice, most Java developers treat the words "instance" and "object" as synonyms. (And that includes me then I'm trying to explain something quickly.) And most developers use the word "value" rather than "instance" to refer to an instance of a primitive type.

curl posting with header application/x-www-form-urlencoded

// A very simple PHP example that sends a HTTP POST to a remote site

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { ... } else { ... }


How to get rid of blank pages in PDF exported from SSRS

In BIDS or SSDT-BI, do the following:

  1. Click on Report > Report Properties > Layout tab (Page Setup tab in SSDT-BI)
  2. Make a note of the values for Page width, Left margin, Right margin
  3. Close and go back to the design surface
  4. In the Properties window, select Body
  5. Click the + symbol to expand the Size node
  6. Make a note of the value for Width

To render in PDF correctly Body Width + Left margin + Right margin must be less than or equal to Page width. When you see blank pages being rendered it is almost always because the body width plus margins is greater than the page width.

Remember: (Body Width + Left margin + Right margin) <= (Page width)

Equal height rows in a flex container

You can accomplish that now with display: grid:

.list {_x000D_
  display: grid;_x000D_
  overflow: hidden;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-auto-rows: 1fr;_x000D_
  grid-column-gap: 5px;_x000D_
  grid-row-gap: 5px;_x000D_
  max-width: 500px;_x000D_
.list-item {_x000D_
  background-color: #ccc;_x000D_
  display: flex;_x000D_
  padding: 0.5em;_x000D_
  margin-bottom: 20px;_x000D_
.list-content {_x000D_
  width: 100%;_x000D_
<ul class="list">_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h2>box 1</h2>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor</p>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor</p>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_

Although the grid itself is not flexbox, it behaves very similar to a flexbox container, and the items inside the grid can be flex.

The grid layout is also very handy in the case you want responsive grids. That is, if you want the grid to have a different number of columns per row you can then just change grid-template-columns:

grid-template-columns: repeat(1, 1fr); // 1 column
grid-template-columns: repeat(2, 1fr); // 2 columns
grid-template-columns: repeat(3, 1fr); // 3 columns

and so on...

You can mix it with media queries and change according to the size of the page.

Sadly there is still no support for container queries / element queries in the browsers (out of the box) to make it work well with changing the number of columns according to the container size, not to the page size (this would be great to use with reusable webcomponents).

More information about the grid layout:

Support of the Grid Layout accross browsers:

How To Change DataType of a DataColumn in a DataTable?

Old post, but I thought I'd weigh in, with a DataTable extension that can convert a single column at a time, to a given type:

public static class DataTableExt
    public static void ConvertColumnType(this DataTable dt, string columnName, Type newType)
        using (DataColumn dc = new DataColumn(columnName + "_new", newType))
            // Add the new column which has the new type, and move it to the ordinal of the old column
            int ordinal = dt.Columns[columnName].Ordinal;

            // Get and convert the values of the old column, and insert them into the new
            foreach (DataRow dr in dt.Rows)
                dr[dc.ColumnName] = Convert.ChangeType(dr[columnName], newType);

            // Remove the old column

            // Give the new column the old column's name
            dc.ColumnName = columnName;

It can then be called like this:

MyTable.ConvertColumnType("MyColumnName", typeof(int));

Of course using whatever type you desire, as long as each value in the column can actually be converted to the new type.

How to kill all processes matching a name?

The safe way to do this is:

pkill -f amarok

jQuery ui dialog change title after load-callback

Using dialog methods:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

Or directly, hacky though:

$("span.ui-dialog-title").text('My New Title'); 

For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library:

Difference in months between two dates

public partial class Form1 : Form
    public Form1()

    private void button1_Click(object sender, EventArgs e)

        label3.Text = new DateDifference(Convert.ToDateTime("2018-09-13"), Convert.ToDateTime("2018-11-15")).ToString();
        label2.Text = new DateDifference(Convert.ToDateTime("2018-10-12"), Convert.ToDateTime("2018-11-15")).ToString();

        DateDifference oDateDifference = new DateDifference(Convert.ToDateTime("2018-11-12"));
       label1.Text  =   oDateDifference.ToString();


public class DateDifference
    public DateTime start { get; set; }
    public DateTime currentDAte { get; set; }
    public DateTime origstart { get; set; }
    public DateTime origCurrentDAte { get; set; }

    int days { get; set; }
    int months { get; set; }
    int years { get; set; }

    public DateDifference(DateTime postedDate, DateTime currentDAte)
        this.start = this.removeTime(postedDate);
        this.currentDAte = this.removeTime(currentDAte);
        this.origstart = postedDate;
        this.origCurrentDAte = currentDAte;


    public DateDifference(DateTime postedDate)
        DateTime currentDate_ = DateTime.Now;
        this.start = this.removeTime(postedDate);
        this.currentDAte = this.removeTime(currentDate_);
        this.origstart = postedDate;
        this.origCurrentDAte = currentDate_;
        if (start > this.currentDAte)
            throw new Exception("Current date is greater than date posted");

    void compute()
        while (this.start.Year <= this.currentDAte.Year)
            if (this.start.Year <= this.currentDAte.Year && (this.start.AddMonths(1) <= this.currentDAte))
                this.start = this.start.AddMonths(1);

            if ((this.start.Year == this.currentDAte.Year) && (this.start >= this.currentDAte.AddMonths(-1) && this.start <= this.currentDAte))

        while (this.start.DayOfYear < this.currentDAte.DayOfYear)
            this.start = start.AddDays(1);

        if (this.months > 11)
            while (this.months > 11)
                this.months = months - 12;


    public override string ToString()
        if (this.start > this.currentDAte)
            throw new Exception("Current date is greater than date posted");
        String ret = this.ComposeTostring();
        return ret;

    private String ComposeTostring()
        if (this.years > 0)
            if (this.months > 0)
                if (this.days > 0)
                    return String.Format("{0} year{1}, {2} month{3} && {4} Day{5} ago", this.years, plural(this.years), this.months, plural(this.months), this.days, plural(this.days));
                return String.Format("{0} year{1}, {2} month{3} ago", this.years, plural(this.years), this.months, plural(this.months));
                if (this.days > 0)
                    return String.Format("{0} year{1},{2} day{3} ago", this.years, plural(this.years), this.days, plural(this.days));

                return String.Format("{0} year{1} ago", this.years, plural(this.years));


        if (this.months > 0)
            if (this.days > 0)
                return String.Format("{0} month{1}, {2} day{3} ago", this.months, plural(this.months), this.days, plural(this.days));
                return String.Format("{0} month{1} ago", this.months, plural(this.months));

        if ((this.origCurrentDAte - this.origstart).Days > 0)
            int daysDiff = (this.origCurrentDAte - this.origstart).Days;
            this.origstart = this.origstart.AddDays(daysDiff);
            int HoursDiff = (this.origCurrentDAte - this.origstart).Hours;
            return String.Format("{0} day{1}, {2} hour{3} ago", daysDiff, plural(daysDiff), HoursDiff, plural(HoursDiff));

        else if ((this.origCurrentDAte - this.origstart).Hours > 0)
            int HoursDiff = (this.origCurrentDAte - this.origstart).Hours;
            this.origstart = this.origstart.AddHours(HoursDiff);
            int MinDiff = (this.origCurrentDAte - this.origstart).Minutes;
            return String.Format("{0} hour{1}, {2} minute{3} ago", HoursDiff, plural(HoursDiff), MinDiff, plural(MinDiff));
        else if ((this.origCurrentDAte - this.origstart).Minutes > 0)

            int MinDiff = (this.origCurrentDAte - this.origstart).Minutes;
            this.origstart = this.origstart.AddMinutes(MinDiff);
            int SecDiff = (this.origCurrentDAte - this.origstart).Seconds;
            return String.Format("{0} minute{1}, {2} second{3} ago", MinDiff, plural(MinDiff), SecDiff, plural(SecDiff));
        else if ((this.origCurrentDAte - this.origstart).Seconds > 0)
            int sec = (this.origCurrentDAte - this.origstart).Seconds;
            return String.Format("{0} second{1}", sec, plural(sec));

        return "";

    String plural(int val)
        return (val > 1 ? "s" : String.Empty);

    DateTime removeTime(DateTime dtime)
        dtime = dtime.AddHours(-dtime.Hour);
        dtime = dtime.AddMinutes(-dtime.Minute);
        dtime = dtime.AddSeconds(-dtime.Second);
        return dtime;

    public void reset()

        this.days = 0;
        this.months = 0;
        this.years = 0;
        this.start = DateTime.MinValue;
        this.currentDAte = DateTime.MinValue;
        this.origstart = DateTime.MinValue;
        this.origCurrentDAte = DateTime.MinValue;

Regular expression to match characters at beginning of line only

Beginning of line or beginning of string?

Start and end of string


/ = delimiter
^ = start of string
CTR = literal CTR
$ = end of string
.* = zero or more of any character except newline

Start and end of line


/ = delimiter
^ = start of line
CTR = literal CTR
$ = end of line
.* = zero or more of any character except newline
m = enables multi-line mode, this sets regex to treat every line as a string, so ^ and $ will match start and end of line

While in multi-line mode you can still match the start and end of the string with \A\Z permanent anchors


\A = means start of string
CTR = literal CTR
.* = zero or more of any character except newline
\Z = end of string
m = enables multi-line mode

As such, another way to match the start of the line would be like this:




\r = carriage return / old Mac OS newline
\n = line-feed / Unix/Mac OS X newline
\r\n = windows newline

Note, if you are going to use the backslash \ in some program string that supports escaping, like the php double quotation marks "" then you need to escape them first

so to run \r\nCTR.* you would use it as "\\r\\nCTR.*"

What is the use of static constructors?

No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.

It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

How to open new browser window on button click event?

Or write to the response stream:


Send JSON data from Javascript to PHP?

Javascript file using jQuery (cleaner but library overhead):

    type: 'POST',
    url: 'process.php',
    data: {json: JSON.stringify(json_data)},
    dataType: 'json'

PHP file (process.php):

directions = json_decode($_POST['json']);

Note that if you use callback functions in your javascript:

    type: 'POST',
    url: 'process.php',
    data: {json: JSON.stringify(json_data)},
    dataType: 'json'
.done( function( data ) {
.fail( function( data ) {

You must, in your PHP file, return a JSON object (in javascript formatting), in order to get a 'done/success' outcome in your Javascript code. At a minimum return/print:


See Ajax request return 200 OK but error event is fired instead of success

Although for anything a bit more serious you should be sending back a proper header explicitly with the appropriate response code.

How to perform keystroke inside powershell?

Also the $wshell = New-Object -ComObject; helped a script that was running in the background, it worked fine with just but adding $wshell. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")

How to instantiate a File object in JavaScript?

According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.

So to create a empty file do:

var f = new File([""], "filename");
  • The first argument is the data provided as an array of lines of text;
  • The second argument is the filename ;
  • The third argument looks like:

    var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})

It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.

Validating with an XML schema in Python

I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check Validation with lxml. The page also lists how to use lxml to validate with other schema types.

Tracking changes in Windows registry

A straightforward way to do this with no extra tools is to export the registry to a text file before the install, then export it to another file after. Then, compare the two files.

Having said that, the Sysinternals tools are great for this.

What do these operators mean (** , ^ , %, //)?

You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:

  • The ** operator does exponentiation. a ** b is a raised to the b power. The same ** symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).
  • The ^ operator does a binary xor. a ^ b will return a value with only the bits set in a or in b but not both. This one is simple!
  • The % operator is mostly to find the modulus of two integers. a % b returns the remainder after dividing a by b. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b, rather than the same sign as a. The same operator is also used for the "old" style of string formatting, so a % b can return a string if a is a format string and b is a value (or tuple of values) which can be inserted into a.
  • The // operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b). In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division at the top of your files. I strongly recommend it!)

I need an unordered list without any bullets

You can remove bullets by setting the list-style-type to none on the CSS for the parent element (typically a <ul>), for example:

ul {
  list-style-type: none;

You might also want to add padding: 0 and margin: 0 to that if you want to remove indentation as well.

See Listutorial for a great walkthrough of list formatting techniques.

npm notice created a lockfile as package-lock.json. You should commit this file

If this is output from a Dockerfile then you don't want / need to commit it.

However you will want to tag the base image and any other contributing images / applications.


FROM node:12.18.1

Checking for a null object in C++

Basically, all I'm trying to do is to prevent the program from crashing when some_cpp_function() is called with NULL.

It is not possible to call the function with NULL. One of the purpose of having the reference, it will point to some object always as you have to initialize it when defining it. Do not think reference as a fancy pointer, think of it as an alias name for the object itself. Then this type of confusion will not arise.

How to catch a click event on a button?

Just declare a method,e.g:if ur button id is button1 then,

button1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(Context, "Hello", Toast.LENGTH_SHORT).show();

If you want to make the imageview1 visible then in that method write:


How to solve SyntaxError on autogenerated

I solved this problem to uninstall the multiple version of Python. Check Django Official Documentation for Python compatibility.

"Python compatibility

Django 2.1 supports Python 3.5, 3.6, and 3.7. Django 2.0 is the last version to support Python 3.4." file

#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
   os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'work.settings')
       from import execute_from_command_line
   except ImportError as exc:
      raise ImportError(
        "Couldn't import Django. Are you sure it's installed and "
        "available on your PYTHONPATH environment variable? Did you "
        "forget to activate a virtual environment?"
      ) from exc

If removing "from exc" from second last line of this code will generate another error due to multiple versions of Python.

How to build and fill pandas dataframe from for loop?

Try this using list comprehension:

import pandas as pd

df = pd.DataFrame(
    [p,, p.passing_att, p.passer_rating()] for p in game.players.passing()

how to bind datatable to datagridview in c#

Even better:

DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();

ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;

ServersTable.DataSource = SBind;

You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.

How to Get XML Node from XDocument


<?xml version="1.0" encoding="utf-8"?>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();


Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();


Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")


jQuery: Setting select list 'selected' based on text, failing strangely

In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript

document.getElementById("The id of the element").value = "The value"

And that would set the value and make the current value selected in the combo box. Tested in firefox.

it was easier than keep googling a solution for jQuery

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:


git - Server host key not cached

Just ssh'ing to the host is not enough, on Windows at least. That adds the host key to ssh/known_hosts but the error still persists.

You need to close the git bash window and open a new one. Then the registry cache is cleared and the push/pull then works.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The provided solution here is correct. However, the same error can also occur from a user error, where your endpoint request method is NOT matching the method your using when making the request.

For example, the server endpoint is defined with "RequestMethod.PUT" while you are requesting the method as POST.

String.replaceAll single backslashes with double backslashes

You'll need to escape the (escaped) backslash in the first argument as it is a regular expression. Replacement (2nd argument - see Matcher#replaceAll(String)) also has it's special meaning of backslashes, so you'll have to replace those to:

theString.replaceAll("\\\\", "\\\\\\\\");

Mix Razor and Javascript code

Wrap your Razor code in @{ } when inside JS script and be aware of using just @ Sometimes it doesn't work:

function hideSurveyReminder() {
       @Session["_isSurveyPassed"] = true;

This will produce

function hideSurveyReminder() {
       False = true;

in browser =(

src absolute path problem

I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.

Is there a way to iterate over a range of integers?

The problem is not the range, the problem is how the end of slice is calculated. with a fixed number 10 the simple for loop is ok but with a calculated size like bfl.Size() you get a function-call on every iteration. A simple range over int32 would help because this evaluate the bfl.Size() only once.

type BFLT PerfServer   
  func (this *BFLT) Call() {
    bfl := MqBufferLCreateTLS(0)                                                                                   
    for this.ReadItemExists() {                                                                                    
    // size := bfl.Size() 
    for i := int32(0); i < bfl.Size() /* size */; i++ {                                                                             

PHP Session data not being saved

Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php_sessions which didn't exist anymore. A solution would have been to declare ini_set(' session.save_path','SOME WRITABLE PATH'); in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles.

Android Linear Layout - How to Keep Element At Bottom Of View?





Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.

To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */

jsFiddle demo

1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

Add a property to a JavaScript object using a variable as the name?

You can even make List of objects like this

var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
    var feeType = {};

    var $ID = $(this).find("input[id^=txtFeeType]").attr('id');

    feeType["feeTypeID"] = $('#ddlTerm').val();
    feeType["feeTypeName"] = $('#ddlProgram').val();
    feeType["feeTypeDescription"] = $('#ddlBatch').val();


Excel column number from column name

In my opinion the simpliest way to get column number is:
Sub Sample() ColName = ActiveCell.Column MsgBox ColName End Sub

Netbeans - class does not have a main method

It was most likely that you capitalized 'm' in 'main' to 'Main'

This happened to me this instant but I fixed it thanks to the various source code examples given by all those that responded. Thank you.

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {

Should print out everything you were trying in your question.

edit renamed the variables to make it bit easier to understand what is what.

Changing :hover to touch/click for mobile devices

If you use :active selector in combination with :hover you can achieve this according to w3schools as long as the :active selector is called after the :hover selector.

 .info-slide:hover, .info-slide:active{

You'd have to test the FIDDLE in a mobile environment. I can't at the moment.
correction - I just tested in a mobile, it works fine

Convert JSON string to dict using Python

If you trust the data source, you can use eval to convert your string into a dictionary:



>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>

Replace single quotes in SQL Server

Try this :

select replace (colname, char(39)+char(39), '') AS colname FROM .[dbo].[Db Name];

I have achieved the desired result. Example : Input value --> Like '%Pat') '' OR

      Want Output -->  *Like '%Pat') OR*

using above query achieved the desired result.

MySql server startup error 'The server quit without updating PID file '

The solution that worked for me was here:

Changing some of my permissions seemed to do the trick. I'm running a Mid-2012 Macbook Air with OS X 10.8.2 and mysql was installed with homebrew.

chmod 0755 /var
chown root:wheel /var/tmp
sudo chmod 0771 /usr/local/var/mysql/*

Run batch file from Java code

try following

try {
            String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
            Process p =  Runtime.getRuntime().exec(command);           
        } catch (IOException ex) {

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

Javascript Append Child AFTER Element

If you are looking for a plain JS solution, then you just use insertBefore() against nextSibling.

Something like:

parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);

Note that default value of nextSibling is null, so, you don't need to do anything special for that.

Update: You don't even need the if checking presence of parentGuest.nextSibling like the currently accepted answer does, because if there's no next sibling, it will return null, and passing null to the 2nd argument of insertBefore() means: append at the end.



IF you are using jQuery (ignore otherwise, I have stated plain JS answer above), you can leverage the convenient after() method:

$("#one").after("<li id='two'>");


C# Foreach statement does not contain public definition for GetEnumerator

In foreach loop instead of carBootSaleList use

You probably do not need answer anymore, but it could help someone.

How to do a SOAP Web Service call from Java class?

I understand your problem boils down to how to call a SOAP (JAX-WS) web service from Java and get its returning object. In that case, you have two possible approaches:

  1. Generate the Java classes through wsimport and use them; or
  2. Create a SOAP client that:
    1. Serializes the service's parameters to XML;
    2. Calls the web method through HTTP manipulation; and
    3. Parse the returning XML response back into an object.

About the first approach (using wsimport):

I see you already have the services' (entities or other) business classes, and it's a fact that the wsimport generates a whole new set of classes (that are somehow duplicates of the classes you already have).

I'm afraid, though, in this scenario, you can only either:

  • Adapt (edit) the wsimport generated code to make it use your business classes (this is difficult and somehow not worth it - bear in mind everytime the WSDL changes, you'll have to regenerate and readapt the code); or
  • Give up and use the wsimport generated classes. (In this solution, you business code could "use" the generated classes as a service from another architectural layer.)

About the second approach (create your custom SOAP client):

In order to implement the second approach, you'll have to:

  1. Make the call:
    • Use the SAAJ (SOAP with Attachments API for Java) framework (see below, it's shipped with Java SE 1.6 or above) to make the calls; or
    • You can also do it through (and some handling).
  2. Turn the objects into and back from XML:
    • Use an OXM (Object to XML Mapping) framework such as JAXB to serialize/deserialize the XML from/into objects
    • Or, if you must, manually create/parse the XML (this can be the best solution if the received object is only a little bit differente from the sent one).

Creating a SOAP client using classic is not that hard (but not that simple either), and you can find in this link a very good starting code.

I recommend you use the SAAJ framework:

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
            The example below requests from the Web Service at:

            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
        String soapEndpointUrl = "";
        String soapAction = "";

        callSoapWebService(soapEndpointUrl, soapAction);

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="" xmlns:myNamespace="">

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("CelsiusToFahrenheit", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Celsius", myNamespace);

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse =, soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");

        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();


        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);


        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");

        return soapMessage;


About using JAXB for serializing/deserializing, it is very easy to find information about it. You can start here:

How to increase the execution timeout in php?

I know you are specifically asking about the PHP timeout, but what no one else seems to have mentioned is that there can also be a timeout on the webserver and it can look very similar to the PHP timeout.

So if you have tried:

  1. Increasing the timeout in php.ini by adding a line: max_execution_time = {number of seconds i.e. 60 for one minute}
  2. Increasing the timeout in your script itself by adding: ini_set('max_execution_time','{number of seconds i.e. 60 for one minute}');

And you have checked with the phpinfo() function that max_execution_time has indeed be increased, then you might want to try adding this to .htaccess which will make sure Apache itself does not time out:

RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]

More info here:

Select multiple rows with the same value(s)

One way of doing this is via an exists clause:

select * from genes g
where exists
(select null from genes g1
 where = and g.chromosome = g1.chromosome and <>

Alternatively, in MySQL you can get a summary of all matching ids with a single table access, using group_concat:

select group_concat(id) matching_ids, chromosome, locus 
from genes
group by chromosome, locus
having count(*) > 1

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You can access afterRender hook by using plugins.

And here are all the plugin api available.

In html file:

  <canvas id="myChart"></canvas>
  <div id="imgWrap"></div>

In js file:

var chart = new Chart(ctx, {
  plugins: [{
    afterRender: function () {
      // Do anything you want

const renderIntoImage = () => {
  const canvas = document.getElementById('myChart')
  const imgWrap = document.getElementById('imgWrap')
  var img = new Image();
  img.src = canvas.toDataURL()
  imgWrap.appendChild(img) = 'none'

The import org.junit cannot be resolved

In starting code line copy past 'Junit' or 'TestNG' elements will show with Error till you import library with the Project File.

To import Libraries in to project:

Right Click on the Project --> Properties --> Java Build Path --> Libraries -> Add Library -> 'Junit' or 'TestNG'

Add Junit Libraries

Restrict varchar() column to specific values?

When you are editing a table
Right Click -> Check Constraints -> Add -> Type something like Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly') in expression field and a good constraint name in (Name) field.
You are done.

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

How to draw a custom UIView that is just a circle - iPhone app

Would I just override the drawRect method?


- (void)drawRect:(CGRect)rect
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextAddEllipseInRect(ctx, rect);
    CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));

Also, would it be okay to change the frame of that view within the class itself?

Ideally not, but you could.

Or do I need to change the frame from a different class?

I'd let the parent control that.

How to display list items as columns?

You can use flex as below:

.parent-container {
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    max-height: 100px;

Adjust max-height property as per need to generate another columns

Sum values in foreach loop php

Use +=

$val = 0;

foreach($arr as $var) {
   $val += $var; 

echo $val;

How to Update Multiple Array Elements in mongodb

You can update all elements in MongoDB

{ "key": /vikas/i },
{ $set: { 
 "arr.$[].status" : "completed"
} }

It will update all the "status" value to "completed" in the "arr" Array

If Only one document

 { key:"someunique", "arr.key": "myuniq" },
 { $set: { 
   "arr.$.status" : "completed", 
   "arr.$.msgs":  {
                "result" : ""
 } }

But if not one and also you don't want all the documents in the array to update then you need to loop through the element and inside the if block

db.collectioname.find({findCriteria })
  .forEach(function (doc) {
    doc.arr.forEach(function (singlearr) {
      if (singlearr check) {
        singlearr.handled =0

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

How to get all key in JSON object (javascript)

var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "[email protected]" };

for (x in jsonData) {   
  console.log(x +" => "+ jsonData[x]);  
  alert(x +" => "+  jsonData[x]);  

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Scroll to bottom of div?

var mydiv = $("#scroll");

Works from jQuery 1.6

remove all variables except functions

You can use the following command to clear out ALL variables. Be careful because it you cannot get your variables back.


Can we open pdf file using UIWebView on iOS?

An update to Martin Alléus's answer, to get the full screen whether it is a phone or a iPad without having to hard code:

CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];

NSString *path = [[NSBundle mainBundle] pathForResource:@"pdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];

Declaring an unsigned int in Java

Use char for 16 bit unsigned integers.

Using Cookie in Asp.Net Mvc 4

We are using Response.SetCookie() for update the old one cookies and Response.Cookies.Add() are use to add the new cookies. Here below code CompanyId is update in old cookie[OldCookieName].

HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

In JPA 2, using a CriteriaQuery, how to count results

A query of type MyEntity is going to return MyEntity. You want a query for a Long.

CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);;
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();

Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.

mysql update multiple columns with same now()

You can store the value of a now() in a variable before running the update query and then use that variable to update both the fields last_update and last_monitor.

This will ensure the now() is executed only once and same value is updated on both columns you need.

SQLAlchemy equivalent to SQL "LIKE" statement

try this code

output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))

Should we pass a shared_ptr by reference or by value?

I ran the code below, once with foo taking the shared_ptr by const& and again with foo taking the shared_ptr by value.

void foo(const std::shared_ptr<int>& p)
    static int x = 0;
    *p = ++x;

int main()
    auto p = std::make_shared<int>();
    auto start = clock();
    for (int i = 0; i < 10000000; ++i)
    std::cout << "Took " << clock() - start << " ms" << std::endl;

Using VS2015, x86 release build, on my intel core 2 quad (2.4GHz) processor

const shared_ptr&     - 10ms  
shared_ptr            - 281ms 

The copy by value version was an order of magnitude slower.
If you are calling a function synchronously from the current thread, prefer the const& version.

Writing sqlplus output to a file

You may use the SPOOL command to write the information to a file.

Before executing any command type the following:

SPOOL <output file path>

All commands output following will be written to the output file.

To stop command output writing type


oracle diff: how to compare two tables?

Try This,

alter session set "_convert_set_to_join"= true;

The other alternative is to rewrite the SQL query manually [replacing the minus operator with a NOT IN subquery] evidences about 30% improvement in execution time .

 select * 
   from A 
    where (col1,col2,?) not in 
   (select col1,col2,? from B) 
   union all 
   select * from B 
  where (col1,col2,?) not in 
  (select col1,col2,? from A); 

I have referred from this post click here

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.

Date.prototype.getISOTimezoneOffset = function () {
    const offset = this.getTimezoneOffset();
    return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);

Date.prototype.toISOLocaleString = function () {
    return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
        this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
        this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +

Number.prototype.leftPad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) {
        s = "0" + s;
    return s;

Example usage:

var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"

I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.

(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

I'm not sure where to post this answer of mine but I think it's the right place. I came across this very error today and switching the subsystems didn't change a thing.

Changing the 64bit lib files to 32bit (x86) did the trick for me, I hope it will help someone out there !

EOL conversion in notepad ++

I open files "directly" from WinSCP which opens the files in Notepad++ I had a php files on my linux server which always opened in Mac format no matter what I did :-(

If I downloaded the file and then opened it from local (windows) it was open as Dos/Windows....hmmm

The solution was to EOL-convert the local file to "UNIX/OSX Format", save it and then upload it.

Now when I open the file directly from the server it's open as "Dos/Windows" :-)

Why is it string.join(list) instead of list.join(string)?

Why is it string.join(list) instead of list.join(string)?

This is because join is a "string" method! It creates a string from any iterable. If we stuck the method on lists, what about when we have iterables that aren't lists?

What if you have a tuple of strings? If this were a list method, you would have to cast every such iterator of strings as a list before you could join the elements into a single string! For example:

some_strings = ('foo', 'bar', 'baz')

Let's roll our own list join method:

class OurList(list): 
    def join(self, s):
        return s.join(self)

And to use it, note that we have to first create a list from each iterable to join the strings in that iterable, wasting both memory and processing power:

>>> l = OurList(some_strings) # step 1, create our list
>>> l.join(', ') # step 2, use our list join method!
'foo, bar, baz'

So we see we have to add an extra step to use our list method, instead of just using the builtin string method:

>>> ' | '.join(some_strings) # a single step!
'foo | bar | baz'

Performance Caveat for Generators

The algorithm Python uses to create the final string with str.join actually has to pass over the iterable twice, so if you provide it a generator expression, it has to materialize it into a list first before it can create the final string.

Thus, while passing around generators is usually better than list comprehensions, str.join is an exception:

>>> import timeit
>>> min(timeit.repeat(lambda: ''.join(str(i) for i in range(10) if i)))
>>> min(timeit.repeat(lambda: ''.join([str(i) for i in range(10) if i])))

Nevertheless, the str.join operation is still semantically a "string" operation, so it still makes sense to have it on the str object than on miscellaneous iterables.

How to iterate through a list of objects in C++

You're close.

std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;

Note that you can define it inside the for loop:

for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;

And if you are using C++11 then you can use a range-based for loop instead:

for (auto const& i : data) {
    std::cout <<;

Here auto automatically deduces the correct type. You could have written Student const& i instead.

Python 3 sort a dict by its values

You can sort by values in reverse order (largest to smallest) using a dictionary comprehension:

{k: d[k] for k in sorted(d, key=d.get, reverse=True)}
# {'b': 4, 'a': 3, 'c': 2, 'd': 1}

If you want to sort by values in ascending order (smallest to largest)

{k: d[k] for k in sorted(d, key=d.get)}
# {'d': 1, 'c': 2, 'a': 3, 'b': 4}

If you want to sort by the keys in ascending order

{k: d[k] for k in sorted(d)}
# {'a': 3, 'b': 4, 'c': 2, 'd': 1}

This works on CPython 3.6+ and any implementation of Python 3.7+ because dictionaries keep insertion order.

Printing long int value in C

To take input " long int " and output " long int " in C is :

long int n;
scanf("%ld", &n);
printf("%ld", n);

To take input " long long int " and output " long long int " in C is :

long long int n;
scanf("%lld", &n);
printf("%lld", n);

Hope you've cleared..

How to read the last row with SQL Server

You can use last_value: SELECT LAST_VALUE(column) OVER (PARTITION BY column ORDER BY column)...

I test it at one of my databases and it worked as expected.

You can also check de documentation here:

ASP.NET file download from server

Making changes as below and redeploying on server content type as

Response.ContentType = "application/octet-stream";

This worked for me.

Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
Response.AddHeader("Content-Length", file.Length.ToString()); 
Response.ContentType = "application/octet-stream"; 

How to install Android Studio on Ubuntu?

To install android studio on ubuntu here is the simplest way possible:

First of all, you have to install Ubuntu Make before installing Android Studio. Type following commands in the same order one by one on terminal:

1) sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make

2) sudo apt-get update

3) sudo apt-get install ubuntu-make

Now since you are done with Ubuntu make, use below command to install Android Studio:

4) umake android

While installation it will give you a couple of option which you can handle. So, Installation is done. You can open it and run an App of your choice. Isn’t it very easy? Let me know if you go through any problem, I can help.

Source Install Android Studio

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

For TF2.x, you can do like this.

import tensorflow as tf
with tf.compat.v1.Session() as sess:
    hello = tf.constant('hello world')

>>> b'hello world

Order of execution of tests in TestNG

If I understand your question correctly in that you want to run tests in a specified order, TestNG IMethodInterceptor can be used. Take a look at on how to leverage them.

If you want run some preinitialization, take a look at IHookable and associated thread

How to open a link in new tab (chrome) using Selenium WebDriver?

Selenium can only automate on the WebElements of the browser. Opening a new tab is an operation performed on the webBrowser which is a stand alone application. For doing this you can make use of the Robot class from the java.util.* package which can perform operations using the keyboard regardless of what type of application it is. So here's the code for your operation. Note that you cannot automate stand alone applications using the Robot class but you can perform keyboard or mouse operations

WebDriver driver = new ChromeDriver();
Robot rob = new Robot();

After this step you will need a window iterator to switch to the new tab:

Set <String> ids = driver.getWindowHandles();
Iterator <String> it = ids.iterator();
String currentWindow =;
String newWindow =;

What is the shortcut in IntelliJ IDEA to find method / functions?

Ctrl + Shift + Alt+ 7 after selecting the method

Why does the C preprocessor interpret the word "linux" as the constant "1"?

Use this command

gcc -dM -E - < /dev/null

to get this

    #define _LP64 1
#define _STDC_PREDEF_H 1
#define __ATOMIC_ACQUIRE 2
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_CONSUME 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __ATOMIC_HLE_RELEASE 131072
#define __ATOMIC_RELAXED 0
#define __ATOMIC_RELEASE 3
#define __ATOMIC_SEQ_CST 5
#define __BIGGEST_ALIGNMENT__ 16
#define __CHAR16_TYPE__ short unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __CHAR_BIT__ 8
#define __DBL_DECIMAL_DIG__ 17
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __DBL_DIG__ 15
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define __DBL_HAS_DENORM__ 1
#define __DBL_HAS_INFINITY__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __DBL_MANT_DIG__ 53
#define __DBL_MAX_10_EXP__ 308
#define __DBL_MAX_EXP__ 1024
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __DBL_MIN_10_EXP__ (-307)
#define __DBL_MIN_EXP__ (-1021)
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __DEC128_EPSILON__ 1E-33DL
#define __DEC128_MANT_DIG__ 34
#define __DEC128_MAX_EXP__ 6145
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __DEC128_MIN_EXP__ (-6142)
#define __DEC128_MIN__ 1E-6143DL
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __DEC32_EPSILON__ 1E-6DF
#define __DEC32_MANT_DIG__ 7
#define __DEC32_MAX_EXP__ 97
#define __DEC32_MAX__ 9.999999E96DF
#define __DEC32_MIN_EXP__ (-94)
#define __DEC32_MIN__ 1E-95DF
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __DEC64_EPSILON__ 1E-15DD
#define __DEC64_MANT_DIG__ 16
#define __DEC64_MAX_EXP__ 385
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __DEC64_MIN_EXP__ (-382)
#define __DEC64_MIN__ 1E-383DD
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DECIMAL_BID_FORMAT__ 1
#define __DECIMAL_DIG__ 21
#define __DEC_EVAL_METHOD__ 2
#define __ELF__ 1
#define __FINITE_MATH_ONLY__ 0
#define __FLT_DECIMAL_DIG__ 9
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __FLT_DIG__ 6
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __FLT_EVAL_METHOD__ 0
#define __FLT_HAS_DENORM__ 1
#define __FLT_HAS_INFINITY__ 1
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MANT_DIG__ 24
#define __FLT_MAX_10_EXP__ 38
#define __FLT_MAX_EXP__ 128
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __FLT_MIN_10_EXP__ (-37)
#define __FLT_MIN_EXP__ (-125)
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __FLT_RADIX__ 2
#define __FXSR__ 1
#define __GCC_ASM_FLAG_OUTPUTS__ 1
#define __GCC_IEC_559 2
#define __GCC_IEC_559_COMPLEX 2
#define __GNUC_MINOR__ 3
#define __GNUC_PATCHLEVEL__ 0
#define __GNUC_STDC_INLINE__ 1
#define __GNUC__ 6
#define __GXX_ABI_VERSION 1010
#define __INT16_C(c) c
#define __INT16_MAX__ 0x7fff
#define __INT16_TYPE__ short int
#define __INT32_C(c) c
#define __INT32_MAX__ 0x7fffffff
#define __INT32_TYPE__ int
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int
#define __INT8_C(c) c
#define __INT8_MAX__ 0x7f
#define __INT8_TYPE__ signed char
#define __INTMAX_C(c) c ## L
#define __INTMAX_MAX__ 0x7fffffffffffffffL
#define __INTMAX_TYPE__ long int
#define __INTPTR_MAX__ 0x7fffffffffffffffL
#define __INTPTR_TYPE__ long int
#define __INT_FAST16_MAX__ 0x7fffffffffffffffL
#define __INT_FAST16_TYPE__ long int
#define __INT_FAST32_MAX__ 0x7fffffffffffffffL
#define __INT_FAST32_TYPE__ long int
#define __INT_FAST64_MAX__ 0x7fffffffffffffffL
#define __INT_FAST64_TYPE__ long int
#define __INT_FAST8_MAX__ 0x7f
#define __INT_FAST8_TYPE__ signed char
#define __INT_LEAST16_MAX__ 0x7fff
#define __INT_LEAST16_TYPE__ short int
#define __INT_LEAST32_MAX__ 0x7fffffff
#define __INT_LEAST32_TYPE__ int
#define __INT_LEAST64_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST64_TYPE__ long int
#define __INT_LEAST8_MAX__ 0x7f
#define __INT_LEAST8_TYPE__ signed char
#define __INT_MAX__ 0x7fffffff
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __LDBL_DIG__ 18
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __LDBL_HAS_DENORM__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __LDBL_HAS_QUIET_NAN__ 1
#define __LDBL_MANT_DIG__ 64
#define __LDBL_MAX_10_EXP__ 4932
#define __LDBL_MAX_EXP__ 16384
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __LDBL_MIN_10_EXP__ (-4931)
#define __LDBL_MIN_EXP__ (-16381)
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __LONG_LONG_MAX__ 0x7fffffffffffffffLL
#define __LONG_MAX__ 0x7fffffffffffffffL
#define __LP64__ 1
#define __MMX__ 1
#define __NO_INLINE__ 1
#define __ORDER_BIG_ENDIAN__ 4321
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __ORDER_PDP_ENDIAN__ 3412
#define __PIC__ 2
#define __PIE__ 2
#define __PTRDIFF_MAX__ 0x7fffffffffffffffL
#define __PTRDIFF_TYPE__ long int
#define __REGISTER_PREFIX__ 
#define __SCHAR_MAX__ 0x7f
#define __SEG_FS 1
#define __SEG_GS 1
#define __SHRT_MAX__ 0x7fff
#define __SIG_ATOMIC_MAX__ 0x7fffffff
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __SIG_ATOMIC_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __SIZEOF_FLOAT128__ 16
#define __SIZEOF_FLOAT80__ 16
#define __SIZEOF_FLOAT__ 4
#define __SIZEOF_INT128__ 16
#define __SIZEOF_INT__ 4
#define __SIZEOF_LONG_DOUBLE__ 16
#define __SIZEOF_LONG_LONG__ 8
#define __SIZEOF_LONG__ 8
#define __SIZEOF_POINTER__ 8
#define __SIZEOF_PTRDIFF_T__ 8
#define __SIZEOF_SHORT__ 2
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WCHAR_T__ 4
#define __SIZEOF_WINT_T__ 4
#define __SIZE_MAX__ 0xffffffffffffffffUL
#define __SIZE_TYPE__ long unsigned int
#define __SSE2_MATH__ 1
#define __SSE2__ 1
#define __SSE_MATH__ 1
#define __SSE__ 1
#define __SSP_STRONG__ 3
#define __STDC_HOSTED__ 1
#define __STDC_IEC_559_COMPLEX__ 1
#define __STDC_IEC_559__ 1
#define __STDC_ISO_10646__ 201605L
#define __STDC_NO_THREADS__ 1
#define __STDC_UTF_16__ 1
#define __STDC_UTF_32__ 1
#define __STDC_VERSION__ 201112L
#define __STDC__ 1
#define __UINT16_C(c) c
#define __UINT16_MAX__ 0xffff
#define __UINT16_TYPE__ short unsigned int
#define __UINT32_C(c) c ## U
#define __UINT32_MAX__ 0xffffffffU
#define __UINT32_TYPE__ unsigned int
#define __UINT64_C(c) c ## UL
#define __UINT64_MAX__ 0xffffffffffffffffUL
#define __UINT64_TYPE__ long unsigned int
#define __UINT8_C(c) c
#define __UINT8_MAX__ 0xff
#define __UINT8_TYPE__ unsigned char
#define __UINTMAX_C(c) c ## UL
#define __UINTMAX_MAX__ 0xffffffffffffffffUL
#define __UINTMAX_TYPE__ long unsigned int
#define __UINTPTR_MAX__ 0xffffffffffffffffUL
#define __UINTPTR_TYPE__ long unsigned int
#define __UINT_FAST16_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST16_TYPE__ long unsigned int
#define __UINT_FAST32_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST32_TYPE__ long unsigned int
#define __UINT_FAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST64_TYPE__ long unsigned int
#define __UINT_FAST8_MAX__ 0xff
#define __UINT_FAST8_TYPE__ unsigned char
#define __UINT_LEAST16_MAX__ 0xffff
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __UINT_LEAST32_MAX__ 0xffffffffU
#define __UINT_LEAST32_TYPE__ unsigned int
#define __UINT_LEAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_LEAST64_TYPE__ long unsigned int
#define __UINT_LEAST8_MAX__ 0xff
#define __UINT_LEAST8_TYPE__ unsigned char
#define __USER_LABEL_PREFIX__ 
#define __VERSION__ "6.3.0 20170406"
#define __WCHAR_MAX__ 0x7fffffff
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __WCHAR_TYPE__ int
#define __WINT_MAX__ 0xffffffffU
#define __WINT_MIN__ 0U
#define __WINT_TYPE__ unsigned int
#define __amd64 1
#define __amd64__ 1
#define __code_model_small__ 1
#define __gnu_linux__ 1
#define __has_include(STR) __has_include__(STR)
#define __has_include_next(STR) __has_include_next__(STR)
#define __k8 1
#define __k8__ 1
#define __linux 1
#define __linux__ 1
#define __pic__ 2
#define __pie__ 2
#define __unix 1
#define __unix__ 1
#define __x86_64 1
#define __x86_64__ 1
#define linux 1
#define unix 1

How can I create my own comparator for a map?

Yes, the 3rd template parameter on map specifies the comparator, which is a binary predicate. Example:

struct ByLength : public std::binary_function<string, string, bool>
    bool operator()(const string& lhs, const string& rhs) const
        return lhs.length() < rhs.length();

int main()
    typedef map<string, string, ByLength> lenmap;
    lenmap mymap;

    mymap["one"] = "one";
    mymap["a"] = "a";
    mymap["fewbahr"] = "foobar";

    for( lenmap::const_iterator it = mymap.begin(), end = mymap.end(); it != end; ++it )
        cout << it->first << "\n";

MongoDB inserts float when trying to insert integer

Well, it's JavaScript, so what you have in 'value' is a Number, which can be an integer or a float. But there's not really a difference in JavaScript. From Learning JavaScript:

The Number Data Type

Number data types in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don’t have a decimal point or fractional component, they’re treated as integers—base-10 whole numbers in a range of –253 to 253.

'any' vs 'Object'

Object appears to be a more specific declaration than any. From the TypeScript spec (section 3):

All types in TypeScript are subtypes of a single top type called the Any type. The any keyword references this type. The Any type is the one type that can represent any JavaScript value with no constraints. All other types are categorized as primitive types, object types, or type parameters. These types introduce various static constraints on their values.


The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list.

Objects do not allow the same flexibility.

For example:

var myAny : any;

myAny.Something(); // no problemo

var myObject : Object;

myObject.Something(); // Error: The property 'Something' does not exist on value of type 'Object'.

here-document gives 'unexpected end of file' error

When I want to have docstrings for my bash functions, I use a solution similar to the suggestion of user12205 in a duplicate of this question.

See how I define USAGE for a solution that:

  • auto-formats well for me in my IDE of choice (sublime)
  • is multi-line
  • can use spaces or tabs as indentation
  • preserves indentations within the comment.
function foo {
    # Docstring
    read -r -d '' USAGE <<'    END'
        # This method prints foo to the terminal.
        # Enter `foo -h` to see the docstring.
        #      It has indentations and multiple lines.
        # Change the delimiter if you need hashtag for some reason.
        # This can include $$ and = and eval, but won't be evaluated

    if [ "$1" = "-h" ]
        echo "$USAGE" | cut -d "#" -f 2 | cut -c 2-

    echo "foo"

So foo -h yields:

This method prints foo to the terminal.

Enter `foo -h` to see the docstring.
     It has indentations and multiple lines.

Change the delimiter if you need hashtag for some reason.
This can include $$ and = and eval, but won't be evaluated


cut -d "#" -f 2: Retrieve the second portion of the # delimited lines. (Think a csv with "#" as the delimiter, empty first column).

cut -c 2-: Retrieve the 2nd to end character of the resultant string

Also note that if [ "$1" = "-h" ] evaluates as False if there is no first argument, w/o error, since it becomes an empty string.

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

In your controller you'd return an HttpStatusCodeResult like this...

public ActionResult SomeMethod(...your method parameters go here...)
   // todo: put your processing code here

   //If not using MVC5
   return new HttpStatusCodeResult(200);

   //If using MVC5
   return new HttpStatusCodeResult(HttpStatusCode.OK);  // OK = 200

How to count the occurrence of certain item in an ndarray?

Yet another simple solution might be to use numpy.count_nonzero():

import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
y_nonzero_num = np.count_nonzero(y==1)
y_zero_num = np.count_nonzero(y==0)

Don't let the name mislead you, if you use it with the boolean just like in the example, it will do the trick.

correct way to define class variables in Python

I think this sample explains the difference between the styles:

#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
['__doc__', '__init__', '__module__', 'element1']
['__doc__', '__init__', '__module__', 'element1', 'element2']
Hello World
Traceback (most recent call last):
  File "./", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

error: src refspec master does not match any

In my case the error was caused because I was typing

git push origin master

while I was on the develop branch try:

git push origin branchname

Hope this helps somebody

Multiple controllers with AngularJS in single page app

We can simply declare more than one Controller in the same module. Here's an example:

  <!DOCTYPE html>

       <script src="">
      <title> New Page </title>

    <body ng-app="mainApp"> <!-- if we remove ng-app the add book button [show/hide] will has no effect --> 
      <h2> Books </h2>

    <!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->
    <input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
             Enter book name: <input type = "text" ng-model = ""><br>
             Enter book category: <input type = "text" ng-model = "book.category"><br>
             Enter book price: <input type = "text" ng-model = "book.price"><br>
             Enter book author: <input type = "text" ng-model = ""><br>

             You are entering book: {{book.bookDetails()}}

             var mainApp = angular.module("mainApp", []);

             mainApp.controller('bookController', function($scope) {
                $ = {
                   name: "",
                   category: "",
                   author: "",

                   bookDetails: function() {
                      var bookObject;
                      bookObject = $;
                      return "Book name: " + +  '\n' + "Book category: " + bookObject.category + "  \n" + "Book price: " + bookObject.price + "  \n" + "Book Author: " +;


    <h2> Albums </h2>
    <input type = "button" value = "Add Album"ng-click="hideShow2=(hideShow2 ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "albumController" ng-if="hideShow2">
             Enter Album name: <input type = "text" ng-model = ""><br>
             Enter Album category: <input type = "text" ng-model = "album.category"><br>
             Enter Album price: <input type = "text" ng-model = "album.price"><br>
             Enter Album singer: <input type = "text" ng-model = "album.singer"><br>

             You are entering Album: {{album.albumDetails()}}

             //no need to declare this again ;)
             //var mainApp = angular.module("mainApp", []);

             mainApp.controller('albumController', function($scope) {
                $scope.album = {
                   name: "",
                   category: "",
                   singer: "",

                   albumDetails: function() {
                      var albumObject;
                      albumObject = $scope.album;
                      return "Album name: " + +  '\n' + "album category: " + albumObject.category + "\n" + "Book price: " + albumObject.price + "\n" + "Album Singer: " + albumObject.singer;


"E: Unable to locate package python-pip" on Ubuntu 18.04

Try following command sequence on Ubuntu terminal:

sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip

Updating a local repository with changes from a GitHub repository

This question is very general and there are a couple of assumptions I'll make to simplify it a bit. We'll assume that you want to update your master branch.

If you haven't made any changes locally, you can use git pull to bring down any new commits and add them to your master.

git pull origin master

If you have made changes, and you want to avoid adding a new merge commit, use git pull --rebase.

git pull --rebase origin master

git pull --rebase will work even if you haven't made changes and is probably your best call.

How to prove that a problem is NP complete?

In order to prove that a problem L is NP-complete, we need to do the following steps:

  1. Prove your problem L belongs to NP (that is that given a solution you can verify it in polynomial time)
  2. Select a known NP-complete problem L'
  3. Describe an algorithm f that transforms L' into L
  4. Prove that your algorithm is correct (formally: x ? L' if and only if f(x) ? L )
  5. Prove that algo f runs in polynomial time

Eclipse error "Could not find or load main class"

2 types of solutions exits for the same.

(1) Go to run configurations: - run->run configurations In the Classpath tab:

Select Advanced Add where Eclipse usually put the *.class for the projects, which is in bin. So I added the bin directory for the project.

(2) If first solution is not working then it means the jar you are pointing out to your project is taking the path of your local Maven repo which is not getting updated to your project so better you check the jar from that local maven repo and copy it paste it into new project simply or just download it from any site and configure it into your build path.

I hope it helps.

Nullable type as a generic parameter possible?

I just encountered the same problem myself.

... = reader["myYear"] as int?; works and is clean.

It works with any type without an issue. If the result is DBNull, it returns null as the conversion fails.

How to check the gradle version in Android Studio?

You can install andle for gradle version management.

It can help you sync to the latest version almost everything in gradle file.

Simple three step to update all project at once.

1. install:

    $ sudo pip install andle

2. set sdk:

    $ andle setsdk -p <sdk_path>

3. update depedency:

    $ andle update -p <project_path> [--dryrun] [--remote] [--gradle]

--dryrun: only print result in console

--remote: check version in jcenter and mavenCentral

--gradle: check gradle version

See for more information

Switch/toggle div (jQuery)

function toggling_fields_contact_bank(class_name) {
    jQuery("." + class_name).animate({
        height: 'toggle'

href image link download on click

HTML download attribute to specify that the target will be downloaded when a user clicks on the hyperlink.

This attribute is only used if the href attribute is set.

The value of the attribute will be the name of the downloaded file. There are no restrictions on allowed values, and the browser will automatically detect the correct file extension and add it to the file (.img, .pdf, .txt, .html, etc.).

Example code:

<a href=""> Download Image >></a>


<a href="" download> Download Image >></a>


Download Image >>

Html5 download or chrome

Download Image >>

Simplest way to throw an error/exception with a custom message in Swift 2?

Simplest solution without extra extensions, enums, classes and etc.:

NSException(name:NSExceptionName(rawValue: "name"), reason:"reason", userInfo:nil).raise()

Convert normal date to unix timestamp

You could simply use the unary + operator

(+new Date('2012.08.10')/1000).toFixed(0); - look under Dates.

How do I use WPF bindings with RelativeSource?

If you want to bind to another property on the object:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

If you want to get a property on an ancestor:

{Binding Path=PathToProperty,
    RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)

{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

or, shorter (this only works for OneWay bindings):

{TemplateBinding Path=PathToProperty}

This version of the application is not configured for billing through Google Play

You need to sign your APK with your live certificate. Then install that onto your test device. You can then test InAppBilling. If you are testing your application by direct run via eclipse to device(In debug mode) then you will get this error.

If you are using android.test.purchased as the SKU, it will work all the way, but you won't have the developerPayload in your final response.

If you are using your own draft in app item you can test all the way but you will be charged and so will have to refund it yourself afterwards.

You cannot buy items with the same gmail account that you use for the google play development console.

error: Your local changes to the following files would be overwritten by checkout

You can commit in the current branch, checkout to another branch, and finally cherry-pick that commit (in lieu of merge).

What is username and password when starting Spring Boot with Tomcat?

When I started learning Spring Security, then I overrided the method userDetailsService() as in below code snippet:

public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{

    protected void configure(HttpSecurity http) throws Exception {
                .antMatchers("/", "/index").permitAll()

    public UserDetailsService userDetailsService() {
        List<UserDetails> users= new ArrayList<UserDetails>();
        return new InMemoryUserDetailsManager(users);

So we can log in to the application using the above-mentioned creds. (e.g. admin/nimda)

Note: This we should not use in production.

How to replace all dots in a string using JavaScript

mystring.replace(new RegExp('.', "g"), ' ');

How to combine two byte arrays

You're just trying to concatenate the two byte arrays?

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

for (int i = 0; i < combined.length; ++i)
    combined[i] = i < one.length ? one[i] : two[i - one.length];

Or you could use System.arraycopy:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

System.arraycopy(one,0,combined,0         ,one.length);

Or you could just use a List to do the work:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();

List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));

byte[] combined = list.toArray(new byte[list.size()]);

Or you could simply use ByteBuffer with the advantage of adding many arrays.

byte[] allByteArray = new byte[one.length + two.length + three.length];

ByteBuffer buff = ByteBuffer.wrap(allByteArray);

byte[] combined = buff.array();

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

Why is Ant giving me a Unsupported major.minor version error

  1. Check whether u have jdk installed in the path "C:\Program Files\Java" If not Install the JDK in your machine

  2. In Eclipse, right click on "build.xml" then select Run As > External Tools Configuration

  3. Click on "JRE" tab then click on "Installed JREs" > "ADD" > "Standard VM" > Click "Next

  4. Select the Directory "C:\Program Files\Java\jdk1.7.x_xx" and the directory will be added to the "installed jres"

  5. Select the new JDK directory and Click "OK"

  6. Click on "Seperate JRE" dropdown and select the JDK version "jdk1.7.x_xx" and click on "Run"

This would help:)

Powershell script does not run via Scheduled Tasks

Although you may have already found a resolution to your issue, I'm still going to post this note to benefit someone else. I ran into a similar issue. I basically used a different domain account to test and compare. The task ran just fine with "Run whether user is logged on or not" checked.

A couple of things to keep in mind and make sure of:

  1. The account being use to execute task must have "Logon as batch job" rights under the local security policy of the server (or be member of local Admin group). You must specified the account you need to run scripts/bat files.
  2. Make sure you are entering the correct password characters
  3. Tasks in 2008 R2 don't run interactively specially if you run them as "Run whether user is logged on or not". This will likely fail specially if on the script you are looking for any objects\resource specific to a user-profile when the task was created as the powershell session will need that info to start, otherwise it will start and immediately end. As an example for defining $Path when running script as "Run whether user is logged on or not" and I specify a mapped drive. It would look for that drive when the task kicks off, but since the user account validated to run task is not logged in and on the script you are referring back to a source\object that it needs to work against it is not present task will just terminate. mapped drive (\server\share) x:\ vs. Actual UNC path \server\share
  4. Review your steps, script, arguments. Sometimes the smallest piece can make a big difference even if you have done this process many times. I have missed several times a character when entering the password or a semi-colon sometimes when building script or task.

Check this link and hopefully you or someone else can benefit from this info:

Fatal error: Call to a member function bind_param() on boolean

Even when the query syntax is correct, prepare could return false, if there was a previous statement and it wasn't closed. Always close your previous statement with


If the syntax is correct, the following query will run well too.

C++ compile error: has initializer but incomplete type

You need this include:

#include <sstream>

When to throw an exception?

Exceptions are a somewhat costly effect, if for example you have a user that provides an invalid password, it is typically a better idea to pass back a failure flag, or some other indicator that it is invalid.

This is due to the way that exceptions are handled, true bad input, and unique critical stop items should be exceptions, but not failed login info.

How to resolve : Can not find the tag library descriptor for ""

I also use this

<%@ taglib prefix="c" uri="" %>

but I don't get any error.

Did you include the jstl.jar in your library? If not maybe this causing the problem. And also the 'tld' folder do you have it? And how about your web.xml did you map it?

Have a look on the info about jstl for other information.

How can I rename a field for all documents in MongoDB?

I am using ,Mongo 3.4.0

The $rename operator updates the name of a field and has the following form:

{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }

for e.g

db.getCollection('user').update( { _id: 1 }, { $rename: { 'fname': 'FirstName', 'lname': 'LastName' } } )

The new field name must differ from the existing field name. To specify a in an embedded document, use dot notation.

This operation renames the field nmae to name for all documents in the collection:

db.getCollection('user').updateMany( {}, { $rename: { "add": "Address" } } )

db.getCollection('user').update({}, {$rename:{"name.first":"name.FirstName"}}, false, true);

In the method above false, true are: { upsert:false, multi:true }.To update all your records, You need the multi:true.

Rename a Field in an Embedded Document

db.getCollection('user').update( { _id: 1 }, { $rename: { "name.first": "name.fname" } } )

use link :

Why does an image captured using camera intent gets rotated on some devices on Android?

By combining Jason Robinson's answer with Felix's answer and filling the missing parts, here is the final complete solution for this issue that will do the following after testing it on Android Android 4.1 (Jelly Bean), Android 4.4 (KitKat) and Android 5.0 (Lollipop).


  1. Scale down the image if it was bigger than 1024x1024.

  2. Rotate the image to the right orientation only if it was rotate 90, 180 or 270 degree.

  3. Recycle the rotated image for memory purposes.

Here is the code part:

Call the following method with the current Context and the image URI that you want to fix

 * This method is responsible for solving the rotation issue if exist. Also scale the images to
 * 1024x1024 resolution
 * @param context       The current context
 * @param selectedImage The Image URI
 * @return Bitmap image results
 * @throws IOException
public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
        throws IOException {
    int MAX_HEIGHT = 1024;
    int MAX_WIDTH = 1024;

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
    BitmapFactory.decodeStream(imageStream, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    imageStream = context.getContentResolver().openInputStream(selectedImage);
    Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);

    img = rotateImageIfRequired(context, img, selectedImage);
    return img;

Here is the CalculateInSampleSize method from the pre mentioned source:

  * Calculate an inSampleSize for use in a {@link BitmapFactory.Options} object when decoding
  * bitmaps using the decode* methods from {@link BitmapFactory}. This implementation calculates
  * the closest inSampleSize that will result in the final decoded bitmap having a width and
  * height equal to or larger than the requested width and height. This implementation does not
  * ensure a power of 2 is returned for inSampleSize which can be faster when decoding but
  * results in a larger bitmap which isn't as useful for caching purposes.
  * @param options   An options object with out* params already populated (run through a decode*
  *                  method with inJustDecodeBounds==true
  * @param reqWidth  The requested width of the resulting bitmap
  * @param reqHeight The requested height of the resulting bitmap
  * @return The value to be used for inSampleSize
private static int calculateInSampleSize(BitmapFactory.Options options,
                                         int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee a final image
        // with both dimensions larger than or equal to the requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

        // This offers some additional logic in case the image has a strange
        // aspect ratio. For example, a panorama may have a much larger
        // width than height. In these cases the total pixels might still
        // end up being too large to fit comfortably in memory, so we should
        // be more aggressive with sample down the image (=larger inSampleSize).

        final float totalPixels = width * height;

        // Anything more than 2x the requested pixels we'll sample down further
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
    return inSampleSize;

Then comes the method that will check the current image orientation to decide the rotation angle

 * Rotate an image if required.
 * @param img           The image bitmap
 * @param selectedImage Image URI
 * @return The resulted Bitmap after manipulation
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {

InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
    ei = new ExifInterface(input);
    ei = new ExifInterface(selectedImage.getPath());

    int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            return rotateImage(img, 90);
        case ExifInterface.ORIENTATION_ROTATE_180:
            return rotateImage(img, 180);
        case ExifInterface.ORIENTATION_ROTATE_270:
            return rotateImage(img, 270);
            return img;

Finally the rotation method itself

private static Bitmap rotateImage(Bitmap img, int degree) {
    Matrix matrix = new Matrix();
    Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
    return rotatedImg;

-Don't forget to vote up for those guys answers for their efforts and Shirish Herwade who asked this helpful question.

What do two question marks together mean in C#?

It's the null coalescing operator.

Yes, nearly impossible to search for unless you know what it's called! :-)

EDIT: And this is a cool feature from another question. You can chain them.

Hidden Features of C#?

How to get list of all installed packages along with version in composer?

List installed dependencies:

  • Flat: composer show -i
  • Tree: composer show -i -t

-i short for --installed.

-t short for --tree.


Background thread with QThread in PyQt

I created a little example that shows 3 different and simple ways of dealing with threads. I hope it will help you find the right approach to your problem.

import sys
import time

from PyQt5.QtCore import (QCoreApplication, QObject, QRunnable, QThread,
                          QThreadPool, pyqtSignal)

# Subclassing QThread
class AThread(QThread):

    def run(self):
        count = 0
        while count < 5:
            print("A Increasing")
            count += 1

# Subclassing QObject and using moveToThread
class SomeObject(QObject):

    finished = pyqtSignal()

    def long_running(self):
        count = 0
        while count < 5:
            print("B Increasing")
            count += 1

# Using a QRunnable
# Note that a QRunnable isn't a subclass of QObject and therefore does
# not provide signals and slots.
class Runnable(QRunnable):

    def run(self):
        count = 0
        app = QCoreApplication.instance()
        while count < 5:
            print("C Increasing")
            count += 1

def using_q_thread():
    app = QCoreApplication([])
    thread = AThread()

def using_move_to_thread():
    app = QCoreApplication([])
    objThread = QThread()
    obj = SomeObject()

def using_q_runnable():
    app = QCoreApplication([])
    runnable = Runnable()

if __name__ == "__main__":

Using custom std::set comparator

std::less<> when using custom classes with operator<

If you are dealing with a set of your custom class that has operator< defined, then you can just use std::less<>.

As mentioned at C++14 has added two new find APIs:

template< class K > iterator find( const K& x );
template< class K > const_iterator find( const K& x ) const;

which allow you to do:


#include <cassert>
#include <set>

class Point {
        // Note that there is _no_ conversion constructor,
        // everything is done at the template level without
        // intermediate object creation.
        //Point(int x) : x(x) {}
        Point(int x, int y) : x(x), y(y) {}
        int x;
        int y;
bool operator<(const Point& c, int x) { return c.x < x; }
bool operator<(int x, const Point& c) { return x < c.x; }
bool operator<(const Point& c, const Point& d) {
    return c.x < d;

int main() {
    std::set<Point, std::less<>> s;
    s.insert(Point(1, -1));
    s.insert(Point(2, -2));
    s.insert(Point(0,  0));
    s.insert(Point(3, -3));
    assert(s.find(0)->y ==  0);
    assert(s.find(1)->y == -1);
    assert(s.find(2)->y == -2);
    assert(s.find(3)->y == -3);
    // Ignore 1234, find 1.
    assert(s.find(Point(1, 1234))->y == -1);

Compile and run:

g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp

More info about std::less<> can be found at: What are transparent comparators?

Tested on Ubuntu 16.10, g++ 6.2.0.

Split a string into an array of strings based on a delimiter

You can make your own function which returns TArray of string:

function mySplit(input: string): TArray<string>;
  delimiterSet: array [0 .. 0] of char; 
     // split works with char array, not a single char
  delimiterSet[0] := '&'; // some character
  result := input.Split(delimiterSet);

isset() and empty() - what to use

$var = 'abcdef';
   if (strlen($var) > 0);
      //do something, string length greater than zero
     //do something else, string length 0 or less

This is a simple example. Hope it helps.

edit: added isset in the event a variable isn't defined like above, it would cause an error, checking to see if its first set at the least will help remove some headache down the road.

Make Iframe to fit 100% of container's remaining height

try the following:

<iframe name="" src="" width="100%" style="height: 100em"/>

it worked for me

How to find the sum of an array of numbers

A short piece of JavaScript code would do this job:

var numbers = [1,2,3,4];
var totalAmount = 0;

for (var x = 0; x < numbers.length; x++) {

    totalAmount += numbers[x];

console.log(totalAmount); //10 (1+2+3+4)

How can I get a web site's favicon?

HttpWebRequest w = (HttpWebRequest)HttpWebRequest.Create("");

w.AllowAutoRedirect = true;

HttpWebResponse r = (HttpWebResponse)w.GetResponse();

System.Drawing.Image ico;
using (Stream s = r.GetResponseStream())
    ico = System.Drawing.Image.FromStream(s);


Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

Use this code to return and reload the current window:

function printpost() {
  if (window.print()) {
    return false;
  } else {

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

How Can I Remove “public/index.php” in the URL Generated Laravel?

For Laravel 4 & 5:

  1. Rename server.php in your Laravel root folder to index.php
  2. Copy the .htaccess file from /public directory to your Laravel root folder.

That's it !! :)

Create a tar.xz in one command

If you like the pipe mode, this is the most clean solution:

tar c some-dir | xz > some-dir.tar.xz

It's not necessary to put the f option in order to deal with files and then to use - to specify that the file is the standard input. It's also not necessary to specify the -z option for xz, because it's default.

It works with gzip and bzip2 too:

tar c some-dir | gzip > some-dir.tar.gz


tar c some-dir | bzip2 > some-dir.tar.bz2

Decompressing is also quite straightforward:

xzcat tarball.tar.xz | tar x
bzcat tarball.tar.bz2 | tar x
zcat tarball.tar.gz | tar x

If you have only tar archive, you can use cat:

cat archive.tar | tar x

If you need to list the files only, use tar t.

How to implement Rate It feature in Android App

All those libraries are not the solution for the problem in this post. This libraries just open a webpage to the app on google play. Instead this Play core library has more consistent interface.

So I think this is the problem, ProGuard: it obfscates some classes enough

Only read selected columns

You could also use JDBC to achieve this. Let's create a sample csv file.

write.table(x=mtcars, file="mtcars.csv", sep=",", row.names=F, col.names=T) # create example csv file

Download and save the the CSV JDBC driver from this link:

> library(RJDBC)

> <- "jdbc//csvjdbc-1.0-18.jar"
> drv <- JDBC("org.relique.jdbc.csv.CsvDriver",
> conn <- dbConnect(drv, sprintf("jdbc:relique:csv:%s", getwd()))

> head(dbGetQuery(conn, "select * from mtcars"), 3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1   21   6  160 110  3.9  2.62 16.46  0  1    4    4
2   21   6  160 110  3.9 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85  2.32 18.61  1  1    4    1

> head(dbGetQuery(conn, "select mpg, gear from mtcars"), 3)
1   21    4
2   21    4
3 22.8    4

How come I can't remove the blue textarea border in Twitter Bootstrap?


If you do not want to kill a fly with bazooka by use -webkit-appearance:none; which also kills nice sliderinputs btw and presuming you are working with the bootstrap form css selector "form-control" for your input.

This is the solution:

.form-control:focus {
    box-shadow: none!important;
    border-color: #ced4da!important;

If you want to keep a tiny small blue outline the leave border-color out.

Load a Bootstrap popover content with AJAX. Is this possible?

Here is my solution which works fine with ajax loaded content too.

 * popover handler assigned document (or 'body') 
 * triggered on hover, show content from data-content or 
 * ajax loaded from url by using data-remotecontent attribute
    selector: 'a.preview',
    placement: get_popover_placement,
    content: get_popover_content,
    html: true,
    trigger: 'hover'

function get_popover_content() {
    if ($(this).attr('data-remotecontent')) {
        // using remote content, url in $(this).attr('data-remotecontent')
        var content = $.ajax({
            url: $(this).attr('data-remotecontent'),
            type: "GET",
            data: $(this).serialize(),
            dataType: "html",
            async: false,
            success: function() {
                // just get the response
            error: function() {
                // nothing
        var container = $(this).attr('data-rel');
        if (typeof container !== 'undefined') {
            // show a specific element such as "#mydetails"
            return $(content).find(container);
        // show the whole page
        return content;
    // show standard popover content
    return $(this).attr('data-content');

function get_popover_placement(pop, el) {
    if ($(el).attr('data-placement')) {
        return $(el).attr('data-placement');
    // find out the best placement
    // ... cut ...
    return 'left';

Converting List<Integer> to List<String>

This is such a basic thing to do I wouldn't use an external library (it will cause a dependency in your project that you probably don't need).

We have a class of static methods specifically crafted to do these sort of jobs. Because the code for this is so simple we let Hotspot do the optimization for us. This seems to be a theme in my code recently: write very simple (straightforward) code and let Hotspot do its magic. We rarely have performance issues around code like this - when a new VM version comes along you get all the extra speed benefits etc.

As much as I love Jakarta collections, they don't support Generics and use 1.4 as the LCD. I am wary of Google Collections because they are listed as Alpha support level!

Simple way to check if a string contains another string in C?

if (strstr(request, "favicon") != NULL) {
    // contains

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

How to add a form load event (currently not working)

Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load from the dropdown.

A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);

A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!

What is the difference between C++ and Visual C++?

Key differences:

C++ is a general-purpose programming language, but is developed from the originally C programming language. It was developed by Bjarne Stroustrup at Bell Labs starting in 1979. C++ was originally named C with Classes. It was renamed C++ in 1983.

Visual C++, on the other hand, is not a programming language at all. It is in fact a development environment. It is an “integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages.” Microsoft Visual C++, also known as MSVC or VC++, is sold as part of the Microsoft Visual Studio app.

Calling stored procedure with return value

The version of EnterpriseLibrary on my machine had other parameters. This was working:

        SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
        retval.Direction = System.Data.ParameterDirection.ReturnValue;
        object o = cmd.Parameters["@ReturnValue"].Value;

How can I sort a List alphabetically?

Use the two argument for of Collections.sort. You will want a suitable Comparator that treats case appropriate (i.e. does lexical, not UTF16 ordering), such as that obtainable through java.text.Collator.getInstance.

How to access private data members outside the class without making "friend"s?

It's possible to access the private data of class directly in main and other's function...

here is a small code...

class GIFT
    int i,j,k;

    void Fun() 
        cout<< i<<" "<< j<<" "<< k;


int main()
     GIFT *obj=new GIFT(); // the value of i,j,k is 0
     int *ptr=(int *)obj;
     cout<<*ptr;      // you also print value of I
     cout<<*ptr;      // you also print value of J
     cout<<*ptr;      // you also print value of K

How do I left align these Bootstrap form items?

If you are saying that your problem is how to left align the form labels, see if this helps:

Try changing the text-align left / right in the CSS

.form-horizontal .control-label{
    /* text-align:right; */

Good luck!

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

/* cellpadding */
th, td { padding: 5px; }

/* cellspacing */
table { border-collapse: separate; border-spacing: 5px; } /* cellspacing="5" */
table { border-collapse: collapse; border-spacing: 0; }   /* cellspacing="0" */

/* valign */
th, td { vertical-align: top; }

/* align (center) */
table { margin: 0 auto; }

Reload child component when variables on parent component changes. Angular2

Use @Input to pass your data to child components and then use ngOnChanges ( to see if that @Input changed on the fly.

check if a file is open in Python

None of the other provided examples would work for me when dealing with this specific issue with excel on windows 10. The only other option I could think of was to try and rename the file or directory containing the file temporarily, then rename it back.

import os

    os.rename('file.xls', 'tempfile.xls')
    os.rename('tempfile.xls', 'file.xls')
except OSError:
    print('File is still open.')

Serializing a list to JSON

public static string JSONSerialize<T>(T obj)
            string retVal = String.Empty;
            using (MemoryStream ms = new MemoryStream())
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(ms, obj);
                var byteArray = ms.ToArray();
                retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
            return retVal;

Can the Android layout folder contain subfolders?

Check Bash Flatten Folder script that converts folder hierarchy to a single folder

How to get first item from a java.util.Set?

This is a difficult question I came up against the other day myself. java.util.LinkedHashSet maintains a linked list of its contents (addition-ordered by default) but does not provide any accessors. Other structure types will fail to provide O(1) on add(), remove(), and contains().

You can use a LinkedHashSet and get its iterator(), grab one element, and discard it. If you don't care too much about speed or memory when doing this frequently to numerous different sets, that is probably your solution... but that seemed wasteful to me. Plus I had a little extra desired functionality.

I ended up writing my own class, dubbed RandomAccessLinkedHashSet, which concurrently maintains a hashtable, a doubly linked list, and an order-irrelevant array. I wrote it to comply with both Set and Deque, though the Deque implementation is a little sketchy since it will fail to push() elements it already contains, a little bit of a stretch for the interface's contract. Maintaining the third structure, the array, is not necessary at all for what you're doing, but it also allows access to a random element in the set in whatever capacity you can actually provide a random value.

If you're interested I can provide this source. I haven't Serialized it yet but it works great in runtime.

If you cannot guarantee the type of Set provided in any way, then you'll have to stick with the Iterator thing.

Generating statistics from Git repository

A quick google search lead me to:

Have you tried this project? I'm sure there are similar projects.