Programs & Examples On #Transoft

Reset/remove CSS styles for element only

If anyone is coming here looking for an answer that utilizes iframe here it is

<iframe srcdoc="<html><body>your-html-here</body></html>" />

Variables as commands in bash scripts

Quoting spaces inside variables such that the shell will re-interpret things properly is hard. It's this type of thing that prompts me to reach for a stronger language. Whether that's perl or python or ruby or whatever (I choose perl, but that's not always for everyone), it's just something that will allow you to bypass the shell for quoting.

It's not that I've never managed to get it right with liberal doses of eval, but just that eval gives me the eebie-jeebies (becomes a whole new headache when you want to take user input and eval it, though in this case you'd be taking stuff that you wrote and evaling that instead), and that I've gotten headaches in debugging.

With perl, as my example, I'd be able to do something like:

@tar_cmd = ( qw(tar cv), $directory );
@encrypt_cmd = ( qw(openssl des3 -salt) );
@split_cmd = ( qw(split -b 1024m -), $backup_file );

The hard part here is doing the pipes - but a bit of IO::Pipe, fork, and reopening stdout and stderr, and it's not bad. Some would say that's worse than quoting the shell properly, and I understand where they're coming from, but, for me, this is easier to read, maintain, and write. Heck, someone could take the hard work out of this and create a IO::Pipeline module and make the whole thing trivial ;-)

Git diff says subproject is dirty

Do you have adequate permissions to your repo'?

My solution was unrelated to git, however I was seeing the same error messages, and dirty status of submodules.

The root-cause was some files in the .git folder were owned by root, so git did not have write access, therefore git could not change the dirty state of submodules when run as my user.

Do you have the same problem?

From your repository's root folder, use find to list files owned by root [optional]

find .git -user root

Sollution [Linux]

Change all files in the .git folder to have you as the owner

sudo chown -R $USER:$USER .git

# alternatively, only the files listed in the above command...
sudo find .git -user root -exec chown $USER:$USER {} +

How did this happen?

In my case I built libraries in sub-modules from a docker container, the docker daemon traditionally runs as root, so files created fall into root:root ownership. My user has root privileges by proxy through that service, so even though I didn't sudo anything, my git repository still had changes owned by root.

I hope this helps someone, git outa here.

C programming: Dereferencing pointer to incomplete type error

The reason why you're getting that error is because you've declared your struct as:

struct {
 char name[32];
 int  size;
 int  start;
 int  popularity;
} stasher_file;

This is not declaring a stasher_file type. This is declaring an anonymous struct type and is creating a global instance named stasher_file.

What you intended was:

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;

But note that while Brian R. Bondy's response wasn't correct about your error message, he's right that you're trying to write into the struct without having allocated space for it. If you want an array of pointers to struct stasher_file structures, you'll need to call malloc to allocate space for each one:

struct stasher_file *newFile = malloc(sizeof *newFile);
if (newFile == NULL) {
   /* Failure handling goes here. */
strncpy(newFile->name, name, 32);
newFile->size = size;

(BTW, be careful when using strncpy; it's not guaranteed to NUL-terminate.)

Beautiful Soup and extracting a div and its contents by ID

The Id property is always uniquely identified. That means you can use it directly without even specifying the element. Therefore, it is a plus point if your elements have it to parse through the content.

divEle = soup.find(id = "articlebody")

Swift: print() vs println() vs NSLog()

If you're using Swift 2, now you can only use print() to write something to the output.

Apple has combined both println() and print() functions into one.

Updated to iOS 9

By default, the function terminates the line it prints by adding a line break.

print("Hello Swift")


To print a value without a line break after it, pass an empty string as the terminator

print("Hello Swift", terminator: "")


You now can use separator to concatenate multiple items

print("Hello", "Swift", 2, separator:" ")


Or you could combine using in this way

print("Hello", "Swift", 2, separator:" ", terminator:".")

Does Django scale?

I was at the EuroDjangoCon conference the other week, and this was the subject of a couple of talks - including from the founders of what was the largest Django-based site, Pownce (slides from one talk here). The main message is that it's not Django you have to worry about, but things like proper caching, load balancing, database optimisation, etc.

Django actually has hooks for most of those things - caching, in particular, is made very easy.

FileNotFoundError: [Errno 2] No such file or directory

When you open a file with the name address.csv, you are telling the open() function that your file is in the current working directory. This is called a relative path.

To give you an idea of what that means, add this to your code:

import os

cwd = os.getcwd()  # Get the current working directory (cwd)
files = os.listdir(cwd)  # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))

That will print the current working directory along with all the files in it.

Another way to tell the open() function where your file is located is by using an absolute path, e.g.:

f = open("/Users/foo/address.csv")

Why should I prefer to use member initialization lists?

Next to the performance issues, there is another one very important which I'd call code maintainability and extendibility.

If a T is POD and you start preferring initialization list, then if one time T will change to a non-POD type, you won't need to change anything around initialization to avoid unnecessary constructor calls because it is already optimised.

If type T does have default constructor and one or more user-defined constructors and one time you decide to remove or hide the default one, then if initialization list was used, you don't need to update code if your user-defined constructors because they are already correctly implemented.

Same with const members or reference members, let's say initially T is defined as follows:

struct T
    T() { a = 5; }
    int a;

Next, you decide to qualify a as const, if you would use initialization list from the beginning, then this was a single line change, but having the T defined as above, it also requires to dig the constructor definition to remove assignment:

struct T
    T() : a(5) {} // 2. that requires changes here too
    const int a; // 1. one line change

It's not a secret that maintenance is far easier and less error-prone if code was written not by a "code monkey" but by an engineer who makes decisions based on deeper consideration about what he is doing.

How to automatically generate N "distinct" colors?

Here's an idea. Imagine an HSV cylinder

Define the upper and lower limits you want for the Brightness and Saturation. This defines a square cross section ring within the space.

Now, scatter N points randomly within this space.

Then apply an iterative repulsion algorithm on them, either for a fixed number of iterations, or until the points stabilise.

Now you should have N points representing N colours that are about as different as possible within the colour space you're interested in.


Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

Go to Project Properties and under Build Make sure that the "Optimize Code" checkbox is unchecked.

Also, set the "Debug Info" dropdown to "Full" in the Advanced Options (Under Build tab).

Implement touch using Python?

def touch(fname):
    if os.path.exists(fname):
        os.utime(fname, None)
        open(fname, 'a').close()

ASP.NET 4.5 has not been registered on the Web server

If you've installed .NET framework 4.6, you may see this error due to a VS bug. Workarounds and resolutions here:


As noted in some of the comments, this can happen behind the scenes after upgrading to Windows 10 or Visual Studio 2015.

Accessing SQL Database in Excel-VBA

Add set nocount on to the beginning of the stored proc (if you're on SQL Server). I just solved this problem in my own work and it was caused by intermediate results, such as "1203 Rows Affected", being loaded into the Recordset I was trying to use.

How to change the text on the action bar

Update: Latest ActionBar (Title) pattern:

FYI, ActionBar was introduced in API Level 11. ActionBar is a window feature at the top of the Activity that may display the activity title, navigation modes, and other interactive items like search.

I exactly remember about customizing title bar and making it consistent through the application. So I can make a comparison with the earlier days and can list some of the advantages of using ActionBar:

  1. It offers your users a familiar interface across applications that the system gracefully adapts for different screen configurations.
  2. Developers don't need to write much code for displaying the Activity Title, icons and navigation modes because ActionBar is already ready with top level abstraction.

For example:

enter image description here

enter image description here

=> Normal way,

getActionBar().setTitle("Hello world App");   
getSupportActionBar().setTitle("Hello world App");  // provide compatibility to all the versions

=> Customizing Action Bar,

For example:

public void setActionBar(String heading) {
    // TODO Auto-generated method stub actionBar = getSupportActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.title_bar_gray)));


Styling the Action Bar:

The ActionBar provides you with basic and familiar looks, navigation modes and other quick actions to perform. But that doesn't mean it looks the same in every app. You can customize it as per your UI and design requirements. You just have to define and write styles and themes.

Read more at: Styling the Action Bar

And if you want to generate styles for ActionBar then this Style Generator tool can help you out.


Old: Earlier days:

=> Normal way,

you can Change the Title of each screen (i.e. Activity) by setting their Android:label

   <activity android:name=".Hello_World"
                  android:label="This is the Hello World Application">

=> Custom - Title - bar

But if you want to Customize title-bar in your own way, i.e. Want to put Image icon and custom-text, then the following code works for me:


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


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

<ImageView android:id="@+id/ImageView01" 


  android:text="This is my new title" 

public class TitleBar extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        final boolean customTitleSupported = 
        if (customTitleSupported) {
        final TextView myTitleText = (TextView) findViewById(;
        if (myTitleText != null) {
            myTitleText.setText("NEW TITLE");
            // user can also set color using "Color" and then
            // "Color value constant"
            // myTitleText.setBackgroundColor(Color.GREEN);


The strings.xml file is defined under the values folder.

<?xml version="1.0" encoding="utf-8"?>
    <string name="hello">Hello World, Set_Text_TitleBar!</string>
    <string name="app_name">Set_Text_TitleBar</string>
    <color name="titlebackgroundcolor">#3232CD</color>
    <color name="titletextcolor">#FFFF00</color>

AngularJS sorting rows by table header

I think this working CodePen example that I created will show you exactly how to do what you want.

The template:

<section ng-app="app" ng-controller="MainCtrl">
  <span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
  <table class="table table-bordered">
          <a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
          First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          <a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
            Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          <a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
          Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
      <tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">

The JavaScript code:

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

app.controller('MainCtrl', function($scope) {
  $scope.orderByField = 'firstName';
  $scope.reverseSort = false;

  $ = {
    employees: [{
      firstName: 'John',
      lastName: 'Doe',
      age: 30
      firstName: 'Frank',
      lastName: 'Burns',
      age: 54
      firstName: 'Sue',
      lastName: 'Banter',
      age: 21

shell init issue when click tab, what's wrong with getcwd?

Yes, cd; and cd - would work. The reason It can see is that, directory is being deleted from any other terminal or any other program and recreate it. So i-node entry is modified so program can not access old i-node entry.

How can I view the Git history in Visual Studio Code?

It is evident to me that GitLens is the most popular extension for Git history.

enter image description here

What I like the most it can provide you side annotations when some line has been changed the last time and by whom.

Enter image description here

Coerce multiple columns to factors at once

If you have another objective of getting in values from the table then using them to be converted, you can try the following way

### pre processing
ind <- bigm.train[,lapply(.SD,is.character)]
ind <- names(ind[,.SD[T]])
### Convert multiple columns to factor

This selects columns which are specifically character based and then converts them to factor.

CSS background image alt attribute

The classical way to achieve this is to put the text into the div and use an image replacement technique.

<div class"ir background-image">Your alt text</div>

with background-image beeing the class where you assign the background image and ir could be HTML5boilerplates image replacement class, below:

/* ==========================================================================
   Helper classes
   ========================================================================== */

 * Image replacement

.ir {
    background-color: transparent;
    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;

.ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;

Escape Character in SQL Server

You need to just replace ' with '' inside your string

SELECT colA, colB, colC
FROM tableD
WHERE colA = 'John''s Mobile'

You can also use REPLACE(@name, '''', '''''') if generating the SQL dynamically

If you want to escape inside a like statement then you need to use the ESCAPE syntax

It's also worth mentioning that you're leaving yourself open to SQL injection attacks if you don't consider it. More info at Google or:

Create an array with random values

Math.random() will return a number between 0 and 1(exclusive). So, if you want 0-40, you can multiple it by 40, the highest the result can ever be is what you're multiplying by.

var arr = [];
for (var i=0, t=40; i<t; i++) {
    arr.push(Math.round(Math.random() * t))

Is there any sed like utility for cmd.exe?

There is a helper batch file for Windows called repl.bat which has much of the ability of SED but doesn't require any additional download or installation. It is a hybrid batch file that uses Jscript to implement the features and so is swift, and doesn't suffer from the usual poison characters of batch processing and handles blank lines with ease.

Download repl from -

The author is @dbenham from stack overflow and

Another helper batch file called findrepl.bat gives the Windows user much of the capabilty of GREP and is also based on Jscript and is likewise a hybrid batch file. It shares the benefits of repl.bat

Download findrepl from -

The author is @aacini from stack overflow and

How do I check for null values in JavaScript?

Firstly, you have a return statement without a function body. Chances are that that will throw an error.

A cleaner way to do your check would be to simply use the ! operator:

if (!pass || !cpass || !email || !cemail || !user) {

    alert("fill all columns");


How to set up Spark on Windows?

Trying to work with spark-2.x.x, building Spark source code didn't work for me.

  1. So, although I'm not going to use Hadoop, I downloaded the pre-built Spark with hadoop embeded : spark-2.0.0-bin-hadoop2.7.tar.gz

  2. Point SPARK_HOME on the extracted directory, then add to PATH: ;%SPARK_HOME%\bin;

  3. Download the executable winutils from the Hortonworks repository, or from Amazon AWS platform winutils.

  4. Create a directory where you place the executable winutils.exe. For example, C:\SparkDev\x64. Add the environment variable %HADOOP_HOME% which points to this directory, then add %HADOOP_HOME%\bin to PATH.

  5. Using command line, create the directory:

    mkdir C:\tmp\hive
  6. Using the executable that you downloaded, add full permissions to the file directory you created but using the unixian formalism:

    %HADOOP_HOME%\bin\winutils.exe chmod 777 /tmp/hive
  7. Type the following command line:


Scala command line input should be shown automatically.

Remark : You don't need to configure Scala separately. It's built-in too.

Check if all elements in a list are identical

Or use diff method of numpy:

import numpy as np
def allthesame(l):
    return np.unique(l).shape[0]<=1

And to call:




matplotlib: Group boxplots

Grouped boxplots, towards subtle academic publication styling... (source)

(Left) Python 2.7.12 Matplotlib v1.5.3. (Right) Python 3.7.3. Matplotlib v3.1.0.

grouped boxplot example png for Python 2.7.12 Matplotlib v1.5.3 grouped boxplot example png for Python 3.7.3 Matplotlib v3.1.0


import numpy as np
import matplotlib.pyplot as plt

# --- Your data, e.g. results per algorithm:
data1 = [5,5,4,3,3,5]
data2 = [6,6,4,6,8,5]
data3 = [7,8,4,5,8,2]
data4 = [6,9,3,6,8,4]

# --- Combining your data:
data_group1 = [data1, data2]
data_group2 = [data3, data4]

# --- Labels for your data:
labels_list = ['a','b']
xlocations  = range(len(data_group1))
width       = 0.3
symbol      = 'r+'
ymin        = 0
ymax        = 10

ax = plt.gca()
ax.set_xticklabels( labels_list, rotation=0 )
ax.grid(True, linestyle='dotted')
plt.xlabel('X axis label')
plt.ylabel('Y axis label')

# --- Offset the positions per group:
positions_group1 = [x-(width+0.01) for x in xlocations]
positions_group2 = xlocations

#           notch=False,  
#           vert=True, 
#           whis=1.5,
#           bootstrap=None, 
#           usermedians=None, 
#           conf_intervals=None,
#           patch_artist=False,

#           notch=False,  
#           vert=True, 
#           whis=1.5,
#           bootstrap=None, 
#           usermedians=None, 
#           conf_intervals=None,
#           patch_artist=False,

plt.savefig('boxplot_grouped.pdf')    # when publishing, use high quality PDFs                   # uncomment to show the plot. 

How to set IntelliJ IDEA Project SDK

For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

What does ||= (or-equals) mean in Ruby?

As a common misconception, a ||= b is not equivalent to a = a || b, but it behaves like a || a = b.

But here comes a tricky case. If a is not defined, a || a = 42 raises NameError, while a ||= 42 returns 42. So, they don't seem to be equivalent expressions.

How to use clock() in C++

On Windows at least, the only practically accurate measurement mechanism is QueryPerformanceCounter (QPC). std::chrono is implemented using it (since VS2015, if you use that), but it is not accurate to the same degree as using QueryPerformanceCounter directly. In particular it's claim to report at 1 nanosecond granularity is absolutely not correct. So, if you're measuring something that takes a very short amount of time (and your case might just be such a case), then you should use QPC, or the equivalent for your OS. I came up against this when measuring cache latencies, and I jotted down some notes that you might find useful, here;

C++: constructor initializer for arrays

This is my solution for your reference:

struct Foo
    Foo(){}//used to make compiler happy!
    Foo(int x){/*...*/}

struct Bar
    Foo foo[3];

        //initialize foo array here:
        for(int i=0;i<3;++i)

Add a dependency in Maven

I'd do this:

  1. add the dependency as you like in your pom:


  2. run mvn install it will try to download the jar and fail. On the process, it will give you the complete command of installing the jar with the error message. Copy that command and run it! easy huh?!

Get selected key/value of a combo box using jQuery

$(this).find("select").each(function () {

Datatable date sorting dd/mm/yyyy issue

I too got same problem.

I was using span with in td like 03/21/2017, by doing this, datatable treated this as string and sorting did not work.

I removed span inside td, and it got fixed. like, 03/21/2017

Is there a need for range(len(a))?

My code is:

for I in range(len(s)):
    while not set(s[I])<=set('01'):s[i]=input(i)
print(bin(sum([int(x,2)for x in s]))[2:])

It is a binary adder but I don't think the range len or the inside can be replaced to make it smaller/better.

How to remove a newline from a string in Bash

Under , there are some bashisms:

The tr command could be replaced by // bashism:

COMMAND=$'\nREBOOT\r   \n'
echo "|${COMMAND}|"

echo "|${COMMAND//[$'\t\r\n']}|"

echo "|${COMMAND//[$'\t\r\n ']}|"

See Parameter Expansion and QUOTING in bash's man page:

man -Pless\ +/\/pattern bash
man -Pless\ +/\\\'string\\\' bash

man -Pless\ +/^\\\ *Parameter\\\ Exp bash
man -Pless\ +/^\\\ *QUOTING bash


As asked by @AlexJordan, this will suppress all specified characters. So what if $COMMAND do contain spaces...

COMMAND=$'         \n        RE BOOT      \r           \n'
echo "|$COMMAND|"

echo "|$CLEANED|"
|                 RE BOOT                 |

shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}

echo "|$CLEANED|"
|                 RE BOOT|

echo "|$CLEANED|"


COMMAND=$'         \n        RE BOOT      \r           \n'
CLEANED=${COMMAND//[$'\t\r\n']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"

Note: have extglob option to be enabled (shopt -s extglob) in order to use *(...) syntax.

Sorting an ArrayList of objects using a custom sorting order

In addition to what was already posted you should know that since Java 8 we can shorten our code and write it like:

Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));

or since List now have sort method



Since Java 8, functional interfaces (interfaces with only one abstract method - they can have more default or static methods) can be easily implemented using:

Since Comparator<T> has only one abstract method int compare(T o1, T o2) it is functional interface.

So instead of (example from @BalusC answer)

Collections.sort(contacts, new Comparator<Contact>() {
    public int compare(Contact one, Contact other) {
        return one.getAddress().compareTo(other.getAddress());

we can reduce this code to:

Collections.sort(contacts, (Contact one, Contact other) -> {
     return one.getAddress().compareTo(other.getAddress());

We can simplify this (or any) lambda by skipping

  • argument types (Java will infer them based on method signature)
  • or {return ... }

So instead of

(Contact one, Contact other) -> {
     return one.getAddress().compareTo(other.getAddress();

we can write

(one, other) -> one.getAddress().compareTo(other.getAddress())

Also now Comparator has static methods like comparing(FunctionToComparableValue) or comparing(FunctionToValue, ValueComparator) which we could use to easily create Comparators which should compare some specific values from objects.

In other words we can rewrite above code as

Collections.sort(contacts, Comparator.comparing(Contact::getAddress)); 
//assuming that Address implements Comparable (provides default order).

Javascript add method to object

You can make bar a function making it a method. = function(passvariable){  };

As a property it would just be assigned a string, data type or boolean = "a place";

Modelling an elevator using Object-Oriented Analysis and Design

Main thing to worry about is how would you notify the elevator that it needs to move up or down. and also if you are going to have a centralized class to control this behavior and how could you distribute the control.

It seems like it can be very simple or very complicated. If we don't take concurrency or the time for an elevator to get to one place, then it seems like it will be simple since we just need to check the states of elevator, like is it moving up or down, or standing still. But if we make Elevator implement Runnable, and constantly check and synchronize a queue (linkedList). A Controller class will assign which floor to go in the queue. When the queue is empty, the run() method will wait (queue.wait() ), when a floor is assigned to this elevator, it will call queue.notify() to wake up the run() method, and run() method will call goToFloor(queue.pop()). This will make the problem too complicated. I tried to write it on paper, but dont think it works. It seems like we don't really need to take concurrency or timing issue into account here, but we do need to somehow use a queue to distribute the control.

Any suggestion?

how to create dynamic two dimensional array in java?

One more example for 2 dimension String array:

public void arrayExam() {
    List<String[]> A = new ArrayList<String[]>();
    A.add(new String[] {"Jack","good"});
    A.add(new String[] {"Mary","better"});
    A.add(new String[] {"Kate","best"});
    for (String[] row : A) {
        Log.i(TAG,row[0] + "->" + row[1]);


17467 08-02 19:24:40.518  8456  8456 I MyExam  : Jack->good
17468 08-02 19:24:40.518  8456  8456 I MyExam  : Mary->better
17469 08-02 19:24:40.518  8456  8456 I MyExam  : Kate->best

How to get UTC timestamp in Ruby?

Time.utc(2010, 05, 17)

How to browse localhost on Android device?

If you want to access a server running on your PC from your Android device via your wireless network, first run the command ipconfig on your PC (use run (Windows logo + R), cmd, ipconfig).

Note the IPv4 address: (it should be 192.168.0.x) for some x. Use this as the server IP address, together with the port number, e.g., in your code.

Your Android device will then access the server via your wireless network router.

jQuery click event not working after adding class

.live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax

$(document).on('click', "a.tabclick", function() {

This syntax will work for delegated events


Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

Java 9 JDK 9.0.4

  1. Go to the top left corner of Android Studio (4.1.1)-> click on File
  2. Click on Setting
  3. Click on Build, Execution, Deployment
  4. Click on Compiler
  5. Click on Kotlin Compiler
  6. Target JVM version

File | Settings | Build, Execution, Deployment | Compiler | Kotlin Compiler

Understanding Chrome network log "Stalled" state

Google gives a breakdown of these fields in the Evaluating network performance section of their DevTools documentation.

Excerpt from Resource network timing:


Time the request spent waiting before it could be sent. This time is inclusive of any time spent in proxy negotiation. Additionally, this time will include when the browser is waiting for an already established connection to become available for re-use, obeying Chrome's maximum six TCP connection per origin rule.

(If you forget, Chrome has an "Explanation" link in the hover tooltip and under the "Timing" panel.)

Basically, the primary reason you will see this is because Chrome will only download 6 files per-server at a time and other requests will be stalled until a connection slot becomes available.

This isn't necessarily something that needs fixing, but one way to avoid the stalled state would be to distribute the files across multiple domain names and/or servers, keeping CORS in mind if applicable to your needs, however HTTP2 is probably a better option going forward. Resource bundling (like JS and CSS concatenation) can also help to reduce amount of stalled connections.

How do I count occurrence of duplicate items in array

    $input = [1,2,1,3,2,4,10];
    //if give string
    //$input = "hello hello how are you how hello";
    //$array = explode(' ',$input);
    $count_val = [];
    foreach($array as $val){
//output ( [1] => 2 [2] => 2 [3] => 1 [4] => 1 [10] => 1 )

How to install a previous exact version of a NPM package?

For yarn users:

yarn add package_name@version_number

Programmatically go back to the previous fragment in the backstack

This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.

On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !

Inside activities on back pressed put this:

Fragment home = getSupportFragmentManager().findFragmentByTag("DetailedPizza");

if (home instanceof FragmentDetailedPizza && home.isVisible()) {
    if (getFragmentManager().getBackStackEntryCount() != 0) {
    } else {
} else {
    //Primary fragment

And launch the other fragment like this:

Fragment someFragment = new FragmentDetailedPizza();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(, someFragment, "DetailedPizza");

PHP form - on submit stay on same page

You can see the following example for the Form action on the same page

<form action="" method="post">
<table border="1px">
    <tr><td>Name: <input type="text" name="user_name" ></td></tr>
    <tr><td align="right"> <input type="submit" value="submit" name="btn"> 

     echo 'Welcome '. $name; 

Can you hide the controls of a YouTube embed without enabling autoplay?

use autoplay=0

autoplay takes 2 values.

Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.

the important part


Here is the demo for ur problem FIDDLE

HTTP Content-Type Header and JSON

Content-Type: application/json is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html.

Keep in mind, that JSON in JavaScript is an array or object. If you want to see all the data, use console.log instead of alert:

alert(response.text); // Will alert "[object Object]" string
console.log(response.text); // Will log all data objects

If you want to alert the original JSON content as a string, then add single quotation marks ('):

echo "'" . json_encode(array('text' => 'omrele')) . "'";
// alert(response.text) will alert {"text":"omrele"}

Do not use double quotes. It will confuse JavaScript, because JSON uses double quotes on each value and key:

echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';

// It will return the wrong JavaScript code:
<script>var returndata="{"text":"omrele"}";</script>

How to create a new column in a select query

SELECT field1, 
       'example' AS newfield

This will add a column called "newfield" to the output, and its value will always be "example".

How can I monitor the thread count of a process on linux?

JStack is quite inexpensive - one option would be to pipe the output through grep to find active threads and then pipe through wc -l.

More graphically is JConsole, which displays the thread count for a given process.

How to find out what is locking my tables?

For getting straight to "who is blocked/blocking" I combined/abbreviated sp_who and sp_lock into a single query which gives a nice overview of who has what object locked to what level.

--Create Procedure WhoLock
set nocount on
if object_id('tempdb..#locksummary') is not null Drop table #locksummary
if object_id('tempdb..#lock') is not null Drop table #lock
create table #lock (    spid int,    dbid int,    objId int,    indId int,    Type char(4),    resource nchar(32),    Mode char(8),    status char(6))
Insert into #lock exec sp_lock
if object_id('tempdb..#who') is not null Drop table #who
create table #who (     spid int, ecid int, status char(30),
            loginame char(128), hostname char(128),
            blk char(5), dbname char(128), cmd char(16)
            , request_id INT --Needed for SQL 2008 onwards
Insert into #who exec sp_who
Print '-----------------------------------------'
Print 'Lock Summary for ' + @@servername  + ' (excluding tempdb):'
Print '-----------------------------------------' + Char(10)
Select     left(loginame, 28) as loginame, 
    left(db_name(dbid),128) as DB,
    left(object_name(objID),30) as object,
    max(mode) as [ToLevel],
    Count(*) as [How Many],
    Max(Case When mode= 'X' Then cmd Else null End) as [Xclusive lock for command],
    l.spid, hostname
into #LockSummary
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and l.status='GRANT'
group by dbID, objID, l.spid, hostname, loginame

Select * from #LockSummary order by [ToLevel] Desc, [How Many] Desc, loginame, DB, object

Print '--------'
Print 'Who is blocking:'
Print '--------' + char(10)
SELECT p.spid
,convert(char(12), db_name
, program_name
, p.loginame
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM      master..sysprocesses p
JOIN      master..sysdatabases d ON p.dbid =  d.dbid
          FROM      master..sysprocesses p2
          WHERE     p2.blocked = p.spid )

Print '--------'
Print 'Details:'
Print '--------' + char(10)
Select     left(loginame, 30) as loginame,  l.spid,
    left(db_name(dbid),15) as DB,
    left(object_name(objID),40) as object,
    mode ,
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and blk <>0
Order by mode desc, blk, loginame, dbID, objID, l.status

(For what the lock level abbreviations mean, see e.g.

Copied from: sp_WhoLock – a T-SQL stored proc combining sp_who and sp_lock...

NB the [Xclusive lock for command] column can be misleading -- it shows the current command for that spid; but the X lock could have been triggered by an earlier command in the transaction.

Find index of last occurrence of a substring in a string

The more_itertools library offers tools for finding indices of all characters or all substrings.


import more_itertools as mit

s = "hello"
pred = lambda x: x == "l"



Now there is the rlocate tool available:

next(mit.rlocate(s, pred))
# 3

A complementary tool is locate:

list(mit.locate(s, pred))[-1]
# 3

mit.last(mit.locate(s, pred))
# 3


There is also a window_size parameter available for locating the leading item of several items:

s = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
substring = "chuck"
pred = lambda *args: args == tuple(substring)

next(mit.rlocate(s, pred=pred, window_size=len(substring)))
# 59

Scroll to the top of the page after render in react.js

Since the original solution was provided for very early version of react, here is an update:

constructor(props) {
    this.myRef = React.createRef()   // Create a ref object 

componentDidMount() {
  this.myRef.current.scrollTo(0, 0);

render() {
    return <div ref={this.myRef}></div> 
}   // attach the ref property to a dom element

Create a date from day month and year with T-SQL

For SQL Server versions below 12 i can recommend use of CAST in combination with SET DATEFORMAT

-- 26 February 2015
SELECT CAST('26-2-2015' AS DATE)

SELECT CAST('2015-2-26' AS DATE)

how you create those strings is up to you

Spring MVC - How to get all request params in a map in Spring controller?


It has been pointed out that there exists (at least as of 3.0) a pure Spring MVC mechanism by which one could get this data. I will not detail it here, as it is the answer of another user. See @AdamGent's answer for details, and don't forget to upvote it.

In the Spring 3.2 documentation this mechanism is mentioned on both the RequestMapping JavaDoc page and the RequestParam JavaDoc page, but prior, it is only mentioned in the RequestMapping page. In 2.5 documentation there is no mention of this mechanism.

This is likely the preferred approach for most developers as it removes (at least this) binding to the HttpServletRequest object defined by the servlet-api jar.


You should have access to the requests query string via request.getQueryString().

In addition to getQueryString, the query parameters can also be retrieved from request.getParameterMap() as a Map.

Is there a way to make text unselectable on an HTML page?

If it looks bad you can use CSS to change the appearance of selected sections.

How do I get the time difference between two DateTime objects using C#?

What you need is to use the DateTime classs Subtract method, which returns a TimeSpan.

var dateOne = DateTime.Now;
var dateTwo = DateTime.Now.AddMinutes(-5);
var diff = dateTwo.Subtract(dateOne);
var res = String.Format("{0}:{1}:{2}", diff.Hours,diff.Minutes,diff.Seconds));

How to add text to JFrame?

To create a label for text:

JLabel label1 = new JLabel("Test");

To change the text in the label:

label1.setText("Label Text");

And finally to clear the label:


And all you have to do is place the label in your layout, or whatever layout system you are using, and then just add it to the JFrame...

Search for executable files using find command

So if you actually want to find executable file types (e.g. scripts, ELF binaries etc.. etc..) not merely files with execution permission then you probably want to do something more like this (where the current directory . can be replaced with whatever directory you want):

 gfind . -type f -exec bash -c '[[ $(file -b "'{}'") == *" executable "* ]] ' \; -print

Or for those of you who aren't using macports (linux users) or otherwise have gnu find installed as find you want:

 find . -type f -exec bash -c '[[ $(file -b "'{}'") == *" executable "* ]] ' \; -print

Though if you are on OS X it comes with a little utility hidden somewhere called is_exec that basically bundles up that little test for you so you can shorten the command line if you find it. But this way is more flexible as you can easily replace the == test with the =~ test and use it to check for more complex properties like executable plain text files or whatever other info your file command returns.

The exact rules for quotation here are pretty opaque so I just end up working it out by trial and error but I'd love to hear the right explanation.

Sound alarm when code finishes

On Windows

import winsound
duration = 1000  # milliseconds
freq = 440  # Hz
winsound.Beep(freq, duration)

Where freq is the frequency in Hz and the duration is in milliseconds.

On Linux and Mac

import os
duration = 1  # seconds
freq = 440  # Hz
os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))

In order to use this example, you must install sox.

On Debian / Ubuntu / Linux Mint, run this in your terminal:

sudo apt install sox

On Mac, run this in your terminal (using macports):

sudo port install sox

Speech on Mac

import os
os.system('say "your program has finished"')

Speech on Linux

import os
os.system('spd-say "your program has finished"')

You need to install the speech-dispatcher package in Ubuntu (or the corresponding package on other distributions):

sudo apt install speech-dispatcher

How to remove text from a string?

Plain old JavaScript will suffice - jQuery is not necessary for such a simple task:

var myString = "data-123";
var myNewString = myString.replace("data-", "");

See: .replace() docs on MDN for additional information and usage.

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})


<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Python Pandas replicate rows in dataframe

This is an old question, but since it still comes up at the top of my results in Google, here's another way.

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

Say you want to replicate the rows where col1="b".

reps = [3 if val=="b" else 1 for val in df.col1]
df.loc[np.repeat(df.index.values, reps)]

You could replace the 3 if val=="b" else 1 in the list interpretation with another function that could return 3 if val=="b" or 4 if val=="c" and so on, so it's pretty flexible.

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component


        android:stepSize="10" />

How get an apostrophe in a string in javascript

This is plain Javascript and has nothing to do with the jQuery library.

You simply escape the apostrophe with a backslash:

theAnchorText = 'I\'m home';

Another alternative is to use quotation marks around the string, then you don't have to escape apostrophes:

theAnchorText = "I'm home";

Casting objects in Java

Sometimes you will like to receive as argument a Parent reference and inside you probably want to do something specific of a child.

abstract class Animal{
 public abstract void move();
class Shark extends Animal{
 public void move(){
 public void swim(){}
 public void bite(){}
class Dog extends Animal{
 public void move(){
 public void run(){}
 public void bark(){}


void somethingSpecific(Animal animal){
 // Here you don't know and may don't care which animal enters
 animal.move(); // You can call parent methods but you can't call bark or bite.
 if(animal instanceof Shark){
  Shark shark = (Shark)animal;
  shark.bite(); // Now you can call bite!
 //doSomethingSharky(animal); // You cannot call this method.


In above's method you can pass either Shark or Dog, but what if you have something like this:

void doSomethingSharky(Shark shark){
 //Here you cannot receive an Animal reference

That method can only be called by passing shark references So if you have an Animal (and it is deeply a Shark) you can call it like this:

Animal animal...
doSomethingSharky((Shark) animal)

Bottom line, you can use Parent references and it is usually better when you don't care about the implementation of the parent and use casting to use the Child as an specific object, it will be exactly the same object, but your reference know it, if you don't cast it, your reference will point to the same object but cannot be sure what kind of Animal would it be, therefore will only allow you to call known methods.

Python error "ImportError: No module named"

To mark a directory as a package you need a file named, does this help?

mongodb how to get max value from collections

what about using aggregate framework:

db.collection.aggregate({ $group : { _id: null, max: { $max : "$age" }}});

Change bootstrap navbar background color and font color

I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    color: #000; /*Sets the text hover color on navbar*/

.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
        a:hover, .navbar-default .navbar-nav > .active > a:focus {
    color: white; /*BACKGROUND color for active*/
    background-color: #030033;

.navbar-default {
    background-color: #0f006f;
    border-color: #030033;

.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
    color: #262626;
    text-decoration: none;
    background-color: #66CCFF; /*change color of links in drop down here*/

.nav > li > a:hover,
.nav > li > a:focus {
    text-decoration: none;
    background-color: silver; /*Change rollover cell color here*/

.navbar-default .navbar-nav > li > a {
    color: white; /*Change active text color here*/

How do I change the database name using MySQL?

Unfortunately, MySQL does not explicitly support that (except for dumping and reloading database again).


13.1.32. RENAME DATABASE Syntax

RENAME {DATABASE | SCHEMA} db_name TO new_db_name;

This statement was added in MySQL 5.1.7 but was found to be dangerous and was removed in MySQL 5.1.23. ... Use of this statement could result in loss of database contents, which is why it was removed. Do not use RENAME DATABASE in earlier versions in which it is present.

target="_blank" vs. target="_new"

USE _blank

The target attribute specifies where to open the linked document.

USAGE: target="xyz"  [don't forget double quotes]

_blank  Opens the linked document in a new window or tab
_self   Opens the linked document in the same frame as it was clicked (this is default)
_parent     Opens the linked document in the parent frame
_top    Opens the linked document in the full body of the window 
framename   Opens the linked document in a named frame

SINCE "_new" is not any of these IT WILL COME UNDER "framename" so if a user re-clicks on that hyperlink it will not open a new tab instead update the existing tab. Whereas in _blank if user clicks twice then 2 new tabs open.

setting global sql_mode in mysql

Setting sql mode permanently using mysql config file.

In my case i have to change file /etc/mysql/mysql.conf.d/mysqld.cnf as mysql.conf.d is included in /etc/mysql/my.cnf. i change this under [mysqld]


just removed ONLY_FULL_GROUP_BY sql mode cause it was causing issue.

I am using ubuntu 16.04, php 7 and mysql --version give me this mysql Ver 14.14 Distrib 5.7.13, for Linux (x86_64) using EditLine wrapper

After this change run below commands

sudo service mysql stop
sudo service mysql start

Now check sql modes by this query SELECT @@sql_mode and you should get modes that you have just set.

Make Div Draggable using CSS

You can take a look at HTML 5, but I don't think you can restrict the area within you can drag it, just the destination:

And if you don't mind using some great library, I would encourage you to try Dragula.

How to rename files and folder in Amazon S3?

rename all the *.csv.err files in the <<bucket>>/landing dir into *.csv files with s3cmd

 export aws_profile='foo-bar-aws-profile'
 while read -r f ; do tgt_fle=$(echo $f|perl -ne 's/^(.*).csv.err/$1.csv/g;print'); \
        echo s3cmd -c ~/.aws/s3cmd/$aws_profile.s3cfg mv $f $tgt_fle; \
 done < <(s3cmd -r -c ~/.aws/s3cmd/$aws_profile.s3cfg ls --acl-public --guess-mime-type \
        s3://$bucket | grep -i landing | grep csv.err | cut -d" " -f5)

How to scroll HTML page to given anchor?

$(document).ready ->
  $("a[href^='#']").click ->
      scrollTop: $($(this).attr("href")).offset().top, 1000

How to open a second activity on click of button in android app

If you have two buttons and have the same id call to your button click events like this:

Button btn1;
Button btn2;
protected void onCreate(Bundle savedInstanceState) {

    btn1= (Button)findViewById(;

    btn1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent=new Intent(MainActivity.this,target.class);

    btn2=(Button) findViewById(;//Have same id call previous button---> button1

    btn2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {


When you clicked button1, button2 will work and you cannot open your second activity.

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

This issue is caused in Laravel 5.4 by the database version.

According to the docs (in the Index Lengths & MySQL / MariaDB section):

Laravel uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider.

In other words, in <ROOT>/app/Providers/AppServiceProvider.php:

// Import Schema
use Illuminate\Support\Facades\Schema;
// ...

class AppServiceProvider extends ServiceProvider

public function boot()
    // Add the following line

// ...


But as the comment on the other answer says:

Be careful about this solution. If you index email fields for example, stored emails can only have a max length of 191 chars. This is less than the official RFC states.

So the documentation also proposes another solution:

Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database's documentation for instructions on how to properly enable this option.

Find the closest ancestor element that has a specific class

Based on the the8472 answer and here is cross-platform 2017 solution:

if (!Element.prototype.matches) {
    Element.prototype.matches =
        Element.prototype.matchesSelector ||
        Element.prototype.mozMatchesSelector ||
        Element.prototype.msMatchesSelector ||
        Element.prototype.oMatchesSelector ||
        Element.prototype.webkitMatchesSelector ||
        function(s) {
            var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                i = matches.length;
            while (--i >= 0 && matches.item(i) !== this) {}
            return i > -1;

function findAncestor(el, sel) {
    if (typeof el.closest === 'function') {
        return el.closest(sel) || null;
    while (el) {
        if (el.matches(sel)) {
            return el;
        el = el.parentElement;
    return null;

Add a CSS border on hover without moving the element

Add a border to the regular item, the same color as the background, so that it cannot be seen. That way the item has a border: 1px whether it is being hovered or not.

Aligning rotated xticklabels with their respective xticks

You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

Given your description, you want: ha='right'


x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

enter image description here

What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.

Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE

so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.

also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.

Make a UIButton programmatically in Swift

try these..i hope it helps...

override func viewDidLoad() {

    let btn = UIButton()
    btn.frame = CGRectMake(10, 10, 50, 50)  //set frame
    btn.setTitle("btn", forState: .Normal)  //set button title
    btn.setTitleColor(UIColor.redColor(), forState: .Normal) //set button title color
    btn.backgroundColor = UIColor.greenColor() //set button background color
    btn.tag = 1 // set button tag
    btn.addTarget(self, action: "btnclicked:", forControlEvents: .TouchUpInside) //add button action
    self.view.addSubview(btn) //add button in view


these is buttons click event..

func btnclicked(sender: UIButton!) 
    //write the task you want to perform on buttons click event..

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

Check for internet connection with Swift

Swift 5

import SystemConfiguration    

protocol Utilities {}
extension NSObject: Utilities {
    enum ReachabilityStatus {
        case notReachable
        case reachableViaWWAN
        case reachableViaWiFi
    var currentReachabilityStatus: ReachabilityStatus {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
        zeroAddress.sin_family = sa_family_t(AF_INET)
        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
        }) else {
            return .notReachable
        var flags: SCNetworkReachabilityFlags = []
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return .notReachable
        if flags.contains(.reachable) == false {
            // The target host is not reachable.
            return .notReachable
        else if flags.contains(.isWWAN) == true {
            // WWAN connections are OK if the calling application is using the CFNetwork APIs.
            return .reachableViaWWAN
        else if flags.contains(.connectionRequired) == false {
            // If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi...
            return .reachableViaWiFi
        else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false {
            // The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed
            return .reachableViaWiFi
        else {
            return .notReachable

In any method use the below condition

if currentReachabilityStatus == .notReachable {
    // Network Unavailable
} else {
    // Network Available

How do I force Robocopy to overwrite files?

I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:

FOR /F "tokens=*" %G IN ('dir /b') DO robocopy  "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0

As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.

It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.

Does Java have an exponential operator?

To do this with user input:

public static void getPow(){
    Scanner sc = new Scanner(;
    System.out.println("Enter first integer: ");    // 3
    int first = sc.nextInt();
    System.out.println("Enter second integer: ");    // 2
    int second = sc.nextInt();
    System.out.println(first + " to the power of " + second + " is " + 
        (int) Math.pow(first, second));    // outputs 9

JavaScript backslash (\) in variables is causing an error

The backslash (\) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).

In order to output a literal backslash, you need to escape it. That means \\ will output a single backslash (and \\\\ will output two, and so on). The reason "aa ///\" doesn't work is because the backslash escapes the " (which will print a literal quote), and thus your string is not properly terminated. Similarly, "aa ///\\\" won't work, because the last backslash again escapes the quote.

Just remember, for each backslash you want to output, you need to give Javascript two.

Relative imports - ModuleNotFoundError: No module named x

TL;DR: You can't do relative imports from the file you execute since __main__ module is not a part of a package.

Absolute imports - import something available on sys.path

Relative imports - import something relative to the current module, must be a part of a package

If you're running both variants in exactly the same way, one of them should work. Here is an example that should help you understand what's going on. Let's add another file with the overall directory structure like this:


And let's update to see what's going on:

debug = True

    # Trying to find module in the parent package
    from . import config
    del config
except ImportError:
    print('Relative import failed')

    # Trying to find module on sys.path
    import config
except ModuleNotFoundError:
    print('Absolute import failed')
import ryan.test

Let's run first:

$ python ryan/
Relative import failed

Here "test" is the __main__ module and doesn't know anything about belonging to a package. However import config should work, since the ryan folder will be added to sys.path.

Let's run instead:

$ python
Absolute import failed

And here test is inside of the "ryan" package and can perform relative imports. import config fails since implicit relative imports are not allowed in Python 3.

Hope this helped.

P.S.: If you're sticking with Python 3 there is no more need for files.

How to get all possible combinations of a list’s elements?

Here is one using recursion:

>>> import copy
>>> def combinations(target,data):
...     for i in range(len(data)):
...         new_target = copy.copy(target)
...         new_data = copy.copy(data)
...         new_target.append(data[i])
...         new_data = data[i+1:]
...         print new_target
...         combinations(new_target,
...                      new_data)
>>> target = []
>>> data = ['a','b','c','d']
>>> combinations(target,data)
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'd']
['a', 'c']
['a', 'c', 'd']
['a', 'd']
['b', 'c']
['b', 'c', 'd']
['b', 'd']
['c', 'd']

how to create a list of lists

Just came across the same issue today...

In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:

listoflists = []

What is causing the error `string.split is not a function`?

Change this...

var string = document.location;

to this...

var string = document.location + '';

This is because document.location is a Location object. The default .toString() returns the location in string form, so the concatenation will trigger that.

You could also use document.URL to get a string.

Any way to break if statement in PHP?

I'm late to the party but I wanted to contribute. I'm surprised that nobody suggested exit(). It's good for testing. I use it all the time and works like charm.

$a ='';
$b ='';
if($a == $b){
echo 'Clark Kent is Superman';
echo 'Clark Kent was never Superman';

The code will stop at exit() and everything after will not run.


Clark Kent is Superman

It works with foreach() and while() as well. It works anywhere you place it really.

foreach($arr as $val)
  echo "test";

echo "finish";


nothing gets printed here.

Use it with a forloop()

for ($x = 2; $x < 12; $x++) {
    echo "Gru has $x minions <br>";
    if($x == 4){


Gru has 2 minions
Gru has 3 minions
Gru has 4 minions

In a normal case scenario

$a ='Make hot chocolate great again!';
echo $a;
$b = 'I eat chocolate and make Charlie at the Factory pay for it.';


Make hot chocolate great again!

What does SQL clause "GROUP BY 1" mean?

SELECT account_id, open_emp_id
         ^^^^        ^^^^
          1           2

FROM account

In above query GROUP BY 1 refers to the first column in select statement which is account_id.

You also can specify in ORDER BY.

Note : The number in ORDER BY and GROUP BY always start with 1 not with 0.

convert UIImage to NSData

Try one of the following, depending on your image format:


Returns the data for the specified image in JPEG format.

NSData * UIImageJPEGRepresentation (
   UIImage *image,
   CGFloat compressionQuality


Returns the data for the specified image in PNG format

NSData * UIImagePNGRepresentation (
   UIImage *image

Here the docs.


if you want to access the raw bytes that make up the UIImage, you could use this approach:

CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];

This will give you the low-level representation of the image RGB pixels. (Omit the CFBridgingRelease bit if you are not using ARC).

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

If your passing id, then try to follow this method

 const routes: Routes = [
  {path:"", redirectTo:"/home", pathMatch:"full"},
  {path:"home", component:HomeComponent},
  {path:"add", component:AddComponent},
  {path:"edit/:id", component:EditComponent},
  {path:"show/:id", component:ShowComponent}
  imports: [

  exports: [RouterModule],
  declarations: []
export class AppRoutingModule { }

How to show current user name in a cell?

The simplest way is to create a VBA macro that wraps that function, like so:

Function UserNameWindows() As String
    UserName = Environ("USERNAME")
End Function

Then call it from the cell:


See this article for more details, and other ways.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

Some operations in Excel are limited by available Memory. If you repeat the same process over and over it could produce a memory overflow and excel will not be able to repeat it anymore. This happened to me while trying to create several sheets in the same workbook.

Iterate a list with indexes in Python

>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
...     print i, val
0 3
1 4
2 5
3 6

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

Added MSSQLSERVER full access to the folder, diskadmin and bulkadmin server roles.

In my c# application, when preparing for the bulk insert command,

string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And I get this error - Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 8 (STATUS).

I looked at my logfile and found that the terminator becomes ' ' instead of '\n'. The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error:

Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)". Query :BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\NEWSTAGEWWW\CalAtlasToPWCR\Results\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', **ROWTERMINATOR = ''**)

So I added extra escape to the rowterminator - string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And now it inserts successfully.

Bulk Insert SQL -   --->  BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\\NEWSTAGEWWW\\CalAtlasToPWCR\\Results\\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
Bulk Insert to PWCR_Contractor_vw_TEST successful...  --->  clsDatase.PerformBulkInsert

Node.js spawn child process and get terminal output live

I'm still getting my feet wet with Node.js, but I have a few ideas. first, I believe you need to use execFile instead of spawn; execFile is for when you have the path to a script, whereas spawn is for executing a well-known command that Node.js can resolve against your system path.

1. Provide a callback to process the buffered output:

var child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3', 
], function(err, stdout, stderr) { 
    // Node.js will invoke this callback when process terminates.

2. Add a listener to the child process' stdout stream (

var child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3' ]); 
// use event hooks to provide a callback to execute when data are available: 
child.stdout.on('data', function(data) {

Further, there appear to be options whereby you can detach the spawned process from Node's controlling terminal, which would allow it to run asynchronously. I haven't tested this yet, but there are examples in the API docs that go something like this:

child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3', 
], { 
    // detachment and ignored stdin are the key here: 
    detached: true, 
    stdio: [ 'ignore', 1, 2 ]
// and unref() somehow disentangles the child's event loop from the parent's: 
child.stdout.on('data', function(data) {

Difference between Console.Read() and Console.ReadLine()?

These are the methods of system.console

  • ReadKey() (returns a character): reads only one single character from the standard input stream or command line. Usually used when you're giving options to the user in the console to select from, such as select A, B or C. Another prominent example, Press Y or n to continue.
  • ReadLine() (returns a string): or Console.Readline() reads a single line from the standard input stream or the command line. As an example, it can be used to ask the user enter their name or age. It reads all the character till we press enter.
  • Read() (returns an int): or Console.Read() reads only one single character from the standard input stream. Similar to ReadKey except that it returns an integer. It returns the next character from the input stream, or returns (-1) if there is no more character to be read.

(There are more system.console methods like write() and writeline() as well which are used to write in command line, behaving similarly as read() and readline() methods)

This was clearly described with examples in the MSDN documentation (links are included above).

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I update my Hibernate JPA to 2.1 and It works.


Why there is no ConcurrentHashSet against ConcurrentHashMap

It looks like Java provides a concurrent Set implementation with its ConcurrentSkipListSet. A SkipList Set is just a special kind of set implementation. It still implements the Serializable, Cloneable, Iterable, Collection, NavigableSet, Set, SortedSet interfaces. This might work for you if you only need the Set interface.

Remove the last character in a string in T-SQL?

Try this:

select substring('test string', 1, (len('test string') - 1))

Android, How to limit width of TextView (and add three dots at the end of text)?

The approach of @AzharShaikh works fine.


But I realize a trouble that TextView will be truncated by word (in default). Show if we have a text like:

test long_line_without_any_space_abcdefgh

the TextView will display:


And I found solution to handle this trouble, replace spaces with the unicode no-break space character, it makes TextView wrap on characters instead of words:

yourString.replace(" ", "\u00A0");

The result:

test long_line_without_any_space_abc...

Check for special characters (/*-+_@&$#%) in a string?

Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:

[a-zA-Z0-9 ]

How do I enable the column selection mode in Eclipse?

  • Press Alt + Shift + A
  • Observe that the screen zooms out
  • Make selection using the mouse
  • Press Alt + Shift + A to go back to the old mode. enter image description here

How to change language of app when user selects language?

Udhay's sample code works well. Except the question of Sofiane Hassaini and Chirag SolankI, for the re-entrance, it doesn't work. I try to call Udhay's code without restart the activity in onCreate() , before super.onCreate(savedInstanceState);. Then it is OK! Only a little problem, the menu strings still not changed to the set Locale.

    public void setLocale(String lang) { //call this in onCreate()
      Locale myLocale = new Locale(lang); 
      Resources res = getResources(); 
      DisplayMetrics dm = res.getDisplayMetrics(); 
      Configuration conf = res.getConfiguration(); 
      conf.locale = myLocale; 
      res.updateConfiguration(conf, dm); 
      //Intent refresh = new Intent(this, AndroidLocalize.class); 

What is a semaphore?

Mutex: exclusive-member access to a resource

Semaphore: n-member access to a resource

That is, a mutex can be used to syncronize access to a counter, file, database, etc.

A sempahore can do the same thing but supports a fixed number of simultaneous callers. For example, I can wrap my database calls in a semaphore(3) so that my multithreaded app will hit the database with at most 3 simultaneous connections. All attempts will block until one of the three slots opens up. They make things like doing naive throttling really, really easy.

react native get TextInput value

Please take care on how to use setState(). The correct form is

      Key: Value,

And so I would do it as follows:

onChangeText={(event) => this.setState({username:event.nativeEvent.text})}
var username=this.state.username;

How do I check if the user is pressing a key?

In java you don't check if a key is pressed, instead you listen to KeyEvents. The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                    return false;

Then you can always use:

if (IsKeyPressed.isWPressed()) {
    // do your thing.

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

Check if Cookie Exists

public static class CookieHelper
    /// <summary>
    /// Checks whether a cookie exists.
    /// </summary>
    /// <param name="cookieCollection">A CookieCollection, such as Response.Cookies.</param>
    /// <param name="name">The cookie name to delete.</param>
    /// <returns>A bool indicating whether a cookie exists.</returns>
    public static bool Exists(this HttpCookieCollection cookieCollection, string name)
        if (cookieCollection == null)
            throw new ArgumentNullException("cookieCollection");

        return cookieCollection[name] != null;



What is the difference between mocking and spying when using Mockito?

The answer is in the documentation:

Real partial mocks (Since 1.8.0)

Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.

Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.

callRealMethod() was introduced after spy(), but spy() was left there of course, to ensure backward compatibility.

Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod() is called. In general, I would prefer using callRealMethod(), because it doesn't force me to use the doXxx().when() idiom instead of the traditional when().thenXxx()

What are the complexity guarantees of the standard containers?

I found the nice resource Standard C++ Containers. Probably this is what you all looking for.



vector<T> v;              Make an empty vector.                                     O(1)
vector<T> v(n);           Make a vector with N elements.                            O(n)
vector<T> v(n, value);    Make a vector with N elements, initialized to value.      O(n)
vector<T> v(begin, end);  Make a vector and copy the elements from begin to end.    O(n)


v[i]          Return (or set) the I'th element.                        O(1)       Return (or set) the I'th element, with bounds checking.  O(1)
v.size()      Return current number of elements.                       O(1)
v.empty()     Return true if vector is empty.                          O(1)
v.begin()     Return random access iterator to start.                  O(1)
v.end()       Return random access iterator to end.                    O(1)
v.front()     Return the first element.                                O(1)
v.back()      Return the last element.                                 O(1)
v.capacity()  Return maximum number of elements.                       O(1)


v.push_back(value)         Add value to end.                                                O(1) (amortized)
v.insert(iterator, value)  Insert value at the position indexed by iterator.                O(n)
v.pop_back()               Remove value from end.                                           O(1)
v.assign(begin, end)       Clear the container and copy in the elements from begin to end.  O(n)
v.erase(iterator)          Erase value indexed by iterator.                                 O(n)
v.erase(begin, end)        Erase the elements from begin to end.                            O(n)

For other containers, refer to the page.

android:drawableLeft margin and/or padding

You can use a padding for the button and you can play with drawablePadding

    android:onClick="actualizarBD" />

you can use a specific padding depends where put your drawable, with android:paddingLeft="10dp" or android:paddingBottom="10dp" or android:paddingRight="10dp" or android:paddingTop="10dp"

How do I detect what .NET Framework versions and service packs are installed?

In Windows 7 (it should work for Windows 8 also, but I haven't tested it):

Go to a command prompt

Steps to go to a command prompt:

  1. Click Start Menu
  2. In Search Box, type "cmd" (without quotes)
  3. Open cmd.exe

In cmd, type this command

wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get version

This gives the latest version of NET Framework installed.

One can also try Utilties for the same.

Rollback transaction after @Test

In addition to adding @Transactional on @Test method, you also need to add @Rollback(false)

MSVCP120d.dll missing

I have found myself wasting time searching for a solution on this, and i suspect doing it again in future. So here's a note to myself and others who might find this useful.

If MSVCP120.DLL is missing, that means you have not installed Visual C++ Redistributable Packages for Visual Studio 2013 (x86 and x64). Install that, restart and you should find this file in c:\Windows\System32 .

Now if MSVCP120D.DLL is missing, this means that the application you are trying to run is built in Debug mode. As OP has mentioned, the debug version of the runtime is NOT distributable.

So what do we do?

Well, there is one option that I know of: Go to your Project's Debug configuration > C/C++ > Code Generation > Runtime Library and select Multi-threaded Debug (/MTd). This will statically link MSVCP120D.dll into your executable.

There is also a quick-fix if you just want to get something up quickly: Copy the MSVCP120D.DLL from sys32 (mine is C:\Windows\System32) folder. You may also need MSVCR120D.DLL.

Addendum to the quick fix: To reduce guesswork, you can use dependency walker. Open your application with dependency walker, and you'll see what dll files are needed.

For example, my recent application was built in Visual Studio 2015 (Windows 10 64-bit machine) and I am targeting it to a 32-bit Windows XP machine. Using dependency walker, my application (see screenshot) needs the following files:

  • opencv_*.dll <-- my own dll files (might also have dependency)
  • msvcp140d.dll <-- SysWOW64\msvcp140d.dll
  • kernel32.dll <-- SysWOW64\kernel32.dll
  • vcruntime140d.dll <-- SysWOW64\vcruntime140d.dll
  • ucrtbased.dll <-- SysWOW64\ucrtbased.dll

Aside from the opencv* files that I have built, I would also need to copy the system files from C:\Windows\SysWow64 (System32 for 32-bit).

You're welcome. :-)

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

SQL grouping by all the columns

If you are using SqlServer the distinct keyword should work for you. (Not sure about other databases)

declare @t table (a int , b int)

insert into @t (a,b) select 1, 1
insert into @t (a,b) select 1, 2
insert into @t (a,b) select 1, 1

select distinct * from @t

results in

a b
1 1
1 2

remove objects from array by object property

If you just want to remove it from the existing array and not create a new one, try:

var items = [{Id: 1},{Id: 2},{Id: 3}];
items.splice(_.indexOf(items, _.find(items, function (item) { return item.Id === 2; })), 1);

Find stored procedure by name

For SQL Server version 9.0 (2005), you can use the code below:

select * 
syscomments c
inner join sys.procedures p on p.object_id =
where like '%usp_ConnectionsCount%';

How can I use external JARs in an Android project?

If using Android Studio, do the following (I've copied and modified @Vinayak Bs answer):

  1. Select the Project view in the Project sideview (instead of Packages or Android)
  2. Create a folder called libs in your project's root folder
  3. Copy your JAR files to the libs folder
  4. The sideview will be updated and the JAR files will show up in your project
  5. Now right click on each JAR file you want to import and then select "Add as Library...", which will include it in your project
  6. After that, all you need to do is reference the new classes in your code, eg. import javax.mail.*

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

How do I turn off the mysql password validation?

Further to the answer from ktbos:

I modified the mysqld.cnf file and mysql failed to start. It turned out that I was modifying the wrong file!

So be sure the file you modify contains segment tags like [mysqld_safe] and [mysqld]. Under the latter I did as suggested and added the line:


This worked perfectly to resolve my issue of not requiring special characters within the password.

How do I programmatically get the GUID of an application in .NET 2.0

Try the following code. The value you are looking for is stored on a GuidAttribute instance attached to the Assembly

using System.Runtime.InteropServices;

static void Main(string[] args)
    var assembly = typeof(Program).Assembly;
    var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute),true)[0];
    var id = attribute.Value;

Print content of JavaScript object?

Use dir(object). Or you can always download Firebug for Firefox (really helpful).

How do you run your own code alongside Tkinter's event loop?

The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to one place I checked, mishandling threading with Tkinter is unpredictable and platform-dependent.

The problem seems to be that app.start() counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing app.start() with a self.start() inside __init__. I also made it so that all Tk references are either inside the function that calls mainloop() or are inside functions that are called by the function that calls mainloop() (this is apparently critical to avoid the "different apartment" error).

Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user.

The revised code is as follows:

# Run tkinter code in another thread

import tkinter as tk
import threading

class App(threading.Thread):

    def __init__(self):

    def callback(self):

    def run(self):
        self.root = tk.Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)

        label = tk.Label(self.root, text="Hello World")


app = App()
print('Now we can continue running code while mainloop runs!')

for i in range(100000):

Javascript: Setting location.href versus location

Just to clarify, you can't do location.split('#'), location is an object, not a string. But you can do location.href.split('#'); because location.href is a string.

what is the use of Eval() in

While binding a databound control, you can evaluate a field of the row in your data source with eval() function.

For example you can add a column to your gridview like that :

<asp:BoundField DataField="YourFieldName" />

And alternatively, this is the way with eval :

        <asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>

It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :

        <asp:HyperLink ID="HyperLink1" runat="server" 
          NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>' 
          Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>

Android notification is not showing

For me it was an issue with deviceToken. Please check if the receiver and sender device token is properly updated in your database or wherever you are accessing it to send notifications.

For instance, use the following to update the device token on app launch. Therefore it will be always updated properly.

// Device token for push notifications
  new OnSuccessListener<InstanceIdResult>() {

    public void onSuccess(InstanceIdResult instanceIdResult) {

        deviceToken = instanceIdResult.getToken();

        // Insert device token into Firebase database
                  new OnSuccessListener<Void>() {

                    public void onSuccess(Void aVoid) {


Calling a function from a string in C#

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

Using C# to read/write Excel files (.xls/.xlsx)

You can use Excel Automation (it is basically a COM Base stuff) e.g:

Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;

xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("1.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

Link to the full tutorial

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

JSON find in JavaScript

If the JSON data in your array is sorted in some way, there are a variety of searches you could implement. However, if you're not dealing with a lot of data then you're probably going to be fine with an O(n) operation here (as you have). Anything else would probably be overkill.

Save bitmap to location

Make sure the directory is created before you call bitmap.compress:

new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();

JavaScript seconds to time string with format hh:mm:ss

function toHHMMSS(seconds) {
    var h, m, s, result='';
    // HOURs
    h = Math.floor(seconds/3600);
    seconds -= h*3600;
        result = h<10 ? '0'+h+':' : h+':';
    // MINUTEs
    m = Math.floor(seconds/60);
    seconds -= m*60;
    result += m<10 ? '0'+m+':' : m+':';
    // SECONDs
    result += s<10 ? '0'+s : s;
    return result;





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

The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.

MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.

For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).

enter image description here

Console output:


image = new MarvinImage();_x000D_
image.load("", imageLoaded);_x000D_
function imageLoaded(){_x000D_
  console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
  console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
<script src=""></script>

Efficiently replace all accented characters in a string?

The complete solution to your request is:

function convert_accented_characters(str){
    var conversions = new Object();
    conversions['ae'] = 'ä|æ|?';
    conversions['oe'] = 'ö|œ';
    conversions['ue'] = 'ü';
    conversions['Ae'] = 'Ä';
    conversions['Ue'] = 'Ü';
    conversions['Oe'] = 'Ö';
    conversions['A'] = 'À|Á|Â|Ã|Ä|Å|?|A|A|A|A';
    conversions['a'] = 'à|á|â|ã|å|?|a|a|a|a|ª';
    conversions['C'] = 'Ç|C|C|C|C';
    conversions['c'] = 'ç|c|c|c|c';
    conversions['D'] = 'Ð|D|Ð';
    conversions['d'] = 'ð|d|d';
    conversions['E'] = 'È|É|Ê|Ë|E|E|E|E|E';
    conversions['e'] = 'è|é|ê|ë|e|e|e|e|e';
    conversions['G'] = 'G|G|G|G';
    conversions['g'] = 'g|g|g|g';
    conversions['H'] = 'H|H';
    conversions['h'] = 'h|h';
    conversions['I'] = 'Ì|Í|Î|Ï|I|I|I|I|I|I';
    conversions['i'] = 'ì|í|î|ï|i|i|i|i|i|i';
    conversions['J'] = 'J';
    conversions['j'] = 'j';
    conversions['K'] = 'K';
    conversions['k'] = 'k';
    conversions['L'] = 'L|L|L|?|L';
    conversions['l'] = 'l|l|l|?|l';
    conversions['N'] = 'Ñ|N|N|N';
    conversions['n'] = 'ñ|n|n|n|?';
    conversions['O'] = 'Ò|Ó|Ô|Õ|O|O|O|O|O|Ø|?';
    conversions['o'] = 'ò|ó|ô|õ|o|o|o|o|o|ø|?|º';
    conversions['R'] = 'R|R|R';
    conversions['r'] = 'r|r|r';
    conversions['S'] = 'S|S|S|Š';
    conversions['s'] = 's|s|s|š|?';
    conversions['T'] = 'T|T|T';
    conversions['t'] = 't|t|t';
    conversions['U'] = 'Ù|Ú|Û|U|U|U|U|U|U|U|U|U|U|U|U';
    conversions['u'] = 'ù|ú|û|u|u|u|u|u|u|u|u|u|u|u|u';
    conversions['Y'] = 'Ý|Ÿ|Y';
    conversions['y'] = 'ý|ÿ|y';
    conversions['W'] = 'W';
    conversions['w'] = 'w';
    conversions['Z'] = 'Z|Z|Ž';
    conversions['z'] = 'z|z|ž';
    conversions['AE'] = 'Æ|?';
    conversions['ss'] = 'ß';
    conversions['IJ'] = '?';
    conversions['ij'] = '?';
    conversions['OE'] = 'Œ';
    conversions['f'] = 'ƒ';
    for(var i in conversions){
        var re = new RegExp(conversions[i],"g");
        str = str.replace(re,i);
    return str;

What are the options for (keyup) in Angular2?

If your keyup event is outside the CTRL, SHIFT, ENTER and ESC bracket, just use @Md Ayub Ali Sarker's guide. The only keyup pseudo-event mentioned here in angular docs is ENTER key. There are no keyup pseudo-events for number keys and alphabets yet.

Django: OperationalError No Such Table

This happened to me and for me it was because I added db.sqlite3 as untracked from repository. I added it and pushed it to server so it worked properly. Also run makemigartions and migrate after doing this.

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

Convert columns to string in Pandas

pandas >= 1.0: It's time to stop using astype(str)!

Prior to pandas 1.0 (well, 0.25 actually) this was the defacto way of declaring a Series/column as as string:

# pandas <= 0.25
# Note to pedants: specifying the type is unnecessary since pandas will 
# automagically infer the type as object
s = pd.Series(['a', 'b', 'c'], dtype=str)
# dtype('O')

From pandas 1.0 onwards, consider using "string" type instead.

# pandas >= 1.0
s = pd.Series(['a', 'b', 'c'], dtype="string")
# StringDtype

Here's why, as quoted by the docs:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than 'string'.

See also the section on Behavioral Differences between "string" and object.

Extension types (introduced in 0.24 and formalized in 1.0) are closer to pandas than numpy, which is good because numpy types are not powerful enough. For example NumPy does not have any way of representing missing data in integer data (since type(NaN) == float). But pandas can using Nullable Integer columns.

Why should I stop using it?

Accidentally mixing dtypes
The first reason, as outlined in the docs is that you can accidentally store non-text data in object columns.

# pandas <= 0.25
pd.Series(['a', 'b', 1.23])   # whoops, this should have been "1.23"

0       a
1       b
2    1.23
dtype: object

pd.Series(['a', 'b', 1.23]).tolist()
# ['a', 'b', 1.23]   # oops, pandas was storing this as float all the time.
# pandas >= 1.0
pd.Series(['a', 'b', 1.23], dtype="string")

0       a
1       b
2    1.23
dtype: string

pd.Series(['a', 'b', 1.23], dtype="string").tolist()
# ['a', 'b', '1.23']   # it's a string and we just averted some potentially nasty bugs.

Challenging to differentiate strings and other python objects
Another obvious example example is that it's harder to distinguish between "strings" and "objects". Objects are essentially the blanket type for any type that does not support vectorizable operations.


# Setup
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [{}, [1, 2, 3], 123]})
   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

Upto pandas 0.25, there was virtually no way to distinguish that "A" and "B" do not have the same type of data.

# pandas <= 0.25  

A    object
B    object
dtype: object


   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

From pandas 1.0, this becomes a lot simpler:

# pandas >= 1.0
# Convenience function I call to help illustrate my point.
df = df.convert_dtypes()

A    string
B    object
dtype: object


0  a
1  b
2  c

This is self-explanatory ;-)

OK, so should I stop using it right now?

...No. As of writing this answer (version 1.1), there are no performance benefits but the docs expect future enhancements to significantly improve performance and reduce memory usage for "string" columns as opposed to objects. With that said, however, it's never too early to form good habits!

'nuget' is not recognized but other nuget commands working

Nuget.exe is placed at .nuget folder of your project. It can't be executed directly in Package Manager Console, but is executed by Powershell commands because these commands build custom path for themselves.

My steps to solve are:


NuGet can be easily installed in your project using the following command:

Install-Package NuGet.CommandLine

TortoiseGit-git did not exit cleanly (exit code 1)

Try these two commands in git bash:

1) git gc --force

2) git fetch -p

Convert a row of a data frame to vector

Here is a dplyr based option:

newV = df %>% slice(1) %>% unlist(use.names = FALSE)

# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()

Can I open a dropdownlist using jQuery

No you can't.

You can change the size to make it larger... similar to Dreas idea, but it is the size you need to change.

<select id="countries" size="6">
  <option value="1">Country 1</option>
  <option value="2">Country 2</option>
  <option value="3">Country 3</option>
  <option value="4">Country 4</option>
  <option value="5">Country 5</option>
  <option value="6">Country 6</option>

PHP include relative path

You could always include it using __DIR__:


__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.


Should then work to include the config file from where you want.

How to specify 64 bit integers in c

Try an LL suffix on the number, the compiler may be casting it to an intermediate type as part of the parse. See

long long int i2 = 0x0000444400004444LL;

Additionally, the the compiler is discarding the leading zeros, so 0x000044440000 is becoming 0x44440000, which is a perfectly acceptable 32-bit integer (which is why you aren't seeing any warnings prior to f2).

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

LINQ query to select top five

Just thinking you might be feel unfamiliar of the sequence From->Where->Select, as in sql script, it is like Select->From->Where.

But you may not know that inside Sql Engine, it is also parse in the sequence of 'From->Where->Select', To validate it, you can try a simple script

select id as i from table where i=3

and it will not work, the reason is engine will parse Where before Select, so it won't know alias i in the where. To make this work, you can try

select * from (select id as i from table) as t where i = 3

Why is "except: pass" a bad programming practice?

Simply put, if an exception or error is thrown, something's wrong. It may not be something very wrong, but creating, throwing, and catching errors and exceptions just for the sake of using goto statements is not a good idea, and it's rarely done. 99% of the time, there was a problem somewhere.

Problems need to be dealt with. Just like how it is in life, in programming, if you just leave problems alone and try to ignore them, they don't just go away on their own a lot of times; instead they get bigger and multiply. To prevent a problem from growing on you and striking again further down the road, you either 1) eliminate it and clean up the mess afterwards, or 2) contain it and clean up the mess afterwards.

Just ignoring exceptions and errors and leaving them be like that is a good way to experience memory leaks, outstanding database connections, needless locks on file permissions, etc.

On rare occasions, the problem is so miniscule, trivial, and - aside from needing a try...catch block - self-contained, that there really is just no mess to be cleaned up afterwards. These are the only occasions when this best practice doesn't necessarily apply. In my experience, this has generally meant that whatever the code is doing is basically petty and forgoable, and something like retry attempts or special messages are worth neither the complexity nor holding the thread up on.

At my company, the rule is to almost always do something in a catch block, and if you don't do anything, then you must always place a comment with a very good reason why not. You must never pass or leave an empty catch block when there is anything to be done.

Using querySelectorAll to retrieve direct children

The following solution is different to the ones proposed so far, and works for me.

The rationale is that you select all matching children first, and then filter out the ones which are not direct children. A child is a direct child if it does not have a matching parent with the same selector.

function queryDirectChildren(parent, selector) {
    const nodes = parent.querySelectorAll(selector);
    const filteredNodes = [] => 
        n.parentNode.closest(selector) === parent.closest(selector)
    return filteredNodes;


A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

My solution below is for cases when default maven repositories are not accessible (e.g. due to firewalls).

In case the default repository is not accessible appropriate local <pluginRepository> has to be specified in the settings.xml. If it's the same as your local artifact repository it still needs to be added to the <pluginRepositories> section for plugin jars to be found. Regular <repositories> section is not used to fetch plugin jars.

In my case, however, the issue was caused by the fact that there were multiple plugin repositories defined in that section.

The first repository in the list did not contain the required maven-filtering jar.

I had to change the order of <pluginRepository> definitions to ensure the first one contains maven-filtering.

Changing of repository definitions typically requires to clean ~/.m2/repository and start fresh.

TransactionRequiredException Executing an update/delete query

I Got the same error.

I just added the @Transactional annotation of javax.transaction.Transactional on the method.

current/duration time of html5 video?

// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");

// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};

function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
    document.getElementById("demo").innerHTML = vid.currentTime;

@Nullable annotation usage

Different tools may interpret the meaning of @Nullable differently. For example, the Checker Framework and FindBugs handle @Nullable differently.

How to replace innerHTML of a div using jQuery?

If you instead have a jQuery object you want to render instead of the existing content: Then just reset the content and append the new.

var itemtoReplaceContentOf = $('#regTitle');



jQuery Cross Domain Ajax

You just have to parse the string using JSON.parse like this :

var json_result = {"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"};

var parsed = JSON.parse(json_result.AuthenticateUserResult);

Here you will have something like this :








And for the request, don't forget to set dataType:'jsonp' and to add a file in the root directory of your site called crossdomain.xml and containing :

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "">
<!-- Read this: -->

<!-- Most restrictive policy: -->
<site-control permitted-cross-domain-policies="none"/>

<!-- Least restrictive policy: -->
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" to-ports="*" secure="false"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>

EDIT to take care of Sanjay Kumar POST

So you can set the callback function to be called in the JSONP using jsonpCallback!

    jsonpCallback : 'your_function_name',
    //OR with anonymous function
    jsonpCallback : function(data) {
        //do stuff

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:


var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
        yield return resultSelector(outerElement, innerElement); 


var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 

Read more here:

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

This is something to do with user permissions. Giving proper grants will solve this issue.

Step [1]: Open terminal and run this command

$ mysql -uroot -p

Output [1]: This should give you mysql prompt shown below

enter image description here

Step [2]:

mysql> CREATE USER 'parsa'@'localhost' IDENTIFIED BY 'your_password';
mysql> grant all privileges on *.* to 'parsa'@'localhost';


mysql> grant all privileges on `database_name`.`table_name` to 'user_name'@'hostname';


  • hostname can be IP address, localhost,
  • In database_name/table_name, * means all databases
  • In hostname, to specify all hosts use '%'

Step [3]: Get out of current mysql prompt by either entering quit / exit command or press Ctrl+D.

Step [4]: Login to your new user

$ mysql -uparsa -pyour_password

Step [5]: Create the database

mysql> create database `database_name`;

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])

Source and discussion:

How to 'insert if not exists' in MySQL?

Try the following:

IF (SELECT COUNT(*) FROM beta WHERE name = 'John' > 0)
  UPDATE alfa SET c1=(SELECT id FROM beta WHERE name = 'John')
  INSERT INTO beta (name) VALUES ('John')

Thymeleaf using path variables to th:href

I was trying to go through a list of objects, display them as rows in a table, with each row being a link. This worked for me. Hope it helps.

// CUSTOMER_LIST is a model attribute
    <th:block th:each="customer : ${CUSTOMER_LIST}">
            <td><a th:href="@{'/main?id=' + ${}}" th:text="${customer.fullName}" /></td>

Most popular screen sizes/resolutions on Android phones

Another alternative to see popular android resolutions or aspect ratios is Unity statistics:

LATEST UNITY STATISTICS (on 2019.06 return http503) web arhive

Top on 2017-01:

Display Resolutions:

  • 1280 x 720: 28.9%
  • 1920 x 1080: 21.4%
  • 800 x 480: 10.3%
  • 854 x 480: 9.7%
  • 960 x 540: 8.9%
  • 1024 x 600: 7.8%
  • 1280 x 800: 5.0%
  • 2560 x 1440: 2.4%
  • 480 x 320: 1.2%
  • 1920 x 1200: 0.8%
  • 1024 x 768: 0.8%

Display Aspect Ratios:

  • 16:9: 72.4%
  • 5:3: 18.2%
  • 16:10: 6.2%
  • 4:3: 1.7%
  • 3:2: 1.2%
  • 5:4: 0.1%

Make new column in Panda dataframe by adding values from other columns

Building a little more on Anton's answer, you can add all the columns like this:

df['sum'] = df[list(df.columns)].sum(axis=1)

Can an AWS Lambda function call another

Amazon has introduced steps functions in AWS lambda in 2016. I think, now it's more convenient to use steps function as it's really easy to use them. You can build a state machine with two lambda functions as:

  • to produces a quote
  • turns a quote into an order

You can easily do that as below:

Here you can have first state for produces a quote and another to turns into order

  Comment: "Produce a quote and turns into an order",
  StartAt: "ProduceQuote",
  States: {
    ProduceQuote: {
      "Type": Task,
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:ProduceQuote",
      "next": TurnsToOrder
    TurnsToOrder: {
      Type: Task,
      Resource: "arn:aws:lambda:us-east-1:123456789012:function:ProduceQuote",
      end: true

Steps functions makes it really easy to write multiple lambda functions and run in sequence or in parallel. You can get more information about lambda steps functions here: Steps Functions

How to justify a single flexbox item (override justify-content)

There doesn't seem to be justify-self, but you can achieve similar result setting appropriate margin to auto¹. E. g. for flex-direction: row (default) you should set margin-right: auto to align the child to the left.

.container {_x000D_
  height: 100px;_x000D_
  border: solid 10px skyblue;_x000D_
  display: flex;_x000D_
  justify-content: flex-end;_x000D_
.block {_x000D_
  width: 50px;_x000D_
  background: tomato;_x000D_
.justify-start {_x000D_
  margin-right: auto;_x000D_
<div class="container">_x000D_
  <div class="block justify-start"></div>_x000D_
  <div class="block"></div>_x000D_

¹ This behaviour is defined by the Flexbox spec.

Send POST data via raw json with postman

Just check JSON option from the drop down next to binary; when you click raw. This should do

skill synon pass json to postman

Jquery UI Datepicker not displaying

I have found a trick solution. You can use the below codes.

/* any options you want */
beforeShowDay: function (date) {
    $('#ui-datepicker-div').css('clip', 'auto');
    return [true, '', ''];

Java: How to check if object is null?

if (yourObject instanceof yourClassName) will evaluate to false if yourObject is null.

Push JSON Objects to array in localStorage

Putting a whole array into one localStorage entry is very inefficient: the whole thing needs to be re-encoded every time you add something to the array or change one entry.

An alternative is to use which stores any JS object, however deeply nested, using a separate localStorage entry for each terminal value. Arrays are restored much more faithfully, including non-numeric properties and various types of sparseness, object prototypes/constructors are restored in standard cases and the API is ludicrously simple:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);

store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
store.somethingfancy.went[1].mow.write(1, 'lawn');

BTW, I wrote it.

Validate fields after user has left a field

To pick up further on the given answers, you can simplify input tagging by using CSS3 pseudo-classes and only marking visited fields with a class to delay displaying validation errors until the user lost focus on the field:

(Example requires jQuery)


module = angular.module('app.directives', []);
module.directive('lateValidateForm', function () {
    return {
        restrict: 'AC',
        link: function (scope, element, attrs) {
            $inputs = element.find('input, select, textarea');

            $inputs.on('blur', function () {

            element.on('submit', function () {


select.has-visited:not(:focus):required:invalid {
  color: #b94a48;
  border-color: #ee5f5b;


<form late-validate-form name="userForm">
  <input type="email" name="email" required />

Function Pointers in Java

Java8 has introduced lambdas and method references. So if your function matches a functional interface (you can create your own) you can use a method reference in this case.

Java provides a set of common functional interfaces. whereas you could do the following:

public class Test {
   public void test1(Integer i) {}
   public void test2(Integer i) {}
   public void consumer(Consumer<Integer> a) {
   public void provideConsumer() {
     consumer(this::test1);   // method reference
     consumer(x -> test2(x)); // lambda

SQL: Insert all records from one table to another table without specific the columns

You need to have at least the same number of columns and each column has to be defined in exactly the same way, i.e. a varchar column can't be inserted into an int column.

For bulk transfer, check the documentation for the SQL implementation you're using. There are often tools available to bulk transfer data from one table to another. For SqlServer 2005, for example, you could use the SQL Server Import and Export Wizard. Right-click on the database you're trying to move data around in and click Export to access it.

Gradient text color

body{ background:#3F5261; text-align:center; font-family:Arial; } _x000D_
h1 {_x000D_
  background: -webkit-linear-gradient(top, gold, white);_x000D_
  background: linear-gradient(top, gold, white);_x000D_
  -webkit-background-clip: text;_x000D_
  -webkit-text-fill-color: transparent;_x000D_
div{ display:inline-block; position:relative; }_x000D_
div::before{ _x000D_
   content:attr(data-title); _x000D_
   top:0; left:0;_x000D_
<div data-title='SOME TITLE'>_x000D_
  <h1>SOME TITLE</h1>_x000D_

Calculating and printing the nth prime number

I just added the missing lines in your own thought process.

static int nthPrimeFinder(int n) {

        int counter = 1; // For 1 and 2. assuming n is not 1 or 2.
        int i = 2;
        int x = 2;
        int tempLength = n;

        while (counter <= n) {
            for (; i <= tempLength; i++) {
                for (x = 2; x < i; x++) {
                    if (i % x == 0) {
                if (x == i && counter < n) {
                    //System.out.printf("\n%d is prime", x);
                    if (counter == n) {
                        System.out.printf("\n%d is prime", x);
                        return counter;
            tempLength = tempLength+n;
        return 0;

displaying a string on the textview when clicking a button in android

You can do like this:

 String hello;
public void onCreate(Bundle savedInstanceState) {

    mybtn = (Button)findViewById(;
    txtwidth = (TextView)findViewById(;
    hello="This is my first project";

public void onClick(View view){

Check your textview names. Both are same . You must use different object names and you have mentioned that textview object which is not available in your xml layout file. Hope this will help you.

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

As of today (10/30/2018), we noticed our builds breaking in Jenkins with this error.

The error is a bit misleading and required looking at the output of the dump in target/surefire-reports/ to see the following error message:

Error: Could not find or load main class org.apache.maven.surefire.booter.ForkedBooter

That lead me to the following SO post which mentions a possible bug in OpenJDK 181: Maven surefire could not find ForkedBooter class

Either of the fixes in that post solve my issue. To be specific, I used either one of these:

  1. Switching from building in the docker container maven:3.5.4-jdk-8 to maven:3.5.4-jdk-8-alpine
  2. Overriding Spring Boot's class loader detailed here:

What is the list of valid @SuppressWarnings warning names in Java?

All values are permitted (unrecognized ones are ignored). The list of recognized ones is compiler specific.

In The Java Tutorials unchecked and deprecation are listed as the two warnings required by The Java Language Specification, therefore, they should be valid with all compilers:

Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked.

The specific sections inside The Java Language Specification where they are defined is not consistent across versions. In the Java SE 8 Specification unchecked and deprecation are listed as compiler warnings in sections @SuppressWarnings and @Deprecated, respectively.

For Sun's compiler, running javac -X gives a list of all values recognized by that version. For 1.5.0_17, the list appears to be:

  • all
  • deprecation
  • unchecked
  • fallthrough
  • path
  • serial
  • finally

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

HTTP Headers for File Downloads

You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:


$filename = $_GET['file'];

// required for IE, otherwise Content-disposition is ignored
  ini_set('zlib.output_compression', 'Off');

// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));

if( $filename == "" ) 
  echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
} elseif ( ! file_exists( $filename ) ) 
  echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
switch( $file_extension )
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/"; break;
  case "ppt": $ctype="application/"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/octet-stream";
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));

Get user info via Google API

There are 3 steps that needs to be run.

  1. Register your app's client id from Google API console
  2. Ask your end user to give consent using this api
  3. Use google's oauth2 api as described at using the token obtained in step 2. (Though still I could not find how to fill "fields" parameter properly).

It is very interesting that this simplest usage is not clearly described anywhere. And i believe there is a danger, you should pay attention to the verified_emailparameter coming in the response. Because if I am not wrong it may yield fake emails to register your application. (This is just my interpretation, has a fair chance that I may be wrong!)

I find facebook's OAuth mechanics much much clearly described.

Get class labels from Keras functional model

UPDATE: This is no longer valid for newer Keras versions. Please use argmax() as in the answer from Emilia Apostolova.

The functional API models have just the predict() function which for classification would return the class probabilities. You can then select the most probable classes using the probas_to_classes() utility function. Example:

y_proba = model.predict(x)
y_classes = keras.np_utils.probas_to_classes(y_proba)

This is equivalent to model.predict_classes(x) on the Sequential model.

The reason for this is that the functional API support more general class of tasks where predict_classes() would not make sense.

More info:

Visual Studio move project to a different folder

No sure why all answers have overlooked at the most simple solution. Just run the "Command Prompt app" (in the windows bar search for CMD and it will appear automatically)

then just type the following command (change the path where relevant for your own case:)

robocopy /E C:\Users\Peter\source\repos D:\Peter\repos

What robocopy does is to "copies file data from one location to another." and the "secret source" is the / E that means "Copies subdirectories. This option automatically includes empty directories."

Enjoy!!! :-)

CMD Promt

The system cannot find the file specified. in Visual Studio

I had a same problem and this fixed it:

You should add:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib\x64 for 64 bit system

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib for 32 bit system

in Property Manager>Linker>General>Additional Library Directories

find the array index of an object with a specific key value in underscore

Keepin' it simple:

// Find the index of the first element in array
// meeting specified condition.
var findIndex = function(arr, cond) {
  var i, x;
  for (i in arr) {
    x = arr[i];
    if (cond(x)) return parseInt(i);

var idIsTwo = function(x) { return == 2 }
var tv = [ {id: 1}, {id: 2} ]
var i = findIndex(tv, idIsTwo) // 1

Or, for non-haters, the CoffeeScript variant:

findIndex = (arr, cond) ->
  for i, x of arr
    return parseInt(i) if cond(x)

Naming threads and thread-pools of ExecutorService

The BasicThreadFactory from apache commons-lang is also useful to provide the naming behavior. Instead of writing an anonymous inner class, you can use the Builder to name the threads as you want. Here's the example from the javadocs:

 // Create a factory that produces daemon threads with a naming pattern and
 // a priority
 BasicThreadFactory factory = new BasicThreadFactory.Builder()
 // Create an executor service for single-threaded execution
 ExecutorService exec = Executors.newSingleThreadExecutor(factory);

Change the Blank Cells to "NA"

As of (dplyr 1.0.0) we can use across()

For all columns:

dat <- dat %>%
   mutate(across(everything(), ~ifelse(.=="", NA, as.character(.))))

For individual columns:

dat <- dat %>%
   mutate(across(c("Age","Gender"), ~ifelse(.=="", NA, as.character(.))))

As of (dplyr 0.8.0 above) the way this should be written has changed. Before it was, funs() in .funs (funs(name = f(.)). Instead of funs, now we use list (list(name = ~f(.)))

Note that there is also a much simpler way to list the column names ! (both the name of the column and column index work)

dat <- dat %>%
mutate_at(.vars = c("Age","Gender"),
    .funs = list(~ifelse(.=="", NA, as.character(.))))

Original Answer:

You can also use mutate_at in dplyr

dat <- dat %>%
        .funs = funs(ifelse(.=="", NA, as.character(.))))

Select individual columns to change:

dat <- dat %>%
mutate_at(vars(colnames(.)[names(.) %in% c("Age","Gender")]),
        .funs = funs(ifelse(.=="", NA, as.character(.))))

How to call a function from another controller in angularjs?

If you would like to execute the parent controller's parentmethod function inside a child controller, call it:


You can try it over here