Programs & Examples On #Gui builder

Graphical User Interface Builder for various IDEs.

How to add row of data to Jtable from values received from jtextfield and comboboxes

String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};

Here;this is the solution.

Get the date of next monday, tuesday, etc

For some reason, strtotime('next friday') display the Friday date of the current week. Try this instead:

//Current date 2020-02-03
$fridayNextWeek = date('Y-m-d', strtotime('friday next week'); //Outputs 2020-02-14

$nextFriday = date('Y-m-d', strtotime('next friday'); //Outputs 2020-02-07

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

python exception message capturing

You can try specifying the BaseException type explicitly. However, this will only catch derivatives of BaseException. While this includes all implementation-provided exceptions, it is also possibly to raise arbitrary old-style classes.

except BaseException, e:
  logger.error('Failed to do something: ' + str(e))

Find files and tar them (with spaces)

Another solution as seen here:

find var/log/ -iname "anaconda.*" -exec tar -cvzf file.tar.gz {} +

How to prevent rm from reporting that a file was not found?

As far as rm -f doing "anything else", it does force (-f is shorthand for --force) silent removal in situations where rm would otherwise ask you for confirmation. For example, when trying to remove a file not writable by you from a directory that is writable by you.

What are the ascii values of up down left right?

There is no real ascii codes for these keys as such, you will need to check out the scan codes for these keys, known as Make and Break key codes as per helppc's information. The reason the codes sounds 'ascii' is because the key codes are handled by the old BIOS interrupt 0x16 and keyboard interrupt 0x9.

                 Normal Mode            Num lock on
                 Make    Break        Make          Break
Down arrow       E0 50   E0 D0     E0 2A E0 50   E0 D0 E0 AA
Left arrow       E0 4B   E0 CB     E0 2A E0 4B   E0 CB E0 AA
Right arrow      E0 4D   E0 CD     E0 2A E0 4D   E0 CD E0 AA
Up arrow         E0 48   E0 C8     E0 2A E0 48   E0 C8 E0 AA

Hence by looking at the codes following E0 for the Make key code, such as 0x50, 0x4B, 0x4D, 0x48 respectively, that is where the confusion arise from looking at key-codes and treating them as 'ascii'... the answer is don't as the platform varies, the OS varies, under Windows it would have virtual key code corresponding to those keys, not necessarily the same as the BIOS codes, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT.. this will be found in your C++'s header file windows.h, as I recall in the SDK's include folder.

Do not rely on the key-codes to have the same 'identical ascii' codes shown here as the Operating system will reprogram the entire BIOS code in whatever the OS sees fit, naturally that would be expected because since the BIOS code is 16bit, and the OS (nowadays are 32bit protected mode), of course those codes from the BIOS will no longer be valid.

Hence the original keyboard interrupt 0x9 and BIOS interrupt 0x16 would be wiped from the memory after the BIOS loads it and when the protected mode OS starts loading, it would overwrite that area of memory and replace it with their own 32 bit protected mode handlers to deal with those keyboard scan codes.

Here is a code sample from the old days of DOS programming, using Borland C v3:

#include <bios.h>
int getKey(void){
    int key, lo, hi;
    key = bioskey(0);
    lo = key & 0x00FF;
    hi = (key & 0xFF00) >> 8;
    return (lo == 0) ? hi + 256 : lo;

This routine actually, returned the codes for up, down is 328 and 336 respectively, (I do not have the code for left and right actually, this is in my old cook book!) The actual scancode is found in the lo variable. Keys other than the A-Z,0-9, had a scan code of 0 via the bioskey routine.... the reason 256 is added, because variable lo has code of 0 and the hi variable would have the scan code and adds 256 on to it in order not to confuse with the 'ascii' codes...

Using different Web.config in development and production environment

The <appSettings> tag in web.config supports a file attribute that will load an external config with it's own set of key/values. These will override any settings you have in your web.config or add to them.

We take advantage of this by modifying our web.config at install time with a file attribute that matches the environment the site is being installed to. We do this with a switch on our installer.


<appSettings file=".\EnvironmentSpecificConfigurations\dev.config">

<appSettings file=".\EnvironmentSpecificConfigurations\qa.config">

<appSettings file=".\EnvironmentSpecificConfigurations\production.config">


  • Changes to the .config specified by the attribute won't trigger a restart of the worker process

Finding median of list in Python

def median(array):
    """Calculate median of the given list.
    # TODO: use statistics.median in Python 3
    array = sorted(array)
    half, odd = divmod(len(array), 2)
    if odd:
        return array[half]
    return (array[half - 1] + array[half]) / 2.0

JavaScript - Replace all commas in a string

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

How can I display a list view in an Android Alert Dialog?

According to the documentation, there are three kinds of lists that can be used with an AlertDialog:

  1. Traditional single-choice list
  2. Persistent single-choice list (radio buttons)
  3. Persistent multiple-choice list (checkboxes)

I will give an example of each below.

Traditional single-choice list

The way to make a traditional single-choice list is to use setItems.

enter image description here

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case 0: // horse
            case 1: // cow
            case 2: // camel
            case 3: // sheep
            case 4: // goat

// create and show the alert dialog
AlertDialog dialog = builder.create();;

There is no need for an OK button because as soon as the user clicks on a list item control is returned to the OnClickListener.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")

// add a list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
builder.setItems(animals) { dialog, which ->
    when (which) {
        0 -> { /* horse */ }
        1 -> { /* cow   */ }
        2 -> { /* camel */ }
        3 -> { /* sheep */ }
        4 -> { /* goat  */ }

// create and show the alert dialog
val dialog = builder.create()

Radio button list

enter image description here

The advantage of the radio button list over the traditional list is that the user can see what the current setting is. The way to make a radio button list is to use setSingleChoiceItems.

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a radio button list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
int checkedItem = 1; // cow
builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // user checked an item

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();;

I hard coded the chosen item here, but you could keep track of it with a class member variable in a real project.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")

// add a radio button list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItem = 1 // cow
builder.setSingleChoiceItems(animals, checkedItem) { dialog, which ->
    // user checked an item

// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
    // user clicked OK
builder.setNegativeButton("Cancel", null)

// create and show the alert dialog
val dialog = builder.create()

Checkbox list

enter image description here

The way to make a checkbox list is to use setMultiChoiceItems.

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose some animals");

// add a checkbox list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        // user checked or unchecked a box

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();;

Here I hard coded the the which items in the list were already checked. It is more likely that you would want to keep track of them in an ArrayList<Integer>. See the documentation example for more details. You can also set the checked items to null if you always want everything to start unchecked.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose some animals")

// add a checkbox list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItems = booleanArrayOf(true, false, false, true, false)
builder.setMultiChoiceItems(animals, checkedItems) { dialog, which, isChecked ->
    // user checked or unchecked a box

// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
    // user clicked OK
builder.setNegativeButton("Cancel", null)

// create and show the alert dialog
val dialog = builder.create()


  • For the context in the code above, don't use getApplicationContext() or you will get an IllegalStateException (see here for why). Instead, get a reference to the activity context, such as with this.
  • You can also populate the list items from a database or another source using setAdapter or setCursor or passing in a Cursor or ListAdapter into the setSingleChoiceItems or setMultiChoiceItems.
  • If the list is longer than will fit on the screen then the dialog will automatically scroll it. If you have a really long list, though, I'm guessing that you should probably make a custom dialog with a RecyclerView.
  • To test all of the examples above I just had a simple project with a single button than showed the dialog when clicked:

    public class MainActivity extends AppCompatActivity {
        Context context;
        protected void onCreate(Bundle savedInstanceState) {
            context = this;
        public void showAlertDialogButtonClicked(View view) {
            // example code to create alert dialog lists goes here


How to quietly remove a directory with content in PowerShell

If you want to concatenate a variable with a fixed path and a string as the dynamic path into a whole path to remove the folder, you may need the following command:

$fixPath = "C:\Users\myUserName\Desktop"
Remove-Item ("$fixPath" + "\Folder\SubFolder") -Recurse

In the variable $newPath the concatenate path is now: "C:\Users\myUserName\Desktop\Folder\SubFolder"

So you can remove several directories from the starting point ("C:\Users\myUserName\Desktop"), which is already defined and fixed in the variable $fixPath.

$fixPath = "C:\Users\myUserName\Desktop"
Remote-Item ("$fixPath" + "\Folder\SubFolder") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder1") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder2") -Recurse

VS 2012: Scroll Solution Explorer to current file

Yes, you can find that under

Tools - > Options - > Projects and Solutions - > Track Active Item in Solution Explorer

It's off by default (as you've noticed), but once it's on, Solution Explorer will expand folders and highlight the current document as you switch between files.

How organize uploaded media in WP?

I have gone around and found this free plugin after very tired with a lots of files in my WordPress default media management. After I installed the plugin, I am able to organize all images and other files into folders/ categories, just drag and drop to upload/move files into folders and drag and drop to rearrange folders. enter image description hereenter image description here

Regular expression which matches a pattern, or is an empty string

An alternative would be to place your regexp in non-capturing parentheses. Then make that expression optional using the ? qualifier, which will look for 0 (i.e. empty string) or 1 instances of the non-captured group.

For example:

/(?: some regexp )?/

In your case the regular expression would look something like this:


No | "or" operator necessary!

Here is the Mozilla documentation for JavaScript Regular Expression syntax.

"relocation R_X86_64_32S against " linking Error

Add -fPIC at the end of CMAKE_CXX_FLAGS and CMAKE_C_FLAG


set( CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -Wall --std=c++11 -O3 -fPIC" )
set( CMAKE_C_FLAGS  "${CMAKE_C_FLAGS} -Wall -O3 -fPIC" )

This solved my issue.

json parsing error syntax error unexpected end of input

For me the issue was due to single quotes for the name/value pair... data: "{'Name':'AA'}"

Once I changed it to double quotes for the name/value pair it works fine... data: '{"Name":"AA"}' or like this... data: "{\"Name\":\"AA\"}"

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 


1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Quick way to retrieve user information Active Directory

You can simplify this code to:

        DirectorySearcher searcher = new DirectorySearcher();
        searcher.Filter = "(&(objectCategory=user)(cn=steve.evans))";

        SearchResultCollection results = searcher.FindAll();

        if (results.Count == 1)
            //do what you want to do
        else if (results.Count == 0)
            //user does not exist
            //found more than one user
            //something is wrong

If you can narrow down where the user is you can set searcher.SearchRoot to a specific OU that you know the user is under.

You should also use objectCategory instead of objectClass since objectCategory is indexed by default.

You should also consider searching on an attribute other than CN. For example it might make more sense to search on the username (sAMAccountName) since it's guaranteed to be unique.

How to call a function from another controller in angularjs?

Communication between controllers is done though $emit + $on / $broadcast + $on methods.

So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:

app.controller('One', ['$scope', '$rootScope'
    function($scope) {
        $rootScope.$on("CallParentMethod", function(){

        $scope.parentmethod = function() {
            // task
app.controller('two', ['$scope', '$rootScope'
    function($scope) {
        $scope.childmethod = function() {
            $rootScope.$emit("CallParentMethod", {});

While $rootScope.$emit is called, you can send any data as second parameter.

How do I debug error ECONNRESET in Node.js?

Yes, your serving of the policy file can definitely cause the crash.

To repeat, just add a delay to your code:

net.createServer( function(socket) 
    for (i=0; i<1000000000; i++) ;
    socket.write("<?xml version=\"1.0\"?>\n");

… and use telnet to connect to the port. If you disconnect telnet before the delay has expired, you'll get a crash (uncaught exception) when socket.write throws an error.

To avoid the crash here, just add an error handler before reading/writing the socket:

    for(i=0; i<1000000000; i++);
    socket.on('error', function(error) { console.error("error", error); });
    socket.write("<?xml version=\"1.0\"?>\n");

When you try the above disconnect, you'll just get a log message instead of a crash.

And when you're done, remember to remove the delay.

Merge 2 arrays of objects

Update 12 Oct 2019

New version based only on newer Javascript and without the need of any 3rd party library.

const mergeByProperty = (target, source, prop) => {
  source.forEach(sourceElement => {
    let targetElement = target.find(targetElement => {
      return sourceElement[prop] === targetElement[prop];
    targetElement ? Object.assign(targetElement, sourceElement) : target.push(sourceElement);
var target /* arr1 */ = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var source /* arr2 */ = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];

mergeByProperty(target, source, 'name');


This answer was getting old, libs like lodash and underscore are much less needed these days. In this new version, the target (arr1) array is the one we’re working with and want to keep up to date. The source (arr2) array is where the new data is coming from, and we want it merged into our target array.

We loop over the source array looking for new data, and for every object that is not yet found in our target array we simply add that object using target.push(sourceElement) If, based on our key property ('name'), an object is already in our target array - we update its properties and values using Object.assign(targetElement, sourceElement). Our “target” will always be the same array and with updated content.

Old answer using underscore or lodash

I always arrive here from google and I'm always not satisfy from the answers. YOU answer is good but it'll be easier and neater using underscore.js


Here is a more general function that will merge 2 arrays using a property of their objects. In this case the property is 'name'

var arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];

function mergeByProperty(arr1, arr2, prop) {
  _.each(arr2, function(arr2obj) {
    var arr1obj = _.find(arr1, function(arr1obj) {
      return arr1obj[prop] === arr2obj[prop];

    arr1obj ? _.extend(arr1obj, arr2obj) : arr1.push(arr2obj);

mergeByProperty(arr1, arr2, 'name');

<script src=""></script>

[{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]

How to create folder with PHP code?

... You can then use copy() to duplicate a PHP file, although this sounds incredibly inefficient.

Inline for loop

you can use enumerate keeping the ind/index of the elements is in vm, if you make vm a set you will also have 0(1) lookups:

vm = {-1, -1, -1, -1}

print([ind if q in vm else 9999 for ind,ele in enumerate(vm) ])

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here

Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Flutter: how to make a TextField with HintText but no Underline?

decoration: InputDecoration(
 bordeRadius: BordeRadius.circular(20.0)

Git Clone - Repository not found

If you are on Windows, the repository is private, and different or not longer correct credentials were saved once, you won't have access to the repo. You will get the not found error without hinting in the failed-credential-direction. In order to reset the credentials on Windows, open Control Panel (Win+r control), select User Accounts and Credentials Manager. Locate the git account in Windows credentials (not Web credentials!) and erase this entry.

After that, cloning will pop up a login dialogue and you will be able to set these again.

Tested this with git-bash as shell in VSCode

How to use getJSON, sending data with post method?

$.getJSON() is pretty handy for sending an AJAX request and getting back JSON data as a response. Alas, the jQuery documentation lacks a sister function that should be named $.postJSON(). Why not just use $.getJSON() and be done with it? Well, perhaps you want to send a large amount of data or, in my case, IE7 just doesn’t want to work properly with a GET request.

It is true, there is currently no $.postJSON() method, but you can accomplish the same thing by specifying a fourth parameter (type) in the $.post() function:

My code looked like this:

$.post('script.php', data, function(response) {
  // Do something with the request
}, 'json');

Find an element in DOM based on an attribute value

We can use attribute selector in DOM by using document.querySelector() and document.querySelectorAll() methods.

for yours:


and by using querySelectorAll():


In querySelector() and querySelectorAll() methods we can select objects as we select in "CSS".

More about "CSS" attribute selectors in

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

SQL Server : check if variable is Empty or NULL for WHERE clause

Just use

If @searchType is null means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType is NULL

If @searchType is an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType = ''

If @searchType is null or an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''

java.util.regex - importance of Pattern.compile()?

Compile parses the regular expression and builds an in-memory representation. The overhead to compile is significant compared to a match. If you're using a pattern repeatedly it will gain some performance to cache the compiled pattern.

Named tuple and default values for optional keyword arguments

With typing.NamedTuple in Python 3.6.1+ you can provide both a default value and a type annotation to a NamedTuple field. Use typing.Any if you only need the former:

from typing import Any, NamedTuple

class Node(NamedTuple):
    val: Any
    left: 'Node' = None
    right: 'Node' = None


>>> Node(1)
Node(val=1, left=None, right=None)
>>> n = Node(1)
>>> Node(2, left=n)
Node(val=2, left=Node(val=1, left=None, right=None), right=None)

Also, in case you need both default values and optional mutability, Python 3.7 is going to have data classes (PEP 557) that can in some (many?) cases replace namedtuples.

Sidenote: one quirk of the current specification of annotations (expressions after : for parameters and variables and after -> for functions) in Python is that they are evaluated at definition time*. So, since "class names become defined once the entire body of the class has been executed", the annotations for 'Node' in the class fields above must be strings to avoid NameError.

This kind of type hints is called "forward reference" ([1], [2]), and with PEP 563 Python 3.7+ is going to have a __future__ import (to be enabled by default in 4.0) that will allow to use forward references without quotes, postponing their evaluation.

* AFAICT only local variable annotations are not evaluated at runtime. (source: PEP 526)

Generate a dummy-variable

This one liner in base R

model.matrix( ~ iris$Species - 1)


    iris$Speciessetosa iris$Speciesversicolor iris$Speciesvirginica
1                    1                      0                     0
2                    1                      0                     0
3                    1                      0                     0
4                    1                      0                     0
5                    1                      0                     0
6                    1                      0                     0
7                    1                      0                     0
8                    1                      0                     0
9                    1                      0                     0
10                   1                      0                     0
11                   1                      0                     0
12                   1                      0                     0
13                   1                      0                     0
14                   1                      0                     0
15                   1                      0                     0
16                   1                      0                     0
17                   1                      0                     0
18                   1                      0                     0
19                   1                      0                     0
20                   1                      0                     0
21                   1                      0                     0
22                   1                      0                     0
23                   1                      0                     0
24                   1                      0                     0
25                   1                      0                     0
26                   1                      0                     0
27                   1                      0                     0
28                   1                      0                     0
29                   1                      0                     0
30                   1                      0                     0
31                   1                      0                     0
32                   1                      0                     0
33                   1                      0                     0
34                   1                      0                     0
35                   1                      0                     0
36                   1                      0                     0
37                   1                      0                     0
38                   1                      0                     0
39                   1                      0                     0
40                   1                      0                     0
41                   1                      0                     0
42                   1                      0                     0
43                   1                      0                     0
44                   1                      0                     0
45                   1                      0                     0
46                   1                      0                     0
47                   1                      0                     0
48                   1                      0                     0
49                   1                      0                     0
50                   1                      0                     0
51                   0                      1                     0
52                   0                      1                     0
53                   0                      1                     0
54                   0                      1                     0
55                   0                      1                     0
56                   0                      1                     0
57                   0                      1                     0
58                   0                      1                     0
59                   0                      1                     0
60                   0                      1                     0
61                   0                      1                     0
62                   0                      1                     0
63                   0                      1                     0
64                   0                      1                     0
65                   0                      1                     0
66                   0                      1                     0
67                   0                      1                     0
68                   0                      1                     0
69                   0                      1                     0
70                   0                      1                     0
71                   0                      1                     0
72                   0                      1                     0
73                   0                      1                     0
74                   0                      1                     0
75                   0                      1                     0
76                   0                      1                     0
77                   0                      1                     0
78                   0                      1                     0
79                   0                      1                     0
80                   0                      1                     0
81                   0                      1                     0
82                   0                      1                     0
83                   0                      1                     0
84                   0                      1                     0
85                   0                      1                     0
86                   0                      1                     0
87                   0                      1                     0
88                   0                      1                     0
89                   0                      1                     0
90                   0                      1                     0
91                   0                      1                     0
92                   0                      1                     0
93                   0                      1                     0
94                   0                      1                     0
95                   0                      1                     0
96                   0                      1                     0
97                   0                      1                     0
98                   0                      1                     0
99                   0                      1                     0
100                  0                      1                     0
101                  0                      0                     1
102                  0                      0                     1
103                  0                      0                     1
104                  0                      0                     1
105                  0                      0                     1
106                  0                      0                     1
107                  0                      0                     1
108                  0                      0                     1
109                  0                      0                     1
110                  0                      0                     1
111                  0                      0                     1
112                  0                      0                     1
113                  0                      0                     1
114                  0                      0                     1
115                  0                      0                     1
116                  0                      0                     1
117                  0                      0                     1
118                  0                      0                     1
119                  0                      0                     1
120                  0                      0                     1
121                  0                      0                     1
122                  0                      0                     1
123                  0                      0                     1
124                  0                      0                     1
125                  0                      0                     1
126                  0                      0                     1
127                  0                      0                     1
128                  0                      0                     1
129                  0                      0                     1
130                  0                      0                     1
131                  0                      0                     1
132                  0                      0                     1
133                  0                      0                     1
134                  0                      0                     1
135                  0                      0                     1
136                  0                      0                     1
137                  0                      0                     1
138                  0                      0                     1
139                  0                      0                     1
140                  0                      0                     1
141                  0                      0                     1
142                  0                      0                     1
143                  0                      0                     1
144                  0                      0                     1
145                  0                      0                     1
146                  0                      0                     1
147                  0                      0                     1
148                  0                      0                     1
149                  0                      0                     1
150                  0                      0                     1

How do I put text on ProgressBar?


The solution provided by Barry above is excellent, but there's is the "flicker-problem".

As soon as the Value is above zero the OnPaint will be envoked repeatedly and the text will flicker.

There is a solution to this. We do not need VisualStyles for the object since we will be drawing it with our own code.

Add the following code to the custom object Barry wrote and you will avoid the flicker:

    private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);

    protected override void OnHandleCreated(EventArgs e)
        SetWindowTheme(this.Handle, "", "");

I did not write this myself. It found it here:

I've testet it and it works.

How to navigate through textfields (Next / Done Buttons)

Here is an implementation of tabbing using a category on UIControl. This solution has all of the advantages of the methods from Michael and Anth0, but works for all UIControls, not just UITextFields. It also works seamlessly with Interface Builder and storyboards.

Source and sample app: GitHub repository for UIControlsWithTabbing


- (BOOL)textFieldShouldReturn:(UITextField *)textField
    [textField transferFirstResponderToNextControl];
    return NO;

Assigning nextControl in Interface Builder


// UIControl+NextControl.h
// UIControlsWithTabbing

#import <UIKit/UIKit.h>

@interface UIControl (NextControl)

@property (nonatomic, weak) IBOutlet UIControl *nextControl;

- (BOOL)transferFirstResponderToNextControl;



#import "UIControl+NextControl.h"
#import <objc/runtime.h>

static char defaultHashKey;

@implementation UIControl (NextControl)

- (UIControl *)nextControl
    return objc_getAssociatedObject(self, &defaultHashKey);

- (void)setNextControl:(UIControl *)nextControl
    objc_setAssociatedObject(self, &defaultHashKey, nextControl, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

- (BOOL)transferFirstResponderToNextControl
    if (self.nextControl)
        [self.nextControl becomeFirstResponder];

        return YES;

    [self resignFirstResponder];

    return NO;


Tomcat Server Error - Port 8080 already in use

Since it is easy to tackle with Command Prompt. Open the CMD and type following.

netstat -aon | find "8080"

If a process uses above port, it should return something output like this.

TCP    xxx.xx.xx.xx:8080      ESTABLISHED     2222

The last column value (2222) is referred to the Process ID (PID).

Just KILL it as follows.

taskkill /F /PID 2222

Now you can start your server.

how to check if a form is valid programmatically using jQuery Validation Plugin

iContribute: It's never too late for a right answer.

var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
  console.log("Required field missing.");

This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.

How to run python script in webpage

With your current requirement this would work :

    def start_html():
        return '<html>'

    def end_html():
        return '</html>'

    def print_html(text):
        text = str(text)
        text = text.replace('\n', '<br>')
        return '<p>' + str(text) + '</p>'
if __name__ == '__main__':
        webpage_data =  start_html()
        webpage_data += print_html("Hi Welcome to Python test page\n")
        webpage_data += fd.write(print_html("Now it will show a calculation"))
        webpage_data += print_html("30+2=")
        webpage_data += print_html(30+2)
        webpage_data += end_html()
        with open('index.html', 'w') as fd: fd.write(webpage_data)

open the index.html and you will see what you want

Convert textbox text to integer

If your SQL database allows Null values for that field try using int? value like that :

if (this.txtboxname.Text == "" || this.txtboxname.text == null)
     value = null;
     value = Convert.ToInt32(this.txtboxname.Text);

Take care that Convert.ToInt32 of a null value returns 0 !

Convert.ToInt32(null) returns 0

How to add a boolean datatype column to an existing table in sql?

In phpmyadmin, If you need to add a boolean datatype column to an existing table with default value true:

   isAvailable boolean default true;

Converting a string to a date in DB2

You can use:

select VARCHAR_FORMAT(creationdate, 'MM/DD/YYYY') from table name

export html table to csv

A Modern Solution

Most of the proposed solutions here will break with nested tables or other elements inside your td elements. I frequently use other elements inside my tables, but only want to export the topmost table. I took some of the code found here from Calumah and added in some modern vanilla ES6 JS.

Using textContent is a better solution than innerText as innerText will return any HTML inside your td elements. However, even textContent will return the text from nested elements. An even better solution is to use custom data attributes on your td and pull the values for you CSV from there.

Happy coding!

function downloadAsCSV(tableEle, separator = ','){
    let csvRows = []
    //only get direct children of the table in question (thead, tbody)
        //using scope to only get direct tr of node
        node.querySelectorAll(':scope > tr').forEach(function(tr){
            let csvLine = []
            //again scope to only get direct children
            tr.querySelectorAll(':scope > td').forEach(function(td){
                //clone as to not remove anything from original
                let copytd = td.cloneNode(true)
                let data
                if(copytd.dataset.val) data = copytd.dataset.val.replace(/(\r\n|\n|\r)/gm, '')
                else {
                        //remove nested elements before getting text
                    data = copytd.textContent.replace(/(\r\n|\n|\r)/gm, '')
                data = data.replace(/(\s\s)/gm, ' ').replace(/"/g, '""')
    var a = document.createElement("a") = "display: none; visibility: hidden" //safari needs visibility hidden
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvRows.join('\n')) = 'testfile.csv'

Edit: cloneNode() updated to cloneNode(true) to get insides

Make Https call using HttpClient

When connect to https I got this error too, I add this line before HttpClient httpClient = new HttpClient(); and connect successfully:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

I know it from This Answer and Another Similar Anwser and the comment mentions:

This is a hack useful in development so putting a #if DEBUG #endif statement around it is the least you should do to make this safer and stop this ending up in production

Besides, I didn't try the method in Another Answer that use new X509Certificate() or new X509Certificate2() to make a Certificate, I'm not sure simply create by new() will work or not.

EDIT: Some References:

Create a Self-Signed Server Certificate in IIS 7

Import and Export SSL Certificates in IIS 7

Convert .pfx to .cer

Best practices for using ServerCertificateValidationCallback

I find value of Thumbprint is equal to x509certificate.GetCertHashString():

Retrieve the Thumbprint of a Certificate

Python Script to convert Image into Byte array

This works for me

# Convert image to bytes
import PIL.Image as Image
pil_im = Image.fromarray(image)
b = io.BytesIO(), 'jpeg')
im_bytes = b.getvalue()
return im_bytes

git: fatal unable to auto-detect email address

1st Step : Go for the workstation In my case -> cd /c/Users/rashni/MyWS/WSpace

2nd Step : create a folder In my case -> mkdir config

3rd step : use command In my case -> git config --global "rashni" In my case -> git config --global [email protected]

4th step : To check all configuration(optional) In my case -> git config --list

Java getting the Enum name given the Enum Value

Try, the following code..

    public String toString() {

&& (AND) and || (OR) in IF statements

No, if a is true (in a or test), b will not be tested, as the result of the test will always be true, whatever is the value of the b expression.

Make a simple test:

if (true || ((String) null).equals("foobar")) {

will not throw a NullPointerException!

Select by partial string from a pandas DataFrame

If anyone wonders how to perform a related problem: "Select column by partial string"


df.filter(like='hello')  # select columns which contain the word hello

And to select rows by partial string matching, pass axis=0 to filter:

# selects rows which contain the word hello in their index label
df.filter(like='hello', axis=0)  

How do I detect the Python version at runtime?

Just in case you want to see all of the gory details in human readable form, you can use:

import platform;


Output for my system:

3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56) 
[GCC 7.2.0]

Something very detailed but machine parsable would be to get the version_info object from platform.sys, instead, and then use its properties to take a predetermined course of action. For example:

import platform;


Output on my system:

sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)

Create new user in MySQL and give it full access to one database

The below command will work if you want create a new user give him all the access to a specific database(not all databases in your Mysql) on your localhost.

GRANT ALL PRIVILEGES ON test_database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This will grant all privileges to one database test_database (in your case dbTest) to that user on localhost.

Check what permissions that above command issued to that user by running the below command.

SHOW GRANTS FOR 'user'@'localhost'

Just in case, if you want to limit the user access to only one single table

GRANT ALL ON mydb.table_name TO 'someuser'@'host';

Update all objects in a collection using LINQ

I am doing this

Collection.All(c => { c.needsChange = value; return true; });

Utilizing multi core for tar+gzip/bzip compression/decompression

You can also use the tar flag "--use-compress-program=" to tell tar what compression program to use.

For example use:

tar -c --use-compress-program=pigz -f tar.file dir_to_zip 

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:


--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
    date_at <= now() - INTERVAL '130 DAYS'


Tip 1

You can append multiple operands. E.g.: how to get last day of current month?


Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);

More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Integer.toString(int i) vs String.valueOf(int i)

You shouldn't worry about this extra call costing you efficiency problems. If there's any cost, it'll be minimal, and should be negligible in the bigger picture of things.

Perhaps the reason why both exist is to offer readability. In the context of many types being converted to String, then various calls to String.valueOf(SomeType) may be more readable than various SomeType.toString calls.

Conda activate not working?

For windows, Use the Anaconda Powershell Prompt

enter image description here

Phone Number Validation MVC

Try this:

[DataType(DataType.PhoneNumber, ErrorMessage = "Provided phone number not valid")]

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

How to get parameter on Angular2 route in Angular way?

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
        switchMap((params: ParamMap) => this._entityId = params.get('id'))

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

Bash ignoring error for a particular command

The solution:

particular_script || true


$ cat /tmp/

set -e

echo one
particular_script || true
echo two
echo three

$ bash /tmp/

three will be never printed.

Also, I want to add that when pipefail is on, it is enough for shell to think that the entire pipe has non-zero exit code when one of commands in the pipe has non-zero exit code (with pipefail off it must the last one).

$ set -o pipefail
$ false | true ; echo $?
$ set +o pipefail
$ false | true ; echo $?

How to find if a native DLL file is compiled as x64 or x86?

For an unmanaged DLL file, you need to first check if it is a 16-bit DLL file (hopefully not). Then check the IMAGE\_FILE_HEADER.Machine field.

Someone else took the time to work this out already, so I will just repeat here:

To distinguish between a 32-bit and 64-bit PE file, you should check IMAGE_FILE_HEADER.Machine field. Based on the Microsoft PE and COFF specification below, I have listed out all the possible values for this field:

IMAGE_FILE_MACHINE_UNKNOWN 0x0 The contents of this field are assumed to be applicable to any machine type

IMAGE_FILE_MACHINE_AM33 0x1d3 Matsushita AM33


IMAGE_FILE_MACHINE_ARM 0x1c0 ARM little endian


IMAGE_FILE_MACHINE_I386 0x14c Intel 386 or later processors and compatible processors

IMAGE_FILE_MACHINE_IA64 0x200 Intel Itanium processor family

IMAGE_FILE_MACHINE_M32R 0x9041 Mitsubishi M32R little endian




IMAGE_FILE_MACHINE_POWERPC 0x1f0 Power PC little endian

IMAGE_FILE_MACHINE_POWERPCFP 0x1f1 Power PC with floating point support

IMAGE_FILE_MACHINE_R4000 0x166 MIPS little endian







Yes, you may check IMAGE_FILE_MACHINE_AMD64|IMAGE_FILE_MACHINE_IA64 for 64bit and IMAGE_FILE_MACHINE_I386 for 32bit.

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

Two ways that can be works

1: Uninstall app from mobile device manually

2: Open command prompt , trace path of adband execute following command

adb uninstall your_package_name

How to create a date object from string in javascript

First extract the string like this

var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);


var d = new Date( dateString[3], dateString[2]-1, dateString[1] );

What are best practices for REST nested resources?

What you have done is correct. In general there can be many URIs to the same resource - there are no rules that say you shouldn't do that.

And generally, you may need to access items directly or as a subset of something else - so your structure makes sense to me.

Just because employees are accessible under department:


Doesn't mean they can't be accessible under company too:


Which would return employees for that company. It depends on what is needed by your consuming client - that is what you should be designing for.

But I would hope that all URLs handlers use the same backing code to satisfy the requests so that you aren't duplicating code.

Difference between webdriver.Dispose(), .Close() and .Quit()

Difference between driver.close() & driver.quit()

driver.close – It closes the the browser window on which the focus is set.

driver.quit – It basically calls driver.dispose method which in turn closes all the browser windows and ends the WebDriver session gracefully.

Increase number of axis ticks

You can supply a function argument to scale, and ggplot will use that function to calculate the tick locations.

dat <- data.frame(x = rnorm(100), y = rnorm(100))
number_ticks <- function(n) {function(limits) pretty(limits, n)}

ggplot(dat, aes(x,y)) +
  geom_point() +
  scale_x_continuous(breaks=number_ticks(10)) +

How to use LINQ Distinct() with multiple fields

public List<ItemCustom2> GetBrandListByCat(int id)

        var OBJ = (from a in db.Items
                   join b in db.Brands on a.BrandId equals b.Id into abc1
                   where (a.ItemCategoryId == id)
                   from b in abc1.DefaultIfEmpty()
                   select new
                       ItemCategoryId = a.ItemCategoryId,
                       Brand_Name = b.Name,
                       Brand_Id = b.Id,
                       Brand_Pic = b.Pic,


        List<ItemCustom2> ob = new List<ItemCustom2>();
        foreach (var item in OBJ)
            ItemCustom2 abc = new ItemCustom2();
            abc.CategoryId = item.ItemCategoryId;
            abc.BrandId = item.Brand_Id;
            abc.BrandName = item.Brand_Name;
            abc.BrandPic = item.Brand_Pic;
        return ob;


How do I add a Font Awesome icon to input field?

to work this with unicode or fontawesome, you should add a span with class like below, because input tag not support pseudo classes like :after. this is not a direct solution

in html:

   <span class="button1 search"></span>
<input name="username">

in css:

.button1 {
    background-color: #B9D5AD;
    border-radius: 0.2em 0 0 0.2em;
    box-shadow: 1px 0 0 rgba(0, 0, 0, 0.5), 2px 0 0 rgba(255, 255, 255, 0.5); 
    pointer-events: none;
    margin:1px 12px;    
    border-radius: 0.2em;    
    color: #333333;
    cursor: pointer;
    position: absolute;
    padding: 3px;
    text-decoration: none;   


String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

If you really want to match only the dot, then StringComparison.Ordinal would be fastest, as there is no case-difference.

"Ordinal" doesn't use culture and/or casing rules that are not applicable anyway on a symbol like a ..

Appending the same string to a list of strings in Python

my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
my_new_list = [x + string for x in my_list]
print my_new_list

This will print:

['foobar', 'fobbar', 'fazbar', 'funkbar']

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;

How to clear textarea on click?

<textarea name="post" id="post" onclick="if(this.value == 'Write Something here..............') this.value='';" onblur="if(this.value == '') this.value='Write Something here..............';" >Write Something here..............</textarea>

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

If you are adding a foreign key and faced this error, it could be the value in the child table is not present in the parent table.

Let's say for the column to which the foreign key has to be added has all values set to 0 and the value is not available in the table you are referencing it.

You can set some value which is present in the parent table and then adding foreign key worked for me.

Copy files to network computers on windows command line

Why for? What do you want to iterate? Try this.

call :cpy pc-name-1
call :cpy pc-name-2

net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

What are the minimum margins most printers can handle?

The margins vary depending on the printer. In Windows GDI, you call the following functions to get the built-in margins, the "no-print zone":

GetDeviceCaps(hdc, PHYSICALWIDTH);
GetDeviceCaps(hdc, PHYSICALHEIGHT);
GetDeviceCaps(hdc, PHYSICALOFFSETX);
GetDeviceCaps(hdc, PHYSICALOFFSETY);

Printing right to the edge is called a "bleed" in the printing industry. The only laser printer I ever knew to print right to the edge was the Xerox 9700: 120 ppm, $500K in 1980.

How do I jump out of a foreach loop in C#?

You can use break which jumps out of the closest enclosing loop, or you can just directly return true

Printing Even and Odd using two Threads in Java

This can be acheived using Lock and Condition :

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class EvenOddThreads {

    public static void main(String[] args) throws InterruptedException {
        Printer p = new Printer();
        Thread oddThread = new Thread(new PrintThread(p,false),"Odd  :");
        Thread evenThread = new Thread(new PrintThread(p,true),"Even :");


class PrintThread implements Runnable{
    Printer p;
    boolean isEven = false;

    PrintThread(Printer p, boolean isEven){
        this.p = p;
        this.isEven = isEven;

    public void run() {
        int i = (isEven==true) ? 2 : 1;
        while(i < 10 ){

class Printer{

    boolean isEven = true;
    Lock lock = new ReentrantLock();
    Condition condEven = lock.newCondition();
    Condition condOdd = lock.newCondition();

    public void printEven(int no){
            try {
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
        System.out.println(Thread.currentThread().getName() +no);
        isEven = true;

    public void printOdd(int no){
            try {
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
        System.out.println(Thread.currentThread().getName() +no);
        isEven = false;

Fail during installation of Pillow (Python module) in Linux

Working successfuly :

 sudo apt install libjpeg8-dev zlib1g-dev 

How do I join two SQLite tables in my Android application?

In addition to @pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN like this

SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1

via raw query like this -

String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
        + " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
        + " WHERE " + RefuelTable.ID + " = " +  id;
Cursor c = db.rawQuery(

because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -

FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1

and hence be able to take advanatage of the SQLiteDatabase.query() helper method

Cursor c = db.query(
        RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
        Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
        RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " +  id,

For a detailed blog post check this

IE and Edge fix for object-fit: cover;

I just used the @misir-jafarov and is working now with :

  • IE 8,9,10,11 and EDGE detection
  • used in Bootrap 4
  • take the height of its parent div
  • cliped vertically at 20% of top and horizontally 50% (better for portraits)

here is my code :

if (document.documentMode || /Edge/.test(navigator.userAgent)) {
    jQuery('.art-img img').each(function(){
        var t = jQuery(this),
            s = 'url(' + t.attr('src') + ')',
            p = t.parent(),
            d = jQuery('<div></div>');

            'height'                : t.parent().css('height'),
            'background-size'       : 'cover',
            'background-repeat'     : 'no-repeat',
            'background-position'   : '50% 20%',
            'background-image'      : s

Hope it helps.

Replace multiple characters in a C# string

I know this question is super old, but I want to offer 2 options that are more efficient:

1st off, the extension method posted by Paul Walls is good but can be made more efficient by using the StringBuilder class, which is like the string data type but made especially for situations where you will be changing string values more than once. Here is a version I made of the extension method using StringBuilder:

public static string ReplaceChars(this string s, char[] separators, char newVal)
    StringBuilder sb = new StringBuilder(s);
    foreach (var c in separators) { sb.Replace(c, newVal); }
    return sb.ToString();

I ran this operation 100,000 times and using StringBuilder took 73ms compared to 81ms using string. So the difference is typically negligible, unless you're running many operations or using a huge string.

Secondly, here is a 1 liner loop you can use:

foreach (char c in separators) { s = s.Replace(c, '\n'); }

I personally think this is the best option. It is highly efficient and doesn't require writing an extension method. In my testing this ran the 100k iterations in only 63ms, making it the most efficient. Here is an example in context:

string s = "this;is,\ra\t\n\n\ntest";
char[] separators = new char[] { ' ', ';', ',', '\r', '\t', '\n' };
foreach (char c in separators) { s = s.Replace(c, '\n'); }

Credit to Paul Walls for the first 2 lines in this example.

.gitignore all the .DS_Store files in every folder and subfolder

Step 1, delete all the *.DS_store files. One can run

git rm -f *.DS_Store

but be aware that rm -f can be a bit dangerous if you have a typo! Step two: add


to .gitignore. This worked for me!

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

XPath: Get parent node from child node

You can use the two dots at the end of expression, too. See this example:


Node.js EACCES error when listening on most ports

The same issue happened to me. You need to check out your server.js file where you are setting your listening port. Change port number wisely in all places, and it will solve your issue hopefully.

How to correctly represent a whitespace character

Which whitespace character? The most common is the normal space, which is between each word in my sentences. This is just " ".

Missing artifact com.sun:tools:jar

If this problem still happens, it might be because of a JDK of version equal or greater than 11.

The tools.jar archive has been removed from the lib folder in those JDK's (see this answer to a similar question). In that case, try to use other versions of the libraries, that do not rely on the com.sun:tools library.

Adding a y-axis label to secondary y-axis in matplotlib

I don't have access to Python right now, but off the top of my head:

fig = plt.figure()

axes1 = fig.add_subplot(111)
# set props for left y-axis here

axes2 = axes1.twinx()   # mirror them

batch script - run command on each file in directory

you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %% by % :

for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx

If you can run powershell it will be :

Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }

multiple figure in latex with captions

Look at the Subfloats section of,_Figures_and_Captions.


  \subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
  \subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
  \subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
  \subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
  \subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
  \subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}


How to check if a String contains any of some strings

var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";

Import a custom class in Java

First off, avoid using the default package.

Second of all, you don't need to import the class; it's in the same package.

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

On Mac Sierra if using Homebrew then do:

sudo ln -s /usr/local/Cellar/[email protected]/5.6.34/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

Replace non ASCII character from string

This will search and replace all non ASCII letters:

String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");

Convert file to byte array and vice versa

You cannot do it for File, which is primarily an intelligent file path. Can you refactor your code so that it declares the variables, and passes around arguments, with type OutputStream instead of FileOutputStream? If so, see classes and

OutputStream outStream = new ByteArrayOutputStream();
byte[] data = outStream.toByteArray();
InputStream inStream = new ByteArrayInputStream(data);

UIView touch event in controller

Swift 4.2:

@IBOutlet weak var viewLabel1: UIView!
@IBOutlet weak var viewLabel2: UIView!
  override func viewDidLoad() {

    let myView = UITapGestureRecognizer(target: self, action: #selector(someAction(_:)))

 @objc func someAction(_ sender:UITapGestureRecognizer){
   viewLabel2.isHidden = true

javac is not recognized as an internal or external command, operable program or batch file

If java command is working and getting problem with javac. then first check in jdk's bin directory javac.exe file is there or not. If javac.exe file is exist then set JAVA_HOME as System variable.

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

If you are Clion/anyOtherJetBrainsIDE user, and yourFile.exe cause this problem, just delete it and let the app create and link it with libs from a scratch. It helps.

C++ pass an array by reference If the type of a parameter includes a type of the form “pointer to array of unknown bound of T” or “reference to array of unknown bound of T,” the program is ill-formed

Listing files in a specific "folder" of a AWS S3 bucket

While everybody say that there are no directories and files in s3, but only objects (and buckets), which is absolutely true, I would suggest to take advantage of CommonPrefixes, described in this answer. So, you can do following to get list of "folders" (commonPrefixes) and "files" (objectSummaries):

ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucket.getName()).withPrefix(prefix).withDelimiter(DELIMITER);
ListObjectsV2Result listing = s3Client.listObjectsV2(req);
for (String commonPrefix : listing.getCommonPrefixes()) {
for (S3ObjectSummary summary: listing.getObjectSummaries()) {

In your case, for objectSummaries (files) it should return (in case of correct prefix):

for commonPrefixes:


How to get first 5 characters from string

You can get your result by simply use substr():

Syntax substr(string,start,length)


$myStr = "HelloWordl";
echo substr($myStr,0,5);

Output :


rename the columns name after cbind the data

If you offer cbind a set of arguments all of whom are vectors, you will get not a dataframe, but rather a matrix, in this case an all character matrix. They have different features. You can get a dataframe if some of your arguments remain dataframes, Try:

merger <- cbind(Date =as.character(Date),
             weather1[ , c("High", "Low", "Avg..High", "Avg.Low")] , 
             ScnMov =sale$Scanned.Movement[a] )

How do I find my host and username on mysql?

type this command

select CURRENT_USER();

You will get the username and server

React onClick and preventDefault() link refresh/redirect?

try bind(this) so your code looks like below --

 <a className="upvotes" onClick={this.upvote.bind(this)}>upvote</a>

or if you are writing in es6 react component in constructor you could do this

   this.upvote = this.upvote.bind(this);

upvote(e){   // function upvote
   return false


Windows.history.back() + location.reload() jquery

It will have already gone back before it executes the reload.

You would be better off to replace:




Undefined Reference to

I had this issue when I forgot to add the new .h/.c file I created to the meson recipe so this is just a friendly reminder.

How do you auto format code in Visual Studio?

  1. Go to Tools -> Extensions & Updates and type "productivity" in search: 1
  2. Install 'Productivity Power Tools 2015'
  3. Restart VS.
  4. Go to Tools -> Options -> Productivity Power Tools -> Power Commands and check "Format document on save": 2

How to convert int to QString?

And if you want to put it into string within some text context, forget about + operator. Simply do:

// Qt 5 + C++11
auto i = 13;    
auto printable = QStringLiteral("My magic number is %1. That's all!").arg(i);

// Qt 5
int i = 13;    
QString printable = QStringLiteral("My magic number is %1. That's all!").arg(i);

// Qt 4
int i = 13;    
QString printable = QString::fromLatin1("My magic number is %1. That's all!").arg(i);

increment date by one month

function dayOfWeek($date){
    return DateTime::createFromFormat('Y-m-d', $date)->format('N');

Usage examples:

echo dayOfWeek(2016-12-22);
// "4"
echo dayOfWeek(date('Y-m-d'));
// "4"

Git will not init/sync/update new submodules

  • Remove the submodule from your .git/config
  • Run git submodule init command
  • Go to your submodule directory and run git pull origin master

It should works now

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

There is a way to insert sections in partial views, though it's not pretty. You need to have access to two variables from the parent View. Since part of your partial view's very purpose is to create that section, it makes sense to require these variables.

Here's what it looks like to insert a section in the partial view:

@model KeyValuePair<WebPageBase, HtmlHelper>
    Model.Key.DefineSection("SectionNameGoesHere", () =>

And in the page inserting the partial view...

@Html.Partial(new KeyValuePair<WebPageBase, HtmlHelper>(this, Html))

You can also use this technique to define the contents of a section programmatically in any class.


Corrupted Access .accdb file: "Unrecognized Database Format"

After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...

Is it possible in Java to catch two exceptions in the same catch block?

For Java < 7 you can use if-else along with Exception:

try {
    // common logic to handle both exceptions
} catch (Exception ex) {
    if (ex instanceof Exception1 || ex instanceof Exception2) {

    else {
        throw ex;
        // or if you don't want to have to declare Exception use
        // throw new RuntimeException(ex);

Edited and replaced Throwable with Exception.

Quoting backslashes in Python string literals

If you are here for a filepath just use "\\"

import os
path = r"c:\file"+"\\"+"path"

which will outputc:\file\path

@Resource vs @Autowired

Both of them are equally good. The advantage of using Resource is in future if you want to another DI framework other than spring, your code changes will be much simpler. Using Autowired your code is tightly coupled with springs DI.

Tests not running in Test Explorer

I had same issue after update to Visual Studio 16.4.1. Go to Test explorer -> Settings button -> Processor Architecture for AnyCPU projects -> x64

Android: Expand/collapse animation

I stumbled over the same problem today and I guess the real solution to this question is this

<LinearLayout android:id="@+id/container"

You will have to set this property for all topmost layouts, which are involved in the shift. If you now set the visibility of one layout to GONE, the other will take the space as the disappearing one is releasing it. There will be a default animation which is some kind of "fading out", but I think you can change this - but the last one I have not tested, for now.

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Java - escape string to prevent SQL injection

Using a regular expression to remove text which could cause a SQL injection sounds like the SQL statement is being sent to the database via a Statement rather than a PreparedStatement.

One of the easiest ways to prevent an SQL injection in the first place is to use a PreparedStatement, which accepts data to substitute into a SQL statement using placeholders, which does not rely on string concatenations to create an SQL statement to send to the database.

For more information, Using Prepared Statements from The Java Tutorials would be a good place to start.

How to get all Windows service names starting with a common word?

Save it as a .ps1 file and then execute

powershell -file "path\to your\start stop nation service command file.ps1"

What does %5B and %5D in POST requests stand for?

As per this answer over here: str='foo%20%5B12%5D' encodes foo [12]:

%20 is space
%5B is '['
and %5D is ']'

This is called percent encoding and is used in encoding special characters in the url parameter values.

EDIT By the way as I was reading, it just occurred to me why so many people make the same search. See the note on the bottom of the page:

Also note that if one wishes to follow the more recent RFC3986 for URL's, making square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following may help.

function fixedEncodeURI (str) {
    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');

Hopefully this will help people sort out their problems when they stumble upon this question.

Put Excel-VBA code in module or sheet?

Definitely in Modules.

  • Sheets can be deleted, copied and moved with surprising results.
  • You can't call code in sheet "code-behind" from other modules without fully qualifying the reference. This will lead to coupling of the sheet and the code in other modules/sheets.
  • Modules can be exported and imported into other workbooks, and put under version control
  • Code in split logically into modules (data access, utilities, spreadsheet formatting etc.) can be reused as units, and are easier to manage if your macros get large.

Since the tooling is so poor in primitive systems such as Excel VBA, best practices, obsessive code hygiene and religious following of conventions are important, especially if you're trying to do anything remotely complex with it.

This article explains the intended usages of different types of code containers. It doesn't qualify why these distinctions should be made, but I believe most developers trying to develop serious applications on the Excel platform follow them.

There's also a list of VBA coding conventions I've found helpful, although they're not directly related to Excel VBA. Please ignore the crazy naming conventions they have on that site, it's all crazy hungarian.

What is the `zero` value for time.Time in Go?

Invoking an empty time.Time struct literal will return Go's zero date. Thus, for the following print statement:


The output is:

0001-01-01 00:00:00 +0000 UTC

For the sake of completeness, the official documentation explicitly states:

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

How do I list all the files in a directory and subdirectories in reverse chronological order?

Try this one:

find . -type f -printf "%T@ %p\n" | sort -nr | cut -d\  -f2-

Table with table-layout: fixed; and how to make one column wider

What you could do is something like this (pseudocode):

<container table>
      <"300px" table>
      <fixed layout table>

Basically, split up the table into two tables and have it contained by another table.

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

I prefer readability first which most often does not use the setup method. I make an exception when a basic setup operation takes a long time and is repeated within each test.
At that point I move that functionality into a setup method using the @BeforeClass annotation (optimize later).

Example of optimization using the @BeforeClass setup method: I use dbunit for some database functional tests. The setup method is responsible for putting the database in a known state (very slow... 30 seconds - 2 minutes depending on amount of data). I load this data in the setup method annotated with @BeforeClass and then run 10-20 tests against the same set of data as opposed to re-loading/initializing the database inside each test.

Using Junit 3.8 (extending TestCase as shown in your example) requires writing a little more code than just adding an annotation, but the "run once before class setup" is still possible.

Remove all classes that begin with a certain string

In one line ... Removes all classes that match a regular expression someRegExp

$('#my_element_id').removeClass( function() { return (this.className.match(/someRegExp/g) || []).join(' ').replace(prog.status.toLowerCase(),'');});

Combine a list of data frames into one data frame by row

How it should be done in the tidyverse:

df.dplyr.purrr <- listOfDataFrames %>% map_df(bind_rows)

Angular @ViewChild() error: Expected 2 arguments, but got 1

In Angular 8 , ViewChild takes 2 parameters:

Try like this:

@ViewChild('nameInput', { static: false }) nameInputRef: ElementRef;


{ static: false }

If you set static false, the child component ALWAYS gets initialized after the view initialization in time for the ngAfterViewInit/ngAfterContentInit callback functions.

{ static: true}

If you set static true, the child component initialization will take place at the view initialization at ngOnInit

By default you can use { static: false }. If you are creating a dynamic view and want to use the template reference variable, then you should use { static: true}

For more info, you can read this article

Working Demo

In the demo, we will scroll to a div using template reference variable.

 @ViewChild("scrollDiv", { static: true }) scrollTo: ElementRef;

With { static: true }, we can use this.scrollTo.nativeElement in ngOnInit, but with { static: false }, this.scrollTo will be undefined in ngOnInit , so we can access in only in ngAfterViewInit

PHPmailer sending HTML CODE

just you need to pass true as an argument to IsHTML() function.

Checking whether the pip is installed?

pip list is a shell command. You should run it in your shell (bash/cmd), rather than invoke it from python interpreter.

pip does not provide a stable API. The only supported way of calling it is via subprocess, see docs and the code at the end of this answer.

However, if you want to just check if pip exists locally, without running it, and you are running Linux, I would suggest that you use bash's which command:

which pip

It should show you whether the command can be found in bash's PATH/aliases, and if it does, what does it actually execute.

If running pip is not an issue, you could just do:

python -m pip --version

If you really need to do it from a python script, you can always put the import statement into a try...except block:

    import pip
except ImportError:
    print("Pip not present.")

Or check what's the output of a pip --version using subprocess module:

subprocess.check_call([sys.executable, '-m', 'pip', '--version'])

jQuery load more data on scroll

Improving on @deepakssn answer. There is a possibility that you want the data to load a bit before we actually scroll to the bottom.

var scrollLoad = true;
 if (scrollLoad && ($(document).height() - $(window).height())-$(window).scrollTop()<=800){
    // fetch data when we are 800px above the document end
    scrollLoad = false;

[var scrollLoad] is used to block the call until one new data is appended.

Hope this helps.

Use a LIKE statement on SQL Server XML Datatype

Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.

FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'

I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.

EDIT: As Cliff mentions it, you could use:

...nvarchar if there's characters that don't convert to varchar

What is the difference between '/' and '//' when used for division?

In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.

Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.

You can find a detailed description at

What is a daemon thread in Java?

Daemon threads are low-priority threads whose only role is to provide services to user threads.

Daemon threads are generally created by JVM for background tasks while user threads are created by application for foreground tasks.

Since daemon threads are meant to serve user threads and are only needed while user threads are running, they won't prevent the JVM from exiting once all user threads have finished their execution.

We can set non-daemon thread to daemon using :


How to prevent a browser from storing passwords

While the previous solutions are very correct, if you absolutely need the feature then you can mimic the situation with custom input using text-field and JavaScript.

For secure usage, you can use any cryptography technique. So this way you will bypass the browser's password saving behavior.

If you want to know more about the idea, we can discuss that on chat. But the gist is discussed in previous answers and you can get the idea.

ESLint not working in VS Code?

In my case, since I was using TypeScript with React, the fix was simply to tell ESLint to also validate these files. This needs to go in your user settings:

"eslint.validate": [ "javascript", "javascriptreact", "html", "typescriptreact" ],

MySQL - UPDATE query based on SELECT Query

You can use:

UPDATE Station AS st1, StationOld AS st2
   SET st1.already_used = 1
 WHERE st1.code = st2.code

Align HTML input fields by :

Set a width on the form element (which should exist in your example! ) and float (and clear) the input elements. Also, drop the br elements.

Get an array of list element contents in jQuery

And in clean javascript:

var texts = [], lis = document.getElementsByTagName("li");
for(var i=0, im=lis.length; im>i; i++)


How can I convert a string to a float in mysql?

It turns out I was just missing DECIMAL on the CAST() description:


Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.

Thus, the following query worked:

latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));

WPF TemplateBinding vs RelativeSource TemplatedParent

One more thing - TemplateBindings don't allow value converting. They don't allow you to pass a Converter and don't automatically convert int to string for example (which is normal for a Binding).

Echo equivalent in PowerShell for script testing

Write-Host "filesizecounter : " $filesizecounter 

Java: convert List<String> to a String

You can use the apache commons library which has a StringUtils class and a join method.

Check this link:

Note that the link above may become obsolete over time, in which case you can just search the web for "apache commons StringUtils", which should allow you to find the latest reference.

(referenced from this thread) Java equivalents of C# String.Format() and String.Join()

JOptionPane - input dialog box program

After that you have to parse the results. Suppose results are in integers, then

int testint1 = Integer.parse(test1);

Similarly others should be parsed. Now the results should be checked for two higher marks in them, by using if statement After that take out the average.

android get real path by Uri.getPath()

Hii here is my complete code for taking image from camera or galeery

//My variable declaration

protected static final int CAMERA_REQUEST = 0;
    protected static final int GALLERY_REQUEST = 1;
    Bitmap bitmap;
    Uri uri;
    Intent picIntent = null;


if (v.getId(){

//method body

private void startDilog() {
    AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(yourActivity.this);
    myAlertDilog.setTitle("Upload picture option..");
    myAlertDilog.setMessage("Where to upload picture????");
    myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
    myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

//And rest of things

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==GALLERY_REQUEST){
        if (resultCode==RESULT_OK){
            if (data!=null) {
                uri = data.getData();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                try {
                    BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                    options.inSampleSize = calculateInSampleSize(options, 100, 100);
                    options.inJustDecodeBounds = false;
                    Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                } catch (FileNotFoundException e) {
            }else {
                Toast.makeText(getApplicationContext(), "Cancelled",
        }else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Cancelled",
    }else if (requestCode == CAMERA_REQUEST) {
        if (resultCode == RESULT_OK) {
            if (data.hasExtra("data")) {
                bitmap = (Bitmap) data.getExtras().get("data");
                uri = getImageUri(YourActivity.this,bitmap);
                File finalFile = new File(getRealPathFromUri(uri));
            } else if (data.getExtras() == null) {

                        "No extras to retrieve!", Toast.LENGTH_SHORT)

                BitmapDrawable thumbnail = new BitmapDrawable(
                        getResources(), data.getData().getPath());


        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Cancelled",

private String getRealPathFromUri(Uri tempUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = this.getContentResolver().query(tempUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
public 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) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
    return inSampleSize;

private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
    return Uri.parse(path);

How to shift a column in Pandas DataFrame

This is how I do it:

df_ext = pd.DataFrame(index=pd.date_range(df.index[-1], periods=8, closed='right'))
df2 = pd.concat([df, df_ext], axis=0, sort=True)
df2["forecast"] = df2["some column"].shift(7)

Basically I am generating an empty dataframe with the desired index and then just concatenate them together. But I would really like to see this as a standard feature in pandas so I have proposed an enhancement to pandas.

Parse an URL in JavaScript

I wrote a javascript url parsing library, URL.js, you can use it for this.


url.parse("").get.img_id === "33"

What is the proper #include for the function 'sleep()'?

What is the proper #include for the function 'sleep()'?

sleep() isn't Standard C, but POSIX so it should be:

#include <unistd.h>

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Let's do a test with 2 examples:

    $memory = (int)ini_get("memory_limit"); // Display your current value in php.ini (for example: 64M)
    echo "original memory: ".$memory."<br>";
    ini_set('memory_limit','128M'); // Try to override the memory limit for this script
    echo "new memory:".$memory;
    // Will display:
    // original memory: 64
    // new memory: 64

The above example doesn't work for overriding the memory_limit value. But This will work:

    $memory = (int)ini_get("memory_limit"); // get the current value
    ini_set('memory_limit','128'); // override the value
    echo "original memory: ".$memory."<br>"; // echo the original value
    $new_memory = (int)ini_get("memory_limit"); // get the new value
    echo "new memory: ".$new_memory;  // echo the new value
    // Will display:
    // original memory: 64
    // new memory: 128

You have to place the ini_set('memory_limit','128M'); at the top of the file or at least before any echo.

As for me, suhosin wasn't the solution because it doesn't even appear in my phpinfo(), but this worked:

    ini_set('memory_limit','2048M'); // set at the top of the file

Eclipse: How do you change the highlight color of the currently selected method/expression?

1 - right click the highlight whose color you want to change

2 - select "Properties" in the popup menu

3 - choose the new color (as coobird suggested)

This solution is easy because you dont have to search for the highlight by its name ("Ocurrence" or "Write Ocurrence" etc), just right click and the appropriate window is shown.

Is there a command to undo git init?

In windows, type rmdir .git or rmdir /s .git if the .git folder has subfolders.

If your git shell isn't setup with proper administrative rights (i.e. it denies you when you try to rmdir), you can open a command prompt (possibly as administrator--hit the windows key, type 'cmd', right click 'command prompt' and select 'run as administrator) and try the same commands.

rd is an alternative form of the rmdir command.

YAML equivalent of array of objects in JSON


You want this:

  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015


The YAML equivalent of a JSON object is a mapping, which looks like these:

# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2

Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:

# OK
   foo: 1
   bar: 2
# Parse error
   foo: 1
    bar: 2


The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):

# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz

In a block sequence the -s must be in the same column.


Let's turn your JSON into YAML. Here's your JSON:

{"AAPL": [
    "shares": -75.088,
    "date": "11/27/2015"
    "shares": 75.088,
    "date": "11/26/2015"

As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.

Starting from the inside out, we have objects that look like this:

  "shares": -75.088,
  "date": "11/27/2015"

The equivalent YAML mapping is:

shares: -75.088
date: 11/27/2015

We have two of these in an array (sequence):

- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Note how the -s line up and the first characters of the mapping keys line up.

Finally, this sequence is itself a value in a mapping with the key AAPL:

  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Parsing this and converting it back to JSON yields the expected result:

  "AAPL": [
      "date": "11/27/2015", 
      "shares": -75.088
      "date": "11/26/2015", 
      "shares": 75.088

You can see it (and edit it interactively) here.

Import an existing git project into GitLab?


Just simply run this command in an existing Git repository

cd existing_repo
git remote rename origin previous-hosts
git remote add gitlab [email protected]:hutber/
git push -u gitlab --all
git push -u gitlab --tags

Error: fix the version conflict (google-services plugin)

as the message says go to: versions

And copy the last version's number . Mine was less than 3.3.1. Then in project's build.gradle put/change dependencies node as :

dependencies {
    classpath '' // as it was before             
    classpath '' // <-- the version change                  

Then I synced the project and error went

Bootstrap 4 File Input

I just add this in my CSS file and it works:

.custom-file-label::after{content: 'New Text Button' !important;}

Displaying a 3D model in JavaScript/HTML5

a couple years down the road, I'd vote for three.js because

ie 11 supports webgl (to what extent I can't assure you since i'm usually in chrome)

and, as far as importing external models into three.js, here's a link to mrdoob's updated loaders (so many!)

UPDATE nov 2019: the THREE.js loaders are now far more and it makes little sense to post them all: just go to this link and review the loaders - at least 20 of them

Angular 4 default radio button checked by default

We can use [(ngModel)] in following way and have a value selection variable radioSelected

Example tutorial

Demo Link


  <div class="text-center mt-5">
  <h4>Selected value is {{}}</h4>

    <ul class="list-group">
          <li class="list-group-item"  *ngFor="let item of itemsList">
            <input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/> 





  import {Item} from '../app/item';
  import {ITEMS} from '../app/mock-data';

    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  export class AppComponent {
    title = 'app';
    itemsList: Item[] = ITEMS;

      constructor() {
        this.itemsList = ITEMS;
        //Selecting Default Radio item here
        this.radioSelected = "item_3";

      // Get row item from array  
        this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
        this.radioSelectedString = JSON.stringify(this.radioSel);
      // Radio Change Event


Sample Data for Listing

        export const ITEMS: Item[] = [
                name:'Item 1',
                name:'Item 2',
                name:'Item 3',
                name:'Item 4',
                    name:'Item 5',

Extracting specific columns in numpy array

I assume you wanted columns 1 and 9?

To select multiple columns at once, use

X = data[:, [1, 9]]

To select one at a time, use

x, y = data[:, 1], data[:, 9]

With names:

data[:, ['Column Name1','Column Name2']]

You can get the names from data.dtype.names

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

ConcurrentHashMap is preferred when you can use it - though it requires at least Java 5.

It is designed to scale well when used by multiple threads. Performance may be marginally poorer when only a single thread accesses the Map at a time, but significantly better when multiple threads access the map concurrently.

I found a blog entry that reproduces a table from the excellent book Java Concurrency In Practice, which I thoroughly recommend.

Collections.synchronizedMap makes sense really only if you need to wrap up a map with some other characteristics, perhaps some sort of ordered map, like a TreeMap.

What is the Gradle artifact dependency graph command?

For those looking to debug gradle dependencies in react-native projects, the command is (executed from projectname/android)

./gradlew app:dependencies --configuration compile

Do you have to put Task.Run in a method to make it async?

One of the most important thing to remember when decorating a method with async is that at least there is one await operator inside the method. In your example, I would translate it as shown below using TaskCompletionSource.

private Task<int> DoWorkAsync()
    //create a task completion source
    //the type of the result value must be the same
    //as the type in the returning Task
    TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
    Task.Run(() =>
        int result = 1 + 2;
        //set the result to TaskCompletionSource
    //return the Task
    return tcs.Task;

private async void DoWork()
    int result = await DoWorkAsync();

Modifying the "Path to executable" of a windows service

It involves editing the registry, but service information can be found in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services. Find the service you want to redirect, locate the ImagePath subkey and change that value.

Find in Files: Search all code in Team Foundation Server

There is currently no way to do this out of the box, but there is a User Voice suggestion for adding it:

While I doubt it is as simple as flipping a switch, if everyone that has viewed this question voted for it, MS would probably implement something.

Update: Just read Brian Harry's blog, which shows this request as being on their radar, and the Online version of Visual Studio has limited support for searching where git is used as the vcs: From this I think it's fair to say it is just a matter of time...

Update 2: There is now a Microsoft provided extension,Code Search which enables searching in code as well as in work items.

Set div height equal to screen size

Using CSS {height: 100%;} matches the height of the parent. This could be anything, meaning smaller or bigger than the screen. Using {height: 100vh;} matches the height of the viewport.

.container {
    height: 100vh;
    overflow: auto;

According to Mozilla's official documents, 1vh is:

Equal to 1% of the height of the viewport's initial containing block.

Displaying tooltip on mouse hover of a text

This is not elegant, but you might be able to use the RichTextBox.GetCharIndexFromPosition method to return to you the index of the character that the mouse is currently over, and then use that index to figure out if it's over a link, hotspot, or any other special area. If it is, show your tooltip (and you'd probably want to pass the mouse coordinates into the tooltip's Show method, instead of just passing in the textbox, so that the tooltip can be positioned next to the link).

Example here:

Change size of axes title and labels in ggplot2

To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
g+theme(text = element_text(size=rel(3.5))

You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))

What is the default database path for MongoDB?

I have version 2.0.7 installed on Ubuntu and it defaulted to /var/lib/mongodb/ and that is also what was placed into my /etc/mongodb.conf file.

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

Find a line in a file and remove it

So, whenever I hear someone mention that they want to filter out text, I immediately think to go to Streams (mainly because there is a method called filter which filters exactly as you need it to). Another answer mentions using Streams with the Apache commons-io library, but I thought it would be worthwhile to show how this can be done in standard Java 8. Here is the simplest form:

public void removeLine(String lineContent) throws IOException
    File file = new File("myFile.txt");
    List<String> out = Files.lines(file.toPath())
                        .filter(line -> !line.contains(lineContent))
    Files.write(file.toPath(), out, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

I think there isn't too much to explain there, basically Files.lines gets a Stream<String> of the lines of the file, filter takes out the lines we don't want, then collect puts all of the lines of the new file into a List. We then write the list over top of the existing file with Files.write, using the additional option TRUNCATE so the old contents of the file are replaced.

Of course, this approach has the downside of loading every line into memory as they all get stored into a List before being written back out. If we wanted to simply modify without storing, we would need to use some form of OutputStream to write each new line to a file as it passes through the stream, like this:

public void removeLine(String lineContent) throws IOException
    File file = new File("myFile.txt");
    File temp = new File("_temp_");
    PrintWriter out = new PrintWriter(new FileWriter(temp));
        .filter(line -> !line.contains(lineContent))

Not much has been changed in this example. Basically, instead of using collect to gather the file contents into memory, we use forEach so that each line that makes it through the filter gets sent to the PrintWriter to be written out to the file immediately and not stored. We have to save it to a temporary file, because we can't overwrite the existing file at the same time as we are still reading from it, so then at the end, we rename the temp file to replace the existing file.

Getting the parameters of a running JVM

I am adding this new answer because as per JDK8 documentation jcmd is suggested approach now.

It is suggested to use the latest utility, jcmd instead of the previous jstack, jinfo, and jmap utilities for enhanced diagnostics and reduced performance overhead.

Below are commands to get your properties/flags you want.

jcmd pid VM.system_properties
jcmd pid VM.flags

We need pid, for this use jcmd -l, like below

username@users-Air:~/javacode$ jcmd -l 
11441 Test 
6294 Test 
29197 jdk.jcmd/ -l 

Now time to use these pids to get properties/flags you want

Command: jcmd 11441 VM.system_properties

#Tue Oct 17 12:44:50 IST 2017
java.vm.vendor=Oracle Corporation
java.vm.specification.version=9 OS X
java.specification.vendor=Oracle Corporation
java.vm.compressedOopsMode=Zero based
line.separator=\n Platform API Specification
java.vm.specification.vendor=Oracle Corporation
java.awt.graphicsenv=sun.awt.CGraphicsEnvironment 64-Bit Tiered Compilers
os.version=10.12.6 SE Runtime Environment
file.encoding=UTF-8 HotSpot(TM) 64-Bit Server VM
os.arch=x86_64 Virtual Machine Specification
java.library.path=/Users/XXXX/Library/Java/Extensions\:/Library/Java/Extensions\:/Network/Library/Java/Extensions\:/System/Library/Java/Extensions\:/usr/lib/java\:. mode
java.vendor=Oracle Corporation

Command : jcmd 11441 VM.flags output:

-XX:CICompilerCount=3 -XX:ConcGCThreads=1 -XX:G1ConcRefinementThreads=4 -XX:G1HeapRegionSize=1048576 -XX:InitialHeapSize=67108864 -XX:MarkStackSize=4194304 -XX:MaxHeapSize=1073741824 -XX:MaxNewSize=643825664 -XX:MinHeapDeltaBytes=1048576 -XX:NonNMethodCodeHeapSize=5830092 -XX:NonProfiledCodeHeapSize=122914074 -XX:ProfiledCodeHeapSize=122914074 -XX:ReservedCodeCacheSize=251658240 -XX:+SegmentedCodeCache -XX:-UseAOT -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:+UseG1GC 

For more instructions of usages of jcmd, see my blog post

How can you make a custom keyboard in Android?

First of all you will need a keyboard.xml file which will be placed in the res/xml folder (if the folder does not exist, created it).

<?xml version="1.0" encoding="utf-8"?> 
<Keyboard xmlns:android=""
    android:keyHeight="15%p" >

        <Key android:codes="1"    android:keyLabel="1" android:horizontalGap="4%p"/>
        <Key android:codes="2"    android:keyLabel="2" android:horizontalGap="4%p"/>
        <Key android:codes="3"    android:keyLabel="3" android:horizontalGap="4%p" />
        <Key android:codes="4"    android:keyLabel="4" android:horizontalGap="4%p" />
        <Key android:codes="5"    android:keyLabel="5" android:horizontalGap="4%p" />
        <Key android:codes="6"    android:keyLabel="6" android:horizontalGap="4%p"/>
        <Key android:codes="7"    android:keyLabel="7" android:horizontalGap="4%p"/>
        <Key android:codes="8"    android:keyLabel="8" android:horizontalGap="4%p" />
        <Key android:codes="9"    android:keyLabel="9" android:horizontalGap="4%p" />
        <Key android:codes="0"    android:keyLabel="0" android:horizontalGap="4%p" />

        <Key android:codes="-1"    android:keyIcon="@drawable/backspace" android:keyWidth="34%p" android:horizontalGap="4%p"/>
        <Key android:codes="100"    android:keyLabel="Enter" android:keyWidth="53%p" android:horizontalGap="4%p"/>

**Note that you will have to create the backspace drawable and place it in the res/drawable-ldpi folder with a very small size (like 18x18 pixels)

Then in the xml file that you want it to be used (where your TextView is in) you should add the following code:





**Note that the xml file that you will place the android.inputmethodservice.KeyboardView in, has to be RelativeLayout in order to be able to set the alignParentBottom="true" (Usually the keyboards are presented in the bottom of the screen)

Then you need to add the following code in the onCreate function of the Activity that handles the TextView you want to attach the keyboard to

    // Create the Keyboard
    mKeyboard= new Keyboard(this,R.xml.keyboard);

    // Lookup the KeyboardView
    mKeyboardView= (KeyboardView)findViewById(;
    // Attach the keyboard to the view
    mKeyboardView.setKeyboard( mKeyboard );
    // Do not show the preview balloons
    // Install the key handler

**Note that mKeyboard and mKeyboardView are private class variables that you have to create.

Then you need the following function for opening the keyboard ( you must associate it with the TextView through the onClick xml property)

    public void openKeyboard(View v)
       if( v!=null)((InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);

And finally you need the OnKeyboardActionListener that will handle your events

private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {
    @Override public void onKey(int primaryCode, int[] keyCodes) 
         //Here check the primaryCode to see which key is pressed 
         //based on the android:codes property
            Log.i("Key","You just pressed 1 button");

    @Override public void onPress(int arg0) {

    @Override public void onRelease(int primaryCode) {

    @Override public void onText(CharSequence text) {

    @Override public void swipeDown() {

    @Override public void swipeLeft() {

    @Override public void swipeRight() {

    @Override public void swipeUp() {

Hope that helps!!!

Most of the code found here



Since KeyboardView is depreciated since API level 29, you can find its code in this website and create a class in your code before implementing the keyboard as described above.

Protect image download

There is no way to protect image downloading. This is because the image has to be downloaded by the browser for it to be seen by the user. There are tricks (like the transparent background you specified) to restrict certain operations like image right click and saving to browser cache folder, but there isn't a way for truly protecting the images.

Executing multiple commands from a Windows cmd script

Note that you don't need semicolons in batch files. And the reason why you need to use call is that mvn itself is a batch file and batch files need to call each other with call, otherwise control does not return to the caller.

json_encode(): Invalid UTF-8 sequence in argument

Using this code might help. It solved my problem!


or like that


Get current directory name (without full path) in a Bash script

I strongly prefer using gbasename, which is part of GNU coreutils.

Support for "border-radius" in IE

Yes! When IE9 is released in Jan 2011.

Let's say you want an even 15px on all four sides:

.myclass {
 border-style: solid;
 border-width: 2px;
 -moz-border-radius: 15px;
 -webkit-border-radius: 15px;
 border-radius: 15px;

IE9 will use the default border-radius, so just make sure you include that in all your styles calling a border radius. Then your site will be ready for IE9.

-moz-border-radius is for Firefox, -webkit-border-radius is for Safari and Chrome.

Furthermore: don't forget to declare your IE coding is ie9:

<meta http-equiv="X-UA-Compatible" content="IE=9" />

Some lazy developers have <meta http-equiv="X-UA-Compatible" content="IE=7" />. If that tag exists, border-radius will never work in IE.

python dataframe pandas drop column using int

You can simply supply columns parameter to df.drop command so you don't to specify axis in that case, like so

columns_list = [1, 2, 4] # index numbers of columns you want to delete
df = df.drop(columns=df.columns[columns_list])

For reference see columns parameter here:

PHP Call to undefined function

Your function is probably in a different namespace than the one you're calling it from.

The process cannot access the file because it is being used by another process (File is created but contains nothing)

Try This

string path = @"c:\mytext.txt";

if (File.Exists(path))

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
    string addtext = "this line is added" + Environment.NewLine;
    // Close the Stream then Individually you can access the file.

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3


In every File Operation, The File will be Opened and must be Closed prior Opened. Like wise in the Operation 1 you must Close the File Stream for the Further Operations.

Undefined symbols for architecture i386

At the risk of sounding obvious, always check the spelling of your forward class files. Sometimes XCode (at least XCode 4.3.2) will turn a declaration green that's actually camel cased incorrectly. Like in this example:

"_OBJC_CLASS_$_RadioKit", referenced from:
  objc-class-ref in RadioPlayerViewController.o

If RadioKit was a class file and you make it a property of another file, in the interface declaration, you might see that

Radiokit *rk;

has "Radiokit" in green when the actual decalaration should be:

RadioKit *rk;

This error will also throw this type of error. Another example (in my case), is when you have _iPhone and _iphone extensions on your class names for universal apps. Once I changed the appropriate file from _iphone to the correct _iPhone, the errors went away.

Should I use int or Int32

Use of Int or Int32 are the same Int is just sugar to simplify the code for the reader.

Use the Nullable variant Int? or Int32? when you work with databases on fields containing null. That will save you from a lot of runtime issues.

Exception thrown inside catch block - will it be caught again?

Old post but "e" variable must be unique:

try {
  // Do something
} catch(IOException ioE) {
  throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
  // Will the ApplicationException be caught here?

What does the star operator mean, in a function call?

I find this particularly useful for when you want to 'store' a function call.

For example, suppose I have some unit tests for a function 'add':

def add(a, b): return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
    print 'test: adding', test, '==', result, '---', add(*test) == result

There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.

Another place this is useful is for defining Factory objects (objects that create objects for you). Suppose you have some class Factory, that makes Car objects and returns them. You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.

def make_car(*args):
    return Car(*args)

This is also useful when you want to call a superclass' constructor.

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

I had a similar exception (but different problem) - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document , and fortunately it's solved easier:

Instead of

List<Document> docs = obj.get("documents");
Document doc = docs.get(0)

which gives error on second line, One can use

List<Document> docs = obj.get("documents");
Document doc = new Document(docs.get(0));

HTML embedded PDF iframe

It's downloaded probably because there is not Adobe Reader plug-in installed. In this case, IE (it doesn't matter which version) doesn't know how to render it, and it'll simply download the file (Chrome, for example, has its own embedded PDF renderer).

That said. <iframe> is not best way to display a PDF (do not forget compatibility with mobile browsers, for example Safari). Some browsers will always open that file inside an external application (or in another browser window). Best and most compatible way I found is a little bit tricky but works on all browsers I tried (even pretty outdated):

Keep your <iframe> but do not display a PDF inside it, it'll be filled with an HTML page that consists of an <object> tag. Create an HTML wrapping page for your PDF, it should look like this:

    <object data="your_url_to_pdf" type="application/pdf">
        <embed src="your_url_to_pdf" type="application/pdf" />

Of course, you still need the appropriate plug-in installed in the browser. Also, look at this post if you need to support Safari on mobile devices.

1st. Why nesting <embed> inside <object>? You'll find the answer here on SO. Instead of a nested <embed> tag, you may (should!) provide a custom message for your users (or a built-in viewer, see next paragraph). Nowadays, <object> can be used without worries, and <embed> is useless.

2nd. Why an HTML page? So you can provide a fallback if PDF viewer isn't supported. Internal viewer, plain HTML error messages/options, and so on...

It's tricky to check PDF support so that you may provide an alternate viewer for your customers, take a look at PDF.JS project; it's pretty good but rendering quality - for desktop browsers - isn't as good as a native PDF renderer (I didn't see any difference in mobile browsers because of screen size, I suppose).

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

Second Update

The FAQ is not available anymore.

From the documentation of shrinkwrap:

If you wish to lock down the specific bytes included in a package, for example to have 100% confidence in being able to reproduce a deployment or build, then you ought to check your dependencies into source control, or pursue some other mechanism that can verify contents rather than versions.

Shannon and Steven mentioned this before but I think, it should be part of the accepted answer.


The source listed for the below recommendation has been updated. They are no longer recommending the node_modules folder be committed.

Usually, no. Allow npm to resolve dependencies for your packages.

For packages you deploy, such as websites and apps, you should use npm shrinkwrap to lock down your full dependency tree:

Original Post

For reference, npm FAQ answers your question clearly:

Check node_modules into git for things you deploy, such as websites and apps. Do not check node_modules into git for libraries and modules intended to be reused. Use npm to manage dependencies in your dev environment, but not in your deployment scripts.

and for some good rationale for this, read Mikeal Rogers' post on this.


Primary key or Unique index?

I almost never create a table without a numeric primary key. If there is also a natural key that should be unique, I also put a unique index on it. Joins are faster on integers than multicolumn natural keys, data only needs to change in one place (natural keys tend to need to be updated which is a bad thing when it is in primary key - foreign key relationships). If you are going to need replication use a GUID instead of an integer, but for the most part I prefer a key that is user readable especially if they need to see it to distinguish between John Smith and John Smith.

The few times I don't create a surrogate key are when I have a joining table that is involved in a many-to-many relationship. In this case I declare both fields as the primary key.

Expand/collapse section in UITableView in iOS

I've used a NSDictionary as datasource, this looks like a lot of code, but it's really simple and works very well! how looks here

I created a enum for the sections

typedef NS_ENUM(NSUInteger, TableViewSection) {

    TableViewSection0 = 0,

sections property:

@property (nonatomic, strong) NSMutableDictionary * sectionsDisctionary;

A method returning my sections:

-(NSArray <NSNumber *> * )sections{

    return @[@(TableViewSection0), @(TableViewSection1), @(TableViewSection2)];

And then setup my data soruce:


    self.sectionsDisctionary = [NSMutableDictionary dictionary];

    NSArray * sections = [self sections];

    for (NSNumber * section in sections) {

    NSArray * sectionObjects = [self objectsForSection:section.integerValue];

    [self.sectionsDisctionary setObject:[NSMutableDictionary dictionaryWithDictionary:@{@"visible" : @YES, @"objects" : sectionObjects}] forKey:section];

-(NSArray *)objectsForSection:(NSInteger)section{

    NSArray * objects;

    switch (section) {

        case TableViewSection0:

            objects = @[] // objects for section 0;

        case TableViewSection1:

            objects = @[] // objects for section 1;

        case TableViewSection2:

            objects = @[] // objects for section 2;


    return objects;

The next methods, will help you to know when a section is opened, and how to respond to tableview datasource:

Respond the section to datasource:

 *  Asks the delegate for a view object to display in the header of the specified section of the table view.
 *  @param tableView The table-view object asking for the view object.
 *  @param section   An index number identifying a section of tableView .
 *  @return A view object to be displayed in the header of section .
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    NSString * headerName = [self titleForSection:section];

    YourCustomSectionHeaderClass * header = (YourCustomSectionHeaderClass *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:YourCustomSectionHeaderClassIdentifier];

    [header setTag:section];
    [header addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]];
    header.title = headerName;
    header.collapsed = [self sectionIsOpened:section];

    return header;

 * Asks the data source to return the number of sections in the table view
 * @param An object representing the table view requesting this information.
 * @return The number of sections in tableView.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    // Return the number of sections.

    return self.sectionsDisctionary.count;

 * Tells the data source to return the number of rows in a given section of a table view
 * @param tableView: The table-view object requesting this information.
 * @param section: An index number identifying a section in tableView.
 * @return The number of rows in section.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    BOOL sectionOpened = [self sectionIsOpened:section];
    return sectionOpened ? [[self objectsForSection:section] count] : 0;


 Return the section at the given index

 @param index the index

 @return The section in the given index
-(NSMutableDictionary *)sectionAtIndex:(NSInteger)index{

    NSString * asectionKey = [self.sectionsDisctionary.allKeys objectAtIndex:index];

    return [self.sectionsDisctionary objectForKey:asectionKey];

 Check if a section is currently opened

 @param section the section to check

 @return YES if is opened

    NSDictionary * asection = [self sectionAtIndex:section];
    BOOL sectionOpened = [[asection objectForKey:@"visible"] boolValue];

    return sectionOpened;

 Handle the section tap

 @param tap the UITapGestureRecognizer
- (void)handleTapGesture:(UITapGestureRecognizer*)tap{

    NSInteger index = tap.view.tag;

    [self toggleSection:index];

Toggle section visibility

 Switch the state of the section at the given section number

 @param section the section number

    if (index >= 0){

        NSMutableDictionary * asection = [self sectionAtIndex:section];

        [asection setObject:@(![self sectionIsOpened:section]) forKey:@"visible"];

        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?


SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

Pesonally tested on 10g ;-)


Accessing an SQLite Database in Swift

Configure your Swift project to handle SQLite C calls:

Create bridging header file to the project. See the Importing Objective-C into Swift section of the Using Swift with Cocoa and Objective-C. This bridging header should import sqlite3.h:

Add the libsqlite3.0.dylib to your project. See Apple's documentation regarding adding library/framework to one's project.

and used following code

    func executeQuery(query: NSString ) -> Int
        if  sqlite3_open(databasePath! as String, &database) != SQLITE_OK
            println("Databse is not open")
            return 0
            query.stringByReplacingOccurrencesOfString("null", withString: "")
            var cStatement:COpaquePointer = nil
            var executeSql = query as NSString
            var lastId : Int?
            var sqlStatement = executeSql.cStringUsingEncoding(NSUTF8StringEncoding)
            sqlite3_prepare_v2(database, sqlStatement, -1, &cStatement, nil)
            var execute = sqlite3_step(cStatement)
            if execute == SQLITE_DONE
                lastId = Int(sqlite3_last_insert_rowid(database))
                println("Error in Run Statement :- \(sqlite3_errmsg16(database))")
            return lastId!
    func ViewAllData(query: NSString, error: NSError) -> NSArray
        var cStatement = COpaquePointer()
        var result : AnyObject = NSNull()
        var thisArray : NSMutableArray = NSMutableArray(capacity: 4)
        cStatement = prepare(query)
        if cStatement != nil
            while sqlite3_step(cStatement) == SQLITE_ROW
                result = NSNull()
                var thisDict : NSMutableDictionary = NSMutableDictionary(capacity: 4)
                for var i = 0 ; i < Int(sqlite3_column_count(cStatement)) ; i++
                    if sqlite3_column_type(cStatement, Int32(i)) == 0
                    if sqlite3_column_decltype(cStatement, Int32(i)) != nil && strcasecmp(sqlite3_column_decltype(cStatement, Int32(i)), "Boolean") == 0
                        var temp = sqlite3_column_int(cStatement, Int32(i))
                        if temp == 0
                            result = NSNumber(bool : false)
                            result = NSNumber(bool : true)
                    else if sqlite3_column_type(cStatement,Int32(i)) == SQLITE_INTEGER
                        var temp = sqlite3_column_int(cStatement,Int32(i))
                        result = NSNumber(int : temp)
                    else if sqlite3_column_type(cStatement,Int32(i)) == SQLITE_FLOAT
                        var temp = sqlite3_column_double(cStatement,Int32(i))
                        result = NSNumber(double: temp)
                        if sqlite3_column_text(cStatement, Int32(i)) != nil
                            var temp = sqlite3_column_text(cStatement,Int32(i))
                            result = String.fromCString(UnsafePointer<CChar>(temp))!
                            var keyString = sqlite3_column_name(cStatement,Int32(i))
                            thisDict.setObject(result, forKey: String.fromCString(UnsafePointer<CChar>(keyString))!)
                        result = NSNull()

                    if result as! NSObject != NSNull()
                        var keyString = sqlite3_column_name(cStatement,Int32(i))
                        thisDict.setObject(result, forKey: String.fromCString(UnsafePointer<CChar>(keyString))!)
                thisArray.addObject(NSMutableDictionary(dictionary: thisDict))
        return thisArray
    func prepare(sql : NSString) -> COpaquePointer
        var cStatement:COpaquePointer = nil
        sqlite3_open(databasePath! as String, &database)
        var utfSql = sql.UTF8String
        if sqlite3_prepare(database, utfSql, -1, &cStatement, nil) == 0
            return cStatement
            return nil

substring index range

Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end.

To make life easier for substring operation, imagine that characters are between indexes.

0 1 2 3 4 5 6 7 8 9 10  <- available indexes for substring 
 u n i v E R S i t y
        ?     ?
      start  end --> range of "E R S"

Quoting the docs:

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Where can I find Android's default icons?

You can find the default Android menu icons here - link is broken now.

Update: You can find Material Design icons here.

CSS3 Box Shadow on Top, Left, and Right Only

Adding a separate answer because it is radically different.

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

Try something like this (play with the .5)

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

Hope this helps!

C#: Waiting for all threads to complete

This doesn't answer the question (no timeout), but I've made a very simple extension method to wait all threads of a collection:

using System.Collections.Generic;
using System.Threading;
namespace Extensions
    public static class ThreadExtension
        public static void WaitAll(this IEnumerable<Thread> threads)
                foreach(Thread thread in threads)
                { thread.Join(); }

Then you simply call:

List<Thread> threads=new List<Thread>();
//Add your threads to this collection