Programs & Examples On #Youtube channels

How to update PATH variable permanently from Windows command line?

This Python-script[*] does exactly that:

Show/Modify/Append registry env-vars (ie `PATH`) and notify Windows-applications to pickup changes.

First attempts to show/modify HKEY_LOCAL_MACHINE (all users), and 
if not accessible due to admin-rights missing, fails-back 
Write and Delete operations do not proceed to user-tree if all-users succeed.

    {prog}                  : Print all env-vars. 
    {prog}  VARNAME         : Print value for VARNAME. 
    {prog}  VARNAME   VALUE : Set VALUE for VARNAME. 
    {prog}  +VARNAME  VALUE : Append VALUE in VARNAME delimeted with ';' (i.e. used for `PATH`). 
    {prog}  -VARNAME        : Delete env-var value. 

Note that the current command-window will not be affected, 
changes would apply only for new command-windows.

import winreg
import os, sys, win32gui, win32con

def reg_key(tree, path, varname):
    return '%s\%s:%s' % (tree, path, varname) 

def reg_entry(tree, path, varname, value):
    return '%s=%s' % (reg_key(tree, path, varname), value)

def query_value(key, varname):
    value, type_id = winreg.QueryValueEx(key, varname)
    return value

def yield_all_entries(tree, path, key):
    i = 0
    while True:
            n,v,t = winreg.EnumValue(key, i)
            yield reg_entry(tree, path, n, v)
            i += 1
        except OSError:
            break ## Expected, this is how iteration ends.

def notify_windows(action, tree, path, varname, value):
    win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
    print("---%s %s" % (action, reg_entry(tree, path, varname, value)), file=sys.stderr)

def manage_registry_env_vars(varname=None, value=None):
    reg_keys = [
        ('HKEY_LOCAL_MACHINE', r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'),
        ('HKEY_CURRENT_USER', r'Environment'),
    for (tree_name, path) in reg_keys:
        tree = eval('winreg.%s'%tree_name)
            with winreg.ConnectRegistry(None, tree) as reg:
                with winreg.OpenKey(reg, path, 0, winreg.KEY_ALL_ACCESS) as key:
                    if not varname:
                        for regent in yield_all_entries(tree_name, path, key):
                        if not value:
                            if varname.startswith('-'):
                                varname = varname[1:]
                                value = query_value(key, varname)
                                winreg.DeleteValue(key, varname)
                                notify_windows("Deleted", tree_name, path, varname, value)
                                break  ## Don't propagate into user-tree.
                                value = query_value(key, varname)
                                print(reg_entry(tree_name, path, varname, value))
                            if varname.startswith('+'):
                                varname = varname[1:]
                                value = query_value(key, varname) + ';' + value
                            winreg.SetValueEx(key, varname, 0, winreg.REG_EXPAND_SZ, value)
                            notify_windows("Updated", tree_name, path, varname, value)
                            break  ## Don't propagate into user-tree.
        except PermissionError as ex:
            print("!!!Cannot access %s due to: %s" % 
                    (reg_key(tree_name, path, varname), ex), file=sys.stderr)
        except FileNotFoundError as ex:
            print("!!!Cannot find %s due to: %s" % 
                    (reg_key(tree_name, path, varname), ex), file=sys.stderr)

if __name__=='__main__':
    args = sys.argv
    argc = len(args)
    if argc > 3:
        print(__doc__.format(prog=args[0]), file=sys.stderr)


Below are some usage examples, assuming it has been saved in a file called somewhere in your current path. Note that in these examples i didn't have admin-rights, so the changes affected only my local user's registry tree:

> REM ## Print all env-vars
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied

> REM ## Query env-var:
> PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
!!!Cannot find HKEY_CURRENT_USER\Environment:PATH due to: [WinError 2] The system cannot find the file specified

> REM ## Set env-var:
> PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo

> REM ## Append env-var:
> +PATH D:\Bar
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo;D:\Bar

> REM ## Delete env-var:
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Deleted HKEY_CURRENT_USER\Environment:PATH

[*] Adapted from:

Oracle select most recent date record

i think i'd try with MAX something like this:

SELECT staff_id, max( date ) from owner.table group by staff_id

then link in your other columns:

select staff_id, site_id, pay_level, latest
from owner.table, 
(   SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

I had given an answer in Super User site for the thread "Open a network drive with different user" (

I want to use a router's USB drive as a network storage for different users, as this thread I met the error message

"Multiple Connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again."

Beside the method using "NET USE" command, I found another way from the webpage

It is better to solve the Windows connection limitation by editing the hosts file which is under the directory "C:\Windows\System32\Drivers\etc".

For example, my router IP address is and its USB drive has three share folders as \user1, \user2 and \user3 which separated for three users, then we can add the following three lines in hosts file, server1 server2 server3

in this example we map the server1 to user #1, server2 to user #2 and server3 to user #3.

After reboot the PC, we can connect the folder \user1 for user #1, \user2 for user #2 and \user3 for user #3 simultaneously in Windows File Explorer, that is

if we type the router name as \\server1 in folder indication field of Explorer, it will show all shared folders of router's USB drive in Explorer right pane and sever1 under "Network" item in left pane of Explorer, then the user #1 may access the share folder \user1.

At this time if we type \\server2 or \\server3 in the directory indication field of Explorer, then we may connect the router's USB drive as server2 or server3 and access the share folder \user2 or \user3 for user #2 or user #3 and keep the "server1" connection simultaneously.

Using this method we may also use the "NET USE" command to do these actions.

Throwing multiple exceptions in a method of an interface in java

I think you are asking for something like the code below:

public interface A
    void foo() 
        throws AException;

public class B
    implements A
    public void foo()
        throws AException,

This will not work unless BException is a subclass of AException. When you override a method you must conform to the signature that the parent provides, and exceptions are part of the signature.

The solution is to declare the the interface also throws a BException.

The reason for this is you do not want code like:

public class Main
    public static void main(final String[] argv)
        A a;

        a = new B();

        catch(final AException ex)
        // compiler will not let you write a catch BException if the A interface
        // doesn't say that it is thrown.

What would happen if B::foo threw a BException? The program would have to exit as there could be no catch for it. To avoid situations like this child classes cannot alter the types of exceptions thrown (except that they can remove exceptions from the list).

How To fix white screen on app Start up?

This solved the problem :

Edit your styles.xml file :

Paste the code below :


    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowIsTranslucent">true</item>


And don't forget to make the modifications in the AndroidManifest.xml file. (theme's name)

Be careful about the declaration order of the activities in this file.

Binary numbers in Python

Binary, decimal, hexadecimal... the base only matters when reading or outputting numbers, adding binary numbers is just the same as adding decimal number : it is just a matter of representation.

UNIX export command

export is a built-in command of the bash shell and other Bourne shell variants. It is used to mark a shell variable for export to child processes.

Generating UNIQUE Random Numbers within a range

If you need 5 random numbers between 1 and 15, you should do:

var_dump(getRandomNumbers(1, 15, 5));

function getRandomNumbers($min, $max, $count)
    if ($count > (($max - $min)+1))
        return false;
    $values = range($min, $max);
    return array_slice($values,0, $count);

It will return false if you specify a count value larger then the possible range of numbers.

Error: Failed to lookup view in Express

This error really just has to do with the file Path,thats all you have to check,for me my parent folder was "Layouts" but my actual file was layout.html,my path had layouts on both,once i corrected that error was gone.

How to terminate a Python script

Another way is:

raise SystemExit

iPhone - Get Position of UIView within entire UIWindow

Here is a combination of the answer by @Mohsenasm and a comment from @Ghigo adopted to Swift

extension UIView {
    var globalFrame: CGRect? {
        let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
        return self.superview?.convert(self.frame, to: rootView)

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

Open your mysql file any edit tool


/*!40101 SET NAMES utf8mb4 */;


/*!40101 SET NAMES utf8 */;

Save and upload ur mysql.

URL encode sees “&” (ampersand) as “&amp;” HTML entity

If you did literally this:


Then the result is %26, you can test it here. Make sure the string you are encoding is just & and not &amp; to begin with...otherwise it is encoding correctly, which is likely the case. If you need a different result for some reason, you can do a .replace(/&amp;/g,'&') before the encoding.

CreateProcess: No such file or directory

(Referring to original problem)
Today's version of mingw (see post date)
All I had to do was to set the path in same shell I ran gcc.
Took me an hour to remember how to set DOS variables...

A:> set PATH=C:\MinGW\bin\;
C:\Program Files\ImageMagick-6.8.0-Q16\;
C:\Program Files\QuickTime\QTSystem\
A:> gcc hi.c

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)


@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

Escape quote in web.config connection string

Use &quot; That should work.

How to fix: /usr/lib/ version `GLIBCXX_3.4.15' not found

this problem can be solved by installing the latest libstdc++.

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg

How can one pull the (private) data of one's own Android app?

This answer is based on my experience with other answers, and comments in the answers. My hope is I can help someone in a similar situation.

I am doing this on OSX via terminal.

Previously Vinicius Avellar's answer worked great for me. I was only ever most of the time needing the database from the device from a debug application.

Today I had a use case where I needed multiple private files. I ended up with two solutions that worked good for this case.

  1. Use the accepted answer along with Someone Somewhere's OSX specific comments. Create a backup and use the 3rd party solution, to unpack into a tar. I'll write more about my experience with this solution at the bottom of this answer. Scroll down if this is what you are looking for.

  2. A faster solution which I settled with. I created a script for pulling multiple files similar to Tamas' answer. I am able to do it this way because my app is a debug app and I have access to run-as on my device. If you don't have access to run-as this method won't work for you on OSX.

Here is my script for pulling multiple private files that I'll share with you, the reader, who is also investigating this awesome question ;) :

# Strict mode:
set -euo pipefail

# Usage: script -f fileToPull -p packageName

# This script is for pulling private files from an Android device
# using run-as. Note: not all devices have run-as access, and
# application must be a debug version for run-as to work.
# If run-as is deactivated on your device use one of the
# alternative methods here:
# If you have encrypted backup files use:
# From comments in the accepted answer in the above SO question
# If your files aren't encrypted use the accepted answer 
# ( see comments and other answers for OSX compatibility )
# This script is open to expansions to allow selecting 
# device used. Currently first selected device from
# adb shell will be used.

#Check we have one connected device
adb devices -l | grep -e 'device\b' > /dev/null

if [ $? -gt 0 ]; then
    echo "No device connected to adb."
    exit 1

# Set filename or directory to pull from device
# Set package name we will run as
while getopts f:p: opt; do
    case $opt in

# Block file arg from being blank
if [ -z "$fileToPull" ]; then
    echo "Please specify file or folder to pull with -f argument"
    exit 1

# Block package name arg from being blank
if [ -z "$packageName" ]; then
    echo "Please specify package name to run as when pulling file"
    exit 1

# Check package exists
adb shell pm list packages | grep "$packageName" > /dev/null
if [ $? -gt 0 ]; then
    echo "Package name $packageName does not exist on device"
    exit 1

# Check file exists and has permission with run-as
fileCheck=`adb shell "run-as $packageName ls $fileToPull"`
if [[ $fileCheck =~ "Permission denied" ]] || [[ $fileCheck =~ "No such file or directory" ]]; then
    echo "Error: $fileCheck"
    echo "With file -> $fileToPull"
    exit 1

# Function to pull private file
# param 1 = package name
# param 2 = file to pull
# param 3 = output file
function pull_private_file () {

    mkdir -p `dirname $3`

    echo -e "\033[0;35m***" >&2
    echo -e "\033[0;36m Coping file $2 -> $3" >&2
    echo -e "\033[0;35m***\033[0m" >&2

    adb shell "run-as $1 cat $2" > $3

# Check if a file is a directory
# param 1 = directory to check
function is_file_dir() {

    adb shell "if [ -d \"$1\" ]; then echo TRUE; fi"

# Check if a file is a symbolic link
# param 1 = directory to check
function is_file_symlink() {

    adb shell "if [ -L \"$1\" ]; then echo TRUE; fi"

# recursively pull files from device connected to adb
# param 1 = package name
# param 2 = file to pull
# param 3 = output file
function recurse_pull_private_files() {

    is_dir=`is_file_dir "$2"`
    is_symlink=`is_file_symlink "$2"`

    if [ -n "$is_dir" ]; then

        files=`adb shell "run-as $1 ls \"$2\""`

        # Handle the case where directory is a symbolic link
        if [ -n "$is_symlink" ]; then
            correctPath=`adb shell "run-as $1 ls -l \"$2\"" | sed 's/.*-> //' | tr -d '\r'`
            files=`adb shell "run-as $1 ls \"$correctPath\""`

        for i in $files; do

            # Android adds nasty carriage return that screws with bash vars
            # This removes it. Otherwise weird behavior happens
            fileName=`echo "$i" | tr -d '\r'` 

            recurse_pull_private_files "$1" "$nextFile" "$nextOutput"

        pull_private_file "$1" "$2" "$3"

recurse_pull_private_files "$packageName" "$fileToPull" "`basename "$fileToPull"`"


Back to method 1, decrypting a backup using Android Backup Extractor

Here are the steps I took on my Mac, and issues I came across:

First I queued up a backup ( and set a password to encrypt my backup, my device required it ):

adb backup -f myAndroidBackup.ab  com.corp.appName

Second I downloaded just abe.jar from here:

Next I ran:

java -jar ./abe.jar unpack myAndroidBackup.ab myAndroidBackup.tar

At this point I got an error message. Because my archive is encrypted, java gave me an error that I needed to install some security policy libraries.

  • So I went to and downloaded the security policy jars I needed. Now in my case the install instructions told me the wrong location to put the jar files. It says that the proper location is <java-home>/lib/security. I put them there first and still got the error message. So I investigated and on my Mac with Java 1.8 the correct place to put them was: <java-home>/jre/lib/security. I made sure to backup the original policy jars, and put them there. Vola I was able to enter a password with abe.jar and decrypt to a tar file.

Lastly I just ran ( after running previous command again )

tar xvf myAndroidBackup.tar

Now it is important to note that if you can just run-as and cat, it is much much faster. One, you only get the files you want and not the entire application. Two, the more files ( + encryption for me ) makes it slower to transfer. So knowing to do this way is important if you don't have run-as on OSX, but the script should be first goto for a debug application.

Mind you I just wrote it today and tested it a few times, so please notify me of any bugs!

How to return a string from a C++ function?

You never give any value to your strings in main so they are empty, and thus obviously the function returns an empty string.


string str1, str2, str3;


string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";

Also, you have several problems in your replaceSubstring function:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find returns a std::string::size_type (aka. size_t) not an int. Two differences: size_t is unsigned, and it's not necessarily the same size as an int depending on your platform (eg. on 64 bits Linux or Windows size_t is unsigned 64 bits while int is signed 32 bits).
  • What happens if s2 is not part of s1? I'll leave it up to you to find how to fix that. Hint: std::string::npos ;)

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_

how to parse json using groovy

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link =

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
String link = userJson[id].link

How to subscribe to an event on a service in Angular2?

Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer:

Also, the Angular docs now have a cookbook example that uses a Subject.

Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.


import {EventEmitter} from 'angular2/core';
export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emitNavChangeEvent(number) {
  getNavChangeEmitter() {
    return this.navchange;


import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
export class ObservingComponent {
  item: number = 0;
  subscription: any;
  constructor(private navService:NavService) {}
  ngOnInit() {
    this.subscription = this.navService.getNavChangeEmitter()
      .subscribe(item => this.selectedNavItem(item));
  selectedNavItem(item: number) {
    this.item = item;
  ngOnDestroy() {

  selector: 'my-nav',
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
export class Navigation {
  item = 1;
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);


How to echo shell commands as they are executed

Another option is to put "-x" at the top of your script instead of on the command line:

$ cat ./server
#!/bin/bash -x
ssh user@server

$ ./server
+ ssh user@server
user@server's password: ^C

Alter column in SQL Server

Try this one.

ALTER TABLE tb_TableName

ALTER TABLE tb_TableName

Rails filtering array of objects by attribute value

have you tried eager loading?

@attachments = Job.includes(:attachments).find(1).attachments

How can I populate a select dropdown list from a JSON feed with AngularJS?

The proper way to do it is using the ng-options directive. The HTML would look like this.

<select ng-model="selectedTestAccount" 
        ng-options="item.Id as item.Name for item in testAccounts">
    <option value="">Select Account</option>


angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

            method: 'GET',
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.testAccounts = result;

You'll also need to ensure angular is run on your html and that your module is loaded.

<html ng-app="test">
    <body ng-controller="DemoCtrl">

unable to remove file that really exists - fatal: pathspec ... did not match any files

I know this is not the OP's problem, but I ran into the same error with an entirely different basis, so I just wanted to drop it here in case anyone else has the same. This is Windows-specific, and I assume does not affect Linux users.

I had a LibreOffice doc file, call it final report.odt. I later changed its case to Final Report.odt. In Windows, this doesn't even count as a rename. final report.odt, Final Report.odt, FiNaL RePoRt.oDt are all the same. In Linux, these are all distinct.

When I eventually went to git rm "Final Report.odt" and got the "pathspec did not match any files" error. Only when I use the original casing at the time the file was added -- git rm "final report.odt" -- did it work.

Lesson learned: to change the case I should have instead done:

git mv "final report.odt" temp.odt
git mv temp.odt "Final Report.odt"

Again, that wasn't the problem for the OP here; and wouldn't affect a Linux user, as his posts shows he clearly is. I'm just including it for others who may have this problem in Windows git and stumble onto this question.

Error during SSL Handshake with remote server

I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.

So, I had to generate the SSL certificate again and it started working...

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt

What does "Use of unassigned local variable" mean?

Give them a default value:

double lateFee=0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;

Basically, all possible paths don't initialize these variables.

CSS getting text in one line rather than two

The best way to use is white-space: nowrap; This will align the text to one line.

Combining paste() and expression() functions in plot labels

Use substitute instead.

labNames <- c('xLab','yLab')
     xlab=substitute(paste(nn, x^2), list(nn=labNames[1])),
     ylab=substitute(paste(nn, y^2), list(nn=labNames[2])))

Angular JS break ForEach

As the other answers state, Angular doesn't provide this functionality. jQuery does however, and if you have loaded jQuery as well as Angular, you can use

jQuery.each ( array, function ( index, value) {
    if(condition) return false; // this will cause a break in the iteration


How to get file name from file path in android

The easiest solution is to use Uri.getLastPathSegment():

String filename = uri.getLastPathSegment();

ant warning: "'includeantruntime' was not set"

Use <property name="build.sysclasspath" value="last"/> in your build.xml file

For more details search includeAntRuntime in Ant javac

Other possible values could be found here

Php - testing if a radio button is selected and get the value

my form:

<form method="post" action="radio.php">
   select your gender: 
    <input type="radio" name="radioGender" value="female">
    <input type="radio" name="radioGender" value="male">
    <input type="submit" name="btnSubmit" value="submit">

my php:

      if (isset($_POST["btnSubmit"])) {
        if (isset($_POST["radioGender"])) {
        $answer = $_POST['radioGender'];
           if ($answer == "female") {
               echo "female";
           } else {
               echo "male";
            echo "please select your gender";

how does work?

// We can apply `slice` from  `Array.prototype`:[]); //-> []

// Since `slice` is available on an array's prototype chain,
'slice' in []; //-> true
[].slice === Array.prototype.slice; //-> true

// … we can just invoke it directly:
[].slice(); //-> []

// `arguments` has no `slice` method
'slice' in arguments; //-> false

// … but we can apply it the same way:; //-> […]

// In fact, though `slice` belongs to `Array.prototype`,
// it can operate on any array-like object:{0: 1, length: 1}); //-> [1]

Scatter plot and Color mapping in Python

Here is an example

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)

plt.scatter(x, y, c=t)

Here you are setting the color based on the index, t, which is just an array of [1, 2, ..., 100]. enter image description here

Perhaps an easier-to-understand example is the slightly simpler

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
plt.scatter(x, y, c=t)

enter image description here

Note that the array you pass as c doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum/maximum values in c correspond to the bottom/top of the colormap.


You can change the colormap by adding

import as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)

Importing is optional as you can call colormaps as cmap="cmap_name" just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r. So either

plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")

will work. Examples are "jet_r" or cm.plasma_r. Here's an example with the new 1.5 colormap viridis:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')

enter image description here


You can add a colorbar by using

plt.scatter(x, y, c=t, cmap='viridis')

enter image description here

Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots() or ax = fig.add_subplot(111)), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

The first part:


Sends you to the bottom row of column A, which you knew already.

The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:


The program will select E4, the rightmost cell with text in it.

In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

how to check the dtype of a column in python pandas

If you want to mark the type of a dataframe column as a string, you can do:


An example:

In [8]: df = pd.DataFrame([[1,'a',1.2],[2,'b',2.3]])
In [9]: df[0].dtype.kind, df[1].dtype.kind, df[2].dtype.kind
Out[9]: ('i', 'O', 'f')

The answer for your code:

for y in agg.columns:
    if(agg[y].dtype.kind == 'f' or agg[y].dtype.kind == 'i'):


Binding ComboBox SelectedItem using MVVM

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

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

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;

So then you just use this method to get number values


How to repair a serialized string which has been corrupted by an incorrect byte count length?

The corruption in this question is isolated to a single substring at the end of the serialized string with was probably manually replaced by someone who lazily wanted to update the image filename. This fact will be apparent in my demonstration link below using the OP's posted data -- in short, C:fakepath100.jpg does not have a length of 19, it should be 17.

Since the serialized string corruption is limited to an incorrect byte/character count number, the following will do a fine job of updating the corrupted string with the correct byte count value.

The following regex based replacement will only be effective in remedying byte counts, nothing more.

It looks like many of the earlier posts are just copy-pasting a regex pattern from someone else. There is no reason to capture the potentially corrupted byte count number if it isn't going to be used in the replacement. Also, adding the s pattern modifier is a reasonable inclusion in case a string value contains newlines/line returns.

*For those that are not aware of the treatment of multibyte characters with serializing, you must not use mb_strlen() in the custom callback because it is the byte count that is stored not the character count, see my output...

Code: (Demo with OP's data) (Demo with arbitrary sample data) (Demo with condition replacing)

$corrupted = <<<STRING

$repaired = preg_replace_callback(
        //  ^^^- matched/consumed but not captured because not used in replacement
        function ($m) {
            return "s:" . strlen($m[1]) . ":\"{$m[1]}\";";

echo $corrupted , "\n" , $repaired;
echo "\n---\n";


array (
  0 => 'three',
  1 => 'five',
  2 => 'newline1
  3 => 'garçon',

One leg down the rabbit hole... The above works fine even if double quotes occur in a string value, but if a string value contains "; or some other monkeywrenching sbustring, you'll need to go a little further and implement "lookarounds". My new pattern

checks that the leading s is:

  • the start of the entire input string or
  • preceded by ;

and checks that the "; is:

  • at the end of the entire input string or
  • followed by } or
  • followed by a string or integer declaration s: or i:

I haven't test each and every possibility; in fact, I am relatively unfamiliar with all of the possibilities in a serialized string because I never elect to work with serialized data -- always json in modern applications. If there are additional possible leading or trailing characters, leave a comment and I'll extend the lookarounds.

Extended snippet: (Demo)

$corrupted_byte_counts = <<<STRING
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}

$repaired = preg_replace_callback(
        //^^^^^^^^--------------^^^^^^^^^^^^^-- some additional validation
        function ($m) {
            return 's:' . strlen($m[1]) . ":\"{$m[1]}\";";

echo "corrupted serialized array:\n$corrupted_byte_counts";
echo "\n---\n";
echo "repaired serialized array:\n$repaired";
echo "\n---\n";


corrupted serialized array:
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}
repaired serialized array:
newline2";i:3;s:7:"garçon";i:4;s:24:"double " quote \"escaped";i:5;s:7:"a,comma";i:6;s:7:"a:colon";i:7;s:13:"single 'quote";i:8;s:10:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:39:"monkey";wrenching doublequote-semicolon";s:2:"s:";s:10:"val s: val";}
    [0] => three
    [1] => five
    [2] => newline1
    [3] => garçon
    [4] => double " quote \"escaped
    [5] => a,comma
    [6] => a:colon
    [7] => single 'quote
    [8] => semi;colon
    [assoc] => yes
    [9] => monkey";wrenching doublequote-semicolon
    [s:] => val s: val

Android device chooser - My device seems offline

I have HTC wildfire and disabling and enabling the debugging worked fine for the "offline" problem. The error does not show up.

However I ran into a new problem when trying to import a python file with sl3a : "no moduled named android" explained here. That being said, I still cannot run this file located somewhere on the SD Card/python folder. I can connect with androidscreencast.jnlp and it works fine :)

Partition Function COUNT() OVER possible using DISTINCT

There is a very simple solution using dense_rank()

dense_rank() over (partition by [Mth] order by [UserAccountKey]) 
+ dense_rank() over (partition by [Mth] order by [UserAccountKey] desc) 
- 1

This will give you exactly what you were asking for: The number of distinct UserAccountKeys within each month.

How to load data to hive from HDFS without removing the source file?

An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.

You can use ALTER TABLE command with 'LOCATION' option. Here is below required command

ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'

The only condition here is, the location should be a directory instead of file.

Hope this will solve the problem.

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

merge into x as target using y as Source on target.ID = Source.ID
when not matched by target then insert
when matched then update
when not matched by source and target.ID is not null then
update whatevercolumn = 'isdeleted' ;

The system cannot find the file specified. in Visual Studio

The code should be :

#include <iostream>
using namespace std;

int main() {
    cout << "Hello World";
    return 0;

Or maybe :

#include <iostream>

int main() {
    std::cout << "Hello World";
    return 0;

Just a quick note: I have deleted the system command, because I heard it's not a good practice to use it. (but of course, you can add it for this kind of program)

Using pip behind a proxy with CNTLM

I had the same issue : behind a corporate proxy with auth at work, I couldn't have pip work, as well as Sublime Text 2 (well, it worked with custom setup of my proxy settings). For pip (and I'll try that on git), I solved it installing cntlm proxy. It was very simple to configure :

  1. Edit cntlm.ini
  2. Edit "Username", "Domain", "Password" fields
  3. Add a "Proxy" line, with your proxy settings : server:port
  4. Make sure the line "NoProxy" integrates "localhost" (like that by default)
  5. Note the default port : 3128
  6. Save and that's it.

To test that works, just launch a new command line tool, and try :

pip install django --proxy=localhost:3128

That worked for me. Hope this will help you.

Convert objective-c typedef to its string equivalent

Combining @AdamRosenfield answer, @Christoph comment and another trick to handle plain C enums I suggest:

// In a header file
typedef enum {
  JSON = 0,         // explicitly indicate starting index

  FormatTypeCount,  // keep track of the enum size automatically
} FormatType;
extern NSString *const FormatTypeName[FormatTypeCount];

// In a source file
NSString *const FormatTypeName[FormatTypeCount] = {
  [JSON] = @"JSON",
  [XML] = @"XML",
  [Atom] = @"Atom",
  [RSS] = @"RSS",

// Usage
NSLog(@"%@", FormatTypeName[XML]);

In the worst case - like if you change the enum but forget to change the names array - it will return nil for this key.

How do I empty an input value with jQuery?

A better way is:


Load image from resources area of project in C#

Way easier than most all of the proposed answers

tslMode.Image = global::ProjectName.Properties.Resources.ImageName;

Groovy String to Date

Try this:

def date = Date.parse("E MMM dd H:m:s z yyyy", dateStr)

Here are the patterns to format the dates

How to set background color of an Activity to white programmatically?

In your onCreate() method:


Also you need to add to values folder a new XML file called color.xml and Assign there a new color property:


<?xml version="1.0" encoding="utf-8"?>
<color name="main_activity_background_color">#000000</color>

Note that you can name the color.xml any name you want but you refer to it by code as R.color.yourId.


Because getResources().getColor() is deprecated, use getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.main_activity_background_color)); instead.

ggplot2: sorting a plot

You need to make the x-factor into an ordered factor with the ordering you want, e.g

x <- data.frame("variable"=letters[1:5], "value"=rnorm(5)) ## example data
x <- x[with(x,order(-value)), ] ## Sorting
x$variable <- ordered(x$variable, levels=levels(x$variable)[unclass(x$variable)])

ggplot(x, aes(x=variable,y=value)) + geom_bar() +
   scale_y_continuous("",formatter="percent") + coord_flip()

I don't know any better way to do the ordering operation. What I have there will only work if there are no duplicate levels for x$variable.

How do I customize Facebook's sharer.php


This answer is outdated.

Like @jack-marchetti stated in his comment, and @devantoine with the link:

Facebook has changed how the sharer.php works, as Ibrahim Faour replies to the bug filed with Facebook.

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post, from the url OG meta tags.

Try this (via Javascript in this example):

'[title]='+encodeURIComponent('this is a title') + '&p[summary]=' + encodeURIComponent('description here') + '&p[url]=' + encodeURIComponent('') + '&p[images][0]=' + encodeURIComponent('')

I tried this quickly without the image part and the sharer.php window appears pre-populated, so it looks like a solution.

I found this via this SO article:

Want custom title / image / description in facebook share link from a flash app

and this link contained in an answer from Lelis718:

so all credit to Lelis718 for this answer.

[EDIT 3rd May 2013] - seems like the original URL i had here no longer works for me without also including "s=100" in the query string - no idea why but have updated accordingly

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:


Or a negative look-behind assertion:


Or just plain old character sets and alternations:


No visible cause for "Unexpected token ILLEGAL"

I am going to add one more answer to the pile. THis problem could happen also because of encoding. You want utf8 encoding to be on safe side. Some editors by default use utf16 which can cause issue. One quick way to test this, is, for example in VS code, simply recreate the same content but use the local editor of vscode to create the file. Hope this helps some.

Getting activity from context in android

This method should be helpful..!

public Activity getActivityByContext(Context context){

if(context == null){
    return null;

else if((context instanceof ContextWrapper) && (context instanceof Activity)){
        return (Activity) context;

else if(context instanceof ContextWrapper){
        return getActivity(((ContextWrapper) context).getBaseContext());

return null;


I hope this helps.. Merry coding!

Integer.valueOf() vs. Integer.parseInt()

First Question: Difference between parseInt and valueOf in java?

Second Question:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

Third Question:

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();

SVN- How to commit multiple files in a single shot

I've had no issues committing a few files like this:

svn commit fileDir1/ fileDir2/ -m "updated!"

"Invalid signature file" when attempting to run a .jar

I've recently started using IntelliJ on my projects. However, some of my colleagues still use Eclipse on the same projects. Today, I've got the very same error after executing the jar-file created by my IntelliJ. While all the solutions in here talking about almost the same thing, none of them worked for me easily (possibly because I don't use ANT, maven build gave me other errors which referred me to, and also I couldn't figure out what are the signed jars by myself!)

Finally, this helped me

zip -d demoSampler.jar 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*SF'

Guess what's been removed from my jar file?!


It seems that the issue was relevant to some eclipse-relevant files.

C++ trying to swap values in a vector

after passing the vector by reference


will produce the expected result.

How to select current date in Hive SQL

To fetch only current date excluding time stamp:

in lower versions, looks like hive CURRENT_DATE is not available, hence you can use (it worked for me on Hive 0.14)


In higher versions say hive 2.0, you can use :


Is there a way to reset IIS 7.5 to factory settings?

There is one way that I have used my self. Go to Control Panel\Programs\Turn Windows features on or off then uninstall IIS and all of its components completely. I restart windows but I'm not sure if it's required or not. Then install it again from the same path.

How to append rows in a pandas dataframe in a for loop?

Suppose your data looks like this:

import pandas as pd
import numpy as np

df = pd.DataFrame([])
for i in range(5):
    data = dict(zip(np.random.choice(10, replace=False, size=5),
                    np.random.randint(10, size=5)))
    data = pd.DataFrame(data.items())
    data = data.transpose()
    data.columns = data.iloc[0]
    data = data.drop(data.index[[0]])
    df = df.append(data)
# 0   0   1   2   3   4   5   6   7   8   9
# 1   6 NaN NaN   8   5 NaN NaN   7   0 NaN
# 1 NaN   9   6 NaN   2 NaN   1 NaN NaN   2
# 1 NaN   2   2   1   2 NaN   1 NaN NaN NaN
# 1   6 NaN   6 NaN   4   4   0 NaN NaN NaN
# 1 NaN   9 NaN   9 NaN   7   1   9 NaN NaN

Then it could be replaced with

data = []
for i in range(5):
    data.append(dict(zip(np.random.choice(10, replace=False, size=5),
                         np.random.randint(10, size=5))))
df = pd.DataFrame(data)

In other words, do not form a new DataFrame for each row. Instead, collect all the data in a list of dicts, and then call df = pd.DataFrame(data) once at the end, outside the loop.

Each call to df.append requires allocating space for a new DataFrame with one extra row, copying all the data from the original DataFrame into the new DataFrame, and then copying data into the new row. All that allocation and copying makes calling df.append in a loop very inefficient. The time cost of copying grows quadratically with the number of rows. Not only is the call-DataFrame-once code easier to write, it's performance will be much better -- the time cost of copying grows linearly with the number of rows.

Functional, Declarative, and Imperative Programming

There's not really any non-ambiguous, objective definition for these. Here is how I would define them:

Imperative - The focus is on what steps the computer should take rather than what the computer will do (ex. C, C++, Java).

Declarative - The focus is on what the computer should do rather than how it should do it (ex. SQL).

Functional - a subset of declarative languages that has heavy focus on recursion

Java NIO FileChannel versus FileOutputstream performance / usefulness

My experience is, that NIO is much faster with small files. But when it comes to large files FileInputStream/FileOutputStream is much faster.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

How do I download a file with Angular2 or greater

I got a solution for downloading from angular 2 without getting corrupt, using spring mvc and angular 2

1st- my return type is :-ResponseEntity from java end. Here I am sending byte[] array has return type from the controller.

2nd- to include the filesaver in your workspace-in the index page as:

<script src=""></script>

3rd- at component ts write this code:

import {ResponseContentType} from '@angular.core';

let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName', 'Accept': 'application/pdf' });
        let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
              .subscribe(data => {

                  var mediaType = 'application/';
                  let blob: Blob = data.blob();
                    window['saveAs'](blob, 'sample.xls');


This will give you xls file format. If you want other formats change the mediatype and file name with right extension.

How to create range in Swift?

If anyone want to create NSRange object can create as:

let range: NSRange = NSRange.init(location: 0, length: 5)

this will create range with position 0 and length 5

how to add picasso library in android studio

Add this to your dependencies in build.gradle:

enter image description here

dependencies {
 implementation 'com.squareup.picasso:picasso:2.71828'

The latest version can be found here

Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project

Take a look at your libraries folder, the library you just added should be in there.

enter image description here

Reload chart data via JSON with Highcharts

EDIT: The response down below is more correct!


<SELECT id="list">
<button id="change">Refresh Table</button>

<div id="container" style="height: 400px"></div>


var options = {
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'spline'
    series: []

$("#change").click(function() {
    if ($("#list").val() == "A") {
        options.series = [{name: 'A', data: [1,2,3,2,1]}]
        // $.get('/dough/includes/live-chart.php?mode=month'
    } else {
        options.series = [{name: 'B', data: [3,2,1,2,3]}]
        // $.get('/dough/includes/live-chart.php?mode=newmode'

    var chart = new Highcharts.Chart(options);    

This is a very simple example since I don't have my files here with me but the basic idea is that every time the user selects new options for the stuff they want to see, you're going to have replace the .series data object with the new information from your server and then recreate the chart using the new Highcharts.Chart();.

Hope this helps! John


Check this out, its from something I've worked on in the past:

$("table#tblGeneralInfo2 > tbody > tr").each(function (index) {
    if (index != 0) {
        var chartnumbervalue = parseInt($(this).find("td:last").text());
        var charttextvalue = $(this).find("td:first").text();
        chartoptions.series[0].data.push([charttextvalue, chartnumbervalue]);

I had a table with information in the first and last tds that I needed to add to the pie chart. I loop through each of the rows and push in the values. Note: I use chartoptions.series[0].data since pie charts only have 1 series.

Tool to monitor HTTP, TCP, etc. Web Service traffic

Wireshark does not do port redirection, but sniffs and interprets a lot of protocols.

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}

How to install Guest addition in Mac OS as guest and Windows machine as host

Before you start, close VirtualBox! After those manipulations start VB as Administrator!

  1. Run CMD as Administrator
  2. Use lines below one by one:
  • cd "C:\Program Files\Oracle\Virtualbox"
  • VBoxManage setextradata “macOS_Catalina” VBoxInternal2/EfiGraphicsResolution 1920x1080

Screen Resolutions: 1280x720, 1920x1080, 2048x1080, 2560x1440, 3840x2160, 1280x800, 1280x1024, 1440x900, 1600x900


  • macOS_Catalina - insert your VB machine name.

  • 1920x1080 - put here your Screen Resolution.


Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, and i believe in the past I've just used

    ActiveWorkbook.Close False

What does "for" attribute do in HTML <label> tag?

It labels whatever input is the parameter for the for attribute.

<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>

Cannot open Windows.h in Microsoft Visual Studio

Start Visual Studio. Go to Tools->Options and expand Projects and solutions. Select VC++ Directories from the tree and choose Include Files from the combo on the right.

You should see:


If this is missing, you found a problem. If not, search for a file. It should be located in

32 bit systems:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include

64 bit systems:

C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\Include

if VS was installed in the default directory.


Can git undo a checkout of unstaged files

If you are working in an editor like Sublime Text, and have file in question still open, you can press ctrl+z, and it will return to the state it had before git checkout.

Nodejs convert string into UTF-8

When you want to change the encoding you always go from one into another. So you might go from Mac Roman to UTF-8 or from ASCII to UTF-8.

It's as important to know the desired output encoding as the current source encoding. For example if you have Mac Roman and you decode it from UTF-16 to UTF-8 you'll just make it garbled.

If you want to know more about encoding this article goes into a lot of details:

What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text

The npm pacakge encoding which uses node-iconv or iconv-lite should allow you to easily specify which source and output encoding you want:

var resultBuffer = encoding.convert(nameString, 'ASCII', 'UTF-8');

jquery: how to get the value of id attribute?

$('.select_continent').click(function () {

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

This May be helpful:

//I personally prefer dynamic import (angular 8)
{ path: 'pages', loadChildren: () => import('./pages/pages.module').then(mod => mod.PageModule) }

In child routing it should look like: { path: 'about', component: AboutComponent },

Note that there is no pages in path of child routing and in routerLink or nsRouterLink it should look like routerLink="/pages/about"

I hope thi help someone out there.

Is there an arraylist in Javascript?

Try this, maybe can help, it do what you want:


var listArray = new ListArray();_x000D_
let element = {name: 'Edy', age: 27, country: "Brazil"};_x000D_
let element2 = {name: 'Marcus', age: 27, country: "Brazil"};_x000D_
<script src=""></script>

Bash tool to get nth line from a file

If you got multiple lines by delimited by \n (normally new line). You can use 'cut' as well:

echo "$data" | cut -f2 -d$'\n'

You will get the 2nd line from the file. -f3 gives you the 3rd line.

How to get Bitmap from an Uri?

Here's the correct way of doing it, keeping tabs on memory usage as well:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
  super.onActivityResult(requestCode, resultCode, data);
  if (resultCode == RESULT_OK)
    Uri imageUri = data.getData();
    Bitmap bitmap = getThumbnail(imageUri);

public static Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException{
  InputStream input = this.getContentResolver().openInputStream(uri);

  BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
  onlyBoundsOptions.inJustDecodeBounds = true;
  BitmapFactory.decodeStream(input, null, onlyBoundsOptions);

  if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
    return null;

  int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;

  double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0;

  BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
  bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
  bitmapOptions.inDither = true; //optional
  input = this.getContentResolver().openInputStream(uri);
  Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
  return bitmap;

private static int getPowerOfTwoForSampleRatio(double ratio){
  int k = Integer.highestOneBit((int)Math.floor(ratio));
  if(k==0) return 1;
  else return k;

The getBitmap() call from Mark Ingram's post also calls the decodeStream(), so you don't lose any functionality.


Add support library to Android Studio project

You can simply download the library which you want to include and copy it to libs folder of your project. Then select that file (in my case it was android-support-v4 library) right click on it and select "Add as Library"

Checking the equality of two slices

You should use reflect.DeepEqual()

DeepEqual is a recursive relaxation of Go's == operator.

DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.

Array values are deeply equal when their corresponding elements are deeply equal.

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

Func values are deeply equal if both are nil; otherwise they are not deeply equal.

Interface values are deeply equal if they hold deeply equal concrete values.

Map values are deeply equal if they are the same map object or if they have the same length and their corresponding keys (matched using Go equality) map to deeply equal values.

Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

How to create new folder?

Have you tried os.mkdir?

You might also try this little code snippet:

mypath = ...
if not os.path.isdir(mypath):

makedirs creates multiple levels of directories, if needed.

How can I get the application's path in a .NET console application?

For Console Applications, you can try this:


Output (on my local machine):

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug

Or you can try (there's an additional backslash in the end):



c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug\

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Drop root privileges after you bind to port 80 (or 443).

This allows port 80/443 to remain protected, while still preventing you from serving requests as root:

function drop_root() {

A full working example using the above function:

var process = require('process');
var http = require('http');
var server = http.createServer(function(req, res) {

server.listen(80, null, null, function() {
    console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
    console.log('User ID:',process.getuid()+', Group ID:',process.getgid());

See more details at this full reference.

Base64 Encoding Image

Google led me to this solution (base64_encode). Hope this helps!


ON DUPLICATE KEY UPDATE is not really in the standard. It's about as standard as REPLACE is. See SQL MERGE.

Essentially both commands are alternative-syntax versions of standard commands.

Add swipe to delete UITableViewCell

Add these two functions:

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {
        // handle delete (by removing the data from your array and updating the tableview)

Swift 3.0:

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)

Swift 4.2

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {
        // handle delete (by removing the data from your array and updating the tableview)

Not equal to != and !== in PHP

!== should match the value and data type

!= just match the value ignoring the data type

$num = '1';
$num2 = 1;

$num == $num2; // returns true    
$num === $num2; // returns false because $num is a string and $num2 is an integer

Fast query runs slow in SSRS

Had the same problem, and fixed it by giving the shared dataset a default parameter and updating that dataset in the reporting server.

Session 'app': Error Installing APK

In my case with Android 8.0(Oreo), no one of this solutions worked! If you have more than 1 user, then you should go to Settings->Applications->All Applications->Find the application and uninstall for all users! After this steps, it worked!

How to append new data onto a new line

I presume that all you are wanting is simple string concatenation:

def storescores():

   hs = open("hst.txt","a")
   hs.write(name + " ")

Alternatively, change the " " to "\n" for a newline.

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

Here is a working version of the "build defs". This is similar to my previous answer but I figured out the build month. (You just can't compute build month in a #if statement, but you can use a ternary expression that will be compiled down to a constant.)

Also, according to the documentation, if the compiler cannot get the time of day it will give you question marks for these strings. So I added tests for this case, and made the various macros return an obviously wrong value (99) if this happens.

#ifndef BUILD_DEFS_H

#define BUILD_DEFS_H

// Example of __DATE__ string: "Jul 27 2012"
// Example of __TIME__ string: "21:06:19"

    ( \
        (__DATE__[ 7] - '0') * 1000 + \
        (__DATE__[ 8] - '0') *  100 + \
        (__DATE__[ 9] - '0') *   10 + \
        (__DATE__[10] - '0') \

    ( \
        ((__DATE__[4] >= '0') ? (__DATE__[4] - '0') * 10 : 0) + \
        (__DATE__[5] - '0') \

#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')

    ( \
        (BUILD_MONTH_IS_JAN) ?  1 : \
        (BUILD_MONTH_IS_FEB) ?  2 : \
        (BUILD_MONTH_IS_MAR) ?  3 : \
        (BUILD_MONTH_IS_APR) ?  4 : \
        (BUILD_MONTH_IS_MAY) ?  5 : \
        (BUILD_MONTH_IS_JUN) ?  6 : \
        (BUILD_MONTH_IS_JUL) ?  7 : \
        (BUILD_MONTH_IS_AUG) ?  8 : \
        (BUILD_MONTH_IS_SEP) ?  9 : \
        (BUILD_MONTH_IS_OCT) ? 10 : \
        (BUILD_MONTH_IS_NOV) ? 11 : \
        (BUILD_MONTH_IS_DEC) ? 12 : \
        /* error default */  99 \

#define COMPUTE_BUILD_HOUR ((__TIME__[0] - '0') * 10 + __TIME__[1] - '0')
#define COMPUTE_BUILD_MIN  ((__TIME__[3] - '0') * 10 + __TIME__[4] - '0')
#define COMPUTE_BUILD_SEC  ((__TIME__[6] - '0') * 10 + __TIME__[7] - '0')

#define BUILD_DATE_IS_BAD (__DATE__[0] == '?')


#define BUILD_TIME_IS_BAD (__TIME__[0] == '?')


#endif // BUILD_DEFS_H

With the following test code, the above works great:

printf("%04d-%02d-%02dT%02d:%02d:%02d\n", BUILD_YEAR, BUILD_MONTH, BUILD_DAY, BUILD_HOUR, BUILD_MIN, BUILD_SEC);

However, when I try to use those macros with your stringizing macro, it stringizes the literal expression! I don't know of any way to get the compiler to reduce the expression to a literal integer value and then stringize.

Also, if you try to statically initialize an array of values using these macros, the compiler complains with an error: initializer element is not constant message. So you cannot do what you want with these macros.

At this point I'm thinking that your best bet is the Python script that just generates a new include file for you. You can pre-compute anything you want in any format you want. If you don't want Python we can write an AWK script or even a C program.

Difference between one-to-many and many-to-one relationship

There is no difference. It's just a matter of language and preference as to which way round you state the relationship.

Post multipart request with Android SDK

As MultiPartEntity is deprecated. So here is the new way to do it! And you only need httpcore.jar(latest) and httpmime.jar(latest) download them from Apache site.

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(URL);

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    entityBuilder.addTextBody(USER_ID, userId);
    entityBuilder.addTextBody(NAME, name);
    entityBuilder.addTextBody(TYPE, type);
    entityBuilder.addTextBody(COMMENT, comment);
    entityBuilder.addTextBody(LATITUDE, String.valueOf(User.Latitude));
    entityBuilder.addTextBody(LONGITUDE, String.valueOf(User.Longitude));

    if(file != null)
        entityBuilder.addBinaryBody(IMAGE, file);

    HttpEntity entity =;
    HttpResponse response = client.execute(post);
    HttpEntity httpEntity = response.getEntity();
    result = EntityUtils.toString(httpEntity);
    Log.v("result", result);
catch(Exception e)

How to return part of string before a certain character?

Another method could be to split the string by ":" and then pop off the end. var newString = string.split(":").pop();

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

You can increase the timeout in node like so.'/slow/request', function(req, res){ req.connection.setTimeout(100000); //100 seconds ... }

How to use PDO to fetch results array in PHP?

There are three ways to fetch multiple rows returned by PDO statement.

The simplest one is just to iterate over PDOStatement itself:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
// iterating over a statement
foreach($stmt as $row) {
    echo $row['name'];

another one is to fetch rows using fetch() method inside a familiar while statement:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
// using while
while($row = $stmt->fetch()) {
    echo $row['name'];

but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
// fetching rows into array
$data = $stmt->fetchAll();

or, if you need to preprocess some data first, use the while loop and collect the data into array manually

$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
// using while
while($row = $stmt->fetch()) {
    $result[] = [
        'newname' => $row['oldname'],
        // etc

and then output them in a template:

<?php foreach($data as $row): ?>
<?php endforeach ?>

Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.

Laravel 5.4 redirection to custom url after login

in accord with Laravel documentation, I create in app/Http/Controllers/Auth/LoginController.php the following method :

protected function redirectTo()

    if($user->account_type == 1){
        return '/admin';
        return '/home';


to get the user information from my db I used "Illuminate\Support\Facades\Auth;".

"Exception has been thrown by the target of an invocation" error (mscorlib)

I know its kind of odd but I experienced this error for a c# application and finally I found out the problem is the Icon of the form! when I changed it everything just worked fine.

I should say that I had this error just in XP not in 7 or 8 .

CSS selector - element with a given child

I agree that it is not possible in general.

The only thing CSS3 can do (which helped in my case) is to select elements that have no children:

table td:empty
   background-color: white;

Or have any children (including text):

table td:not(:empty)
   background-color: white;

How to append text to an existing file in Java?


public class Writer {

    public static void main(String args[]){
        doWrite("output.txt","Content to be appended to file");

    public static void doWrite(String filePath,String contentToBeAppended){

            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)
        catch( IOException e ){
        // File writing/opening failed at some stage.



Active Menu Highlight CSS

Add a class to the body of each page:

<body class="home">

Or if you're on the contact page:

<body class="contact">

Then take this into consideration when you're creating your styles:

#sub-header ul li:hover,
body.home li.home, { background-color: #000;}

#sub-header ul li:hover a,
body.home li.home a, a { color: #fff; }

Lastly, apply class names to your list items:

  <li class="home"><a href="index.php">Home</a></li>
  <li class="contact"><a href="contact.php">Contact Us</a></li>
  <li class="about"><a href="about.php">About Us</a></li>

This point, whenever you're on the body.home page, your li.home a link will have default styling indicating it is the current page.

How to set Sqlite3 to be case insensitive when string comparing?

Simply, you can use COLLATE NOCASE in your SELECT query:


jQuery check if it is clicked or not

Using jQuery, I would suggest a shorter solution.

var elementClicked;
   elementClicked = true;
if( elementClicked != true ) {
    alert("element not clicked");
    alert("element clicked");

("element" here is to be replaced with the actual name tag)

How to restart counting from 1 after erasing table in MS Access?

In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:

If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.

For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use @Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use @Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).

how to check if object already exists in a list

If it's maintainable to use those 2 properties, you could:

bool alreadyExists = myList.Any(x=> x.Foo=="ooo" && x.Bar == "bat");

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00



EDIT: actually, Chromium docs also indicate how to do it for other OS.

How to overcome "'aclocal-1.15' is missing on your system" warning?

A generic answer that may or not apply to this specific case:

As the error message hint at, aclocal-1.15 should only be required if you modified files that were used to generate aclocal.m4

If you don't modify any of those files (including then you should not need to have aclocal-1.15.

In my case, the problem was not that any of those files was modified but somehow the timestamp on was 6 minutes later compared to aclocal.m4.

I haven't figured out why, but a clean clone of my git repo solved the issue for me. Maybe something linked to git and how it created files in the first place.

Rather than rerunning autoconf and friends, I would just try to get a clean clone and try again.

It's also possible that somebody committed a change to but didn't regenerate the aclocal.m4, in which case you indeed have to rerun automake and friends.

git push rejected

Jarret Hardie is correct. Or, first merge your changes back into master and then try the push. By default, git push pushes all branches that have names that match on the remote -- and no others. So those are your two choices -- either specify it explicitly like Jarret said or merge back to a common branch and then push.

There's been talk about this on the Git mail list and it's clear that this behavior is not about to change anytime soon -- many developers rely on this behavior in their workflows.


Assuming your upstreammaster branch is ready to push then you could do this:

  1. Pull in any changes from the upstream.

    $ git pull upstream master

  2. Switch to my local master branch

    $ git checkout master

  3. Merge changes in from upstreammaster

    $ git merge upstreammaster

  4. Push my changes up

    $ git push upstream

Another thing that you may want to do before pushing is to rebase your changes against upstream/master so that your commits are all together. You can either do that as a separate step between #1 and #2 above (git rebase upstream/master) or you can do it as part of your pull (git pull --rebase upstream master)

How to remove square brackets from list in Python?

def listToStringWithoutBrackets(list1):
    return str(list1).replace('[','').replace(']','')

How to convert a timezone aware string to datetime in Python without dateutil?

I'm new to Python, but found a way to convert

2017-05-27T07:20:18.000-04:00 to

2017-05-27T07:20:18 without downloading new utilities.

from datetime import datetime, timedelta

time_zone1 = int("2017-05-27T07:20:18.000-04:00"[-6:][:3])
>>returns -04

item_date = datetime.strptime("2017-05-27T07:20:18.000-04:00".replace(".000", "")[:-6], "%Y-%m-%dT%H:%M:%S") + timedelta(hours=-time_zone1)

I'm sure there are better ways to do this without slicing up the string so much, but this got the job done.

Change NULL values in Datetime format to empty string

CASE and CAST should work:

CASE WHEN mycol IS NULL THEN '' ELSE CONVERT(varchar(50), mycol, 121) END


My understanding is that HEAD points the current branch, while ORIG_HEAD is used to store the previous HEAD before doing "dangerous" operations.

For example git-rebase and git-am record the original tip of branch before they apply any changes.

ITextSharp HTML to PDF?

Here's what I was able to get working on version 5.4.2 (from the nuget install) to return a pdf response from an mvc controller. It could be modfied to use a FileStream instead of MemoryStream for the output if that's what is needed.

I post it here because it is a complete example of current iTextSharp usage for the html -> pdf conversion (disregarding images, I haven't looked at that since my usage doesn't require it)

It uses iTextSharp's XmlWorkerHelper, so the incoming hmtl must be valid XHTML, so you may need to do some fixup depending on your input.

using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using System.IO;
using System.Web.Mvc;

namespace Sample.Web.Controllers
    public class PdfConverterController : Controller
        public ActionResult HtmlToPdf(string html)

            html = @"<?xml version=""1.0"" encoding=""UTF-8""?>
                 <!DOCTYPE html 
                     PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN""
                 <html xmlns="""" xml:lang=""en"" lang=""en"">
                        <title>Minimal XHTML 1.0 Document with W3C DTD</title>
                    " + html + "</body></html>";

            var bytes = System.Text.Encoding.UTF8.GetBytes(html);

            using (var input = new MemoryStream(bytes))
                var output = new MemoryStream(); // this MemoryStream is closed by FileStreamResult

                var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 50, 50, 50, 50);
                var writer = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;

                var xmlWorker = XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer, document, input, null);
                output.Position = 0;

                return new FileStreamResult(output, "application/pdf");

Round to 2 decimal places

BigDecimal a = new BigDecimal("12345.0789");
a = a.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_UP);
//Also check other rounding modes
System.out.println("a >> "+a.toPlainString()); //Returns 12345.08

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

I needed a PHP-only solution, so just in case someone needs it as well. It takes an allowed input string like "*" and returns the request header server name, if the input matches.

function getCORSHeaderOrigin($allowed, $input)
    if ($allowed == '*') {
        return '*';

    $allowed = preg_quote($allowed, '/');

    if (($wildcardPos = strpos($allowed, '*')) !== false) {
        $allowed = str_replace('*', '(.*)', $allowed);

    $regexp = '/^' . $allowed . '$/';

    if (!preg_match($regexp, $input, $matches)) {
        return 'none';

    return $input;

And here are the test cases for a phpunit data provider:

//    <description>                            <allowed>          <input>                   <expected>
array('Allow Subdomain',                       '', '',        ''),
array('Disallow wrong Subdomain',              '', '',         'none'),
array('Allow All',                             '*',               '',         '*'),
array('Allow Subdomain Wildcard',              '*',   '',         ''),
array('Disallow Wrong Subdomain no Wildcard',  '*',   '',            'none'),
array('Allow Double Subdomain for Wildcard',   '*',   '',        ''),
array('Don\'t fall for incorrect position',    '*',   '', 'none'),
array('Allow Subdomain in the middle',         'a.*', '',       ''),
array('Disallow wrong Subdomain',              'a.*', '',       'none'),
array('Correctly handle dots in allowed',      '',     'exampleXcom',            'none'),

How do I find the duplicates in a list and create another list with them?

You don't need the count, just whether or not the item was seen before. Adapted that answer to this problem:

def list_duplicates(seq):
  seen = set()
  seen_add = seen.add
  # adds all elements it doesn't know yet to seen and all other to seen_twice
  seen_twice = set( x for x in seq if x in seen or seen_add(x) )
  # turn the set into a list (as requested)
  return list( seen_twice )

a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]

Just in case speed matters, here are some timings:

# file:
import collections

def thg435(l):
    return [x for x, y in collections.Counter(l).items() if y > 1]

def moooeeeep(l):
    seen = set()
    seen_add = seen.add
    # adds all elements it doesn't know yet to seen and all other to seen_twice
    seen_twice = set( x for x in l if x in seen or seen_add(x) )
    # turn the set into a list (as requested)
    return list( seen_twice )

def RiteshKumar(l):
    return list(set([x for x in l if l.count(x) > 1]))

def JohnLaRooy(L):
    seen = set()
    seen2 = set()
    seen_add = seen.add
    seen2_add = seen2.add
    for item in L:
        if item in seen:
    return list(seen2)

l = [1,2,3,2,1,5,6,5,5,5]*100

Here are the results: (well done @JohnLaRooy!)

$ python -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
10000 loops, best of 3: 74.6 usec per loop
$ python -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 91.3 usec per loop
$ python -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 266 usec per loop
$ python -mtimeit -s 'import test' 'test.RiteshKumar(test.l)'
100 loops, best of 3: 8.35 msec per loop

Interestingly, besides the timings itself, also the ranking slightly changes when pypy is used. Most interestingly, the Counter-based approach benefits hugely from pypy's optimizations, whereas the method caching approach I have suggested seems to have almost no effect.

$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
100000 loops, best of 3: 17.8 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
10000 loops, best of 3: 23 usec per loop
$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 39.3 usec per loop

Apparantly this effect is related to the "duplicatedness" of the input data. I have set l = [random.randrange(1000000) for i in xrange(10000)] and got these results:

$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
1000 loops, best of 3: 495 usec per loop
$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
1000 loops, best of 3: 499 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 1.68 msec per loop

Compiling an application for use in highly radioactive environments

Since you specifically ask for software solutions, and you are using C++, why not use operator overloading to make your own, safe datatypes? For example:

Instead of using uint32_t (and double, int64_t etc), make your own SAFE_uint32_t which contains a multiple (minimum of 3) of uint32_t. Overload all of the operations you want (* + - / << >> = == != etc) to perform, and make the overloaded operations perform independently on each internal value, ie don't do it once and copy the result. Both before and after, check that all of the internal values match. If values don't match, you can update the wrong one to the value with the most common one. If there is no most-common value, you can safely notify that there is an error.

This way it doesn't matter if corruption occurs in the ALU, registers, RAM, or on a bus, you will still have multiple attempts and a very good chance of catching errors. Note however though that this only works for the variables you can replace - your stack pointer for example will still be susceptible.

A side story: I ran into a similar issue, also on an old ARM chip. It turned out to be a toolchain which used an old version of GCC that, together with the specific chip we used, triggered a bug in certain edge cases that would (sometimes) corrupt values being passed into functions. Make sure your device doesn't have any problems before blaming it on radio-activity, and yes, sometimes it is a compiler bug =)

Undoing accidental git stash pop

Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show them to see the diff and use patch -R to unapply them.

MessageBox Buttons?

  1. Your call to MessageBox.Show needs to pass MessageBoxButtons.YesNo to get the Yes/No buttons instead of the OK button.

  2. Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes....

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    // user clicked yes
    // user clicked no

ClientAbortException: Connection reset by peer: socket write error

Your HTTP client disconnected.

This could have a couple of reasons:

  • Responding to the request took too long, the client gave up
  • You responded with something the client did not understand
  • The end-user actually cancelled the request
  • A network error occurred
  • ... probably more

You can fairly easily emulate the behavior:

URL url = new URL("");

int numberOfBytesToRead = 200;

byte[] buffer = new byte[numberOfBytesToRead];
int numberOfBytesRead = url.openStream().read(buffer);

Is there a good JSP editor for Eclipse?

I followed the advice of Simon Gibbs in this answer and found it worked out fine - if you're in a hurry, the "Web Page Editor (optional)" package from the Eclipse update site does the trick.

For the Eclipse-challenged (me) Help > Install New Software > Work with > Expand Web, XML, and Java EE Development > Select "Web Page Editor (optional)" and "next-through" to completion.

Password Protect a SQLite DB. Is it possible?

Why do you need to encrypt the database? The user could easily disassemble your program and figure out the key. If you're encrypting it for network transfer, then consider using PGP instead of squeezing an encryption layer into a database layer.

How to break out or exit a method in Java?

Use the return keyword to exit from a method.

public void someMethod() {
    //... a bunch of code ...
    if (someCondition()) {
    //... otherwise do the following...

Pls note: We may use break statements which are used to break/exit only from a loop, and not the entire program.

To exit from program: System.exit() Method:
System.exit has status code, which tells about the termination, such as:
exit(0) : Indicates successful termination.
exit(1) or exit(-1) or any non-zero value – indicates unsuccessful termination.

RAW POST using cURL in PHP

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

Java path..Error of jvm.cfg

Don't think if this is a correct way...(perhaps proper installation of Java is a permanent solution)....but this is a trick..:)

Delete the “java.exe” file from “c:\windows” and “c:\windows\system32". That should fix it.

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

protected void onNewIntent(Intent intent) {
    // getIntent() should always return the most recent

With all setup logic happening in onResume() by utilizing getIntent().

Render HTML in React Native

An iOS/Android pure javascript react-native component that renders your HTML into 100% native views. It's made to be extremely customizable and easy to use and aims at being able to render anything you throw at it.


use above library to improve your app performance level and easy to use.


npm install react-native-render-html --save or yarn add react-native-render-html

Basic usage

import React, { Component } from 'react';
import { ScrollView, Dimensions } from 'react-native';
import HTML from 'react-native-render-html';

const htmlContent = `
    <h1>This HTML snippet is now rendered with native components !</h1>
    <h2>Enjoy a webview-free and blazing fast application</h2>
    <img src="" />
    <em style="textAlign: center;">Look at how happy this native cat is</em>

export default class Demo extends Component {
    render () {
        return (
            <ScrollView style={{ flex: 1 }}>
                <HTML html={htmlContent} imagesMaxWidth={Dimensions.get('window').width} />


you may user it's different different types of props (see above link) for the designing and customizable also using below link refer.

Customizable render html

How do I check if a Sql server string is null or empty

You can use ISNULL and check the answer against the known output:

SELECT case when ISNULL(col1, '') = '' then '' else col1 END AS COL1 FROM TEST

Is there a jQuery unfocus method?


Documentation at:

Broadcast Receiver within a Service

The better pattern is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In fact, using this pattern may remove the need for a constant-running Service altogether.

Register the BroadcastReceiver in your Manifest, and create a separate class/file for it.


<receiver android:name=".FooReceiver" >
    <intent-filter >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />

When the receiver runs, you simply pass an Intent (Bundle) to the Service, and respond to it in onStartCommand().


public class FooReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        // do your work quickly!
        // then call context.startService();


In my opinion, I think it's important to explain the why behind the need for a GROUP BY in your SQL when summing with OVER() clause and why you are getting repeated lines of data when you are expecting one row per BrandID.

Take this example: You need to aggregate the total sale price of each order line, per specific order category, between two dates, but you also need to retain individual order data in your final results. A SUM() on the SalesPrice column would not allow you to get the correct totals because it would require a GROUP BY, therefore squashing the details because you wouldn't be able to keep the individual order lines in the select statement.

Many times we see a #temp table, @table variable, or CTE filled with the sum of our data and grouped up so we can join to it again later to get a column of the sums we need. This can add processing time and extra lines of code. Instead, use OVER(PARTITION BY ()) like this:

  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

Notice we are not grouping and we have individual order lines column selected. The PARTITION BY in the last column will return us a sales price total for each row of data in each category. What the last column essentially says is, we want the sum of the sale price (SUM(SalePrice)) over a partition of my results and by a specified category (OVER(PARTITION BY CategoryHere)).

If we remove the other columns from our select statement, and leave our final SUM() column, like this:

  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

The results will still repeat this sum for each row in our original result set. The reason is this method does not require a GROUP BY. If you don't need to retain individual line data, then simply SUM() without the use of OVER() and group up your data appropriately. Again, if you need an additional column with specific totals, you can use the OVER(PARTITION BY ()) method described above without additional selects to join back to.

The above is purely for explaining WHY he is getting repeated lines of the same number and to help understand what this clause provides. This method can be used in many ways and I highly encourage further reading from the documentation here:

Over Clause

Error 1022 - Can't write; duplicate key in table

As others have mentioned, it's possible that the name for your constraint is already in use by another table in your DB. They must be unique across the database.

A good convention for naming foreign key constraints is:


To investigate whether there's a possible clash, you can list all constraints used by your database with this query:

SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'YOUR_DB';

When I ran this query, I discovered I had previously made a temporary copy of a table and this copy was already using the constraint name I was attempting to use.

What tool to use to draw file tree diagram

As promised, here is my Cairo version. I scripted it with Lua, using lfs to walk the directories. I love these little challenges, as they allow me to explore APIs I wanted to dig for quite some time...
lfs and LuaCairo are both cross-platform, so it should work on other systems (tested on French WinXP Pro SP3).

I made a first version drawing file names as I walked the tree. Advantage: no memory overhead. Inconvenience: I have to specify the image size beforehand, so listings are likely to be cut off.

So I made this version, first walking the directory tree, storing it in a Lua table. Then, knowing the number of files, creating the canvas to fit (at least vertically) and drawing the names.
You can easily switch between PNG rendering and SVG one. Problem with the latter: Cairo generates it at low level, drawing the letters instead of using SVG's text capability. Well, at least, it guarantees accurate rending even on systems without the font. But the files are bigger... Not really a problem if you compress it after, to have a .svgz file.
Or it shouldn't be too hard to generate the SVG directly, I used Lua to generate SVG in the past.

-- LuaFileSystem <>
-- LuaCairo <>
local CAIRO = cairo

local PI = math.pi
local TWO_PI = 2 * PI

--~ local dirToList = arg[1] or "C:/PrgCmdLine/Graphviz"
--~ local dirToList = arg[1] or "C:/PrgCmdLine/Tecgraf"
local dirToList = arg[1] or "C:/PrgCmdLine/tcc"
-- Ensure path ends with /
dirToList = string.gsub(dirToList, "([^/])$", "%1/")
print("Listing: " .. dirToList)
local fileNb = 0

--~ outputType = 'svg'
outputType = 'png'

-- dirToList must have a trailing slash
function ListDirectory(dirToList)
  local dirListing = {}
  for file in lfs.dir(dirToList) do
    if file ~= ".." and file ~= "." then
      local fileAttr = lfs.attributes(dirToList .. file)
      if fileAttr.mode == "directory" then
        dirListing[file] = ListDirectory(dirToList .. file .. '/')
        dirListing[file] = ""
      fileNb = fileNb + 1
  return dirListing

--dofile[[../Lua/DumpObject.lua]] -- My own dump routine
local dirListing = ListDirectory(dirToList)
--~ print("\n" .. DumpObject(dirListing))
print("Found " .. fileNb .. " files")

--~ os.exit()

-- Constants to change to adjust aspect
local initialOffsetX = 20
local offsetY = 50
local offsetIncrementX = 20
local offsetIncrementY = 12
local iconOffset = 10

local width = 800 -- Still arbitrary
local titleHeight = width/50
local height = offsetIncrementY * (fileNb + 1) + titleHeight
local outfile = "CairoDirTree." .. outputType

local ctxSurface
if outputType == 'svg' then
  ctxSurface = cairo.SvgSurface(outfile, width, height)
  ctxSurface = cairo.ImageSurface(CAIRO.FORMAT_RGB24, width, height)
local ctx = cairo.Context(ctxSurface)

-- Display a file name
-- file is the file name to display
-- offsetX is the indentation
function DisplayFile(file, bIsDir, offsetX)
  if bIsDir then
    ctx:select_font_face("Sans", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_BOLD)
    ctx:set_source_rgb(0.5, 0.0, 0.7)

  -- Display file name
  ctx:move_to(offsetX, offsetY)

  if bIsDir then
    ctx:new_sub_path() -- Position independent of latest move_to
    -- Draw arc with absolute coordinates
    ctx:arc(offsetX - iconOffset, offsetY - offsetIncrementY/3, offsetIncrementY/3, 0, TWO_PI)
    -- Violet disk
    ctx:set_source_rgb(0.7, 0.0, 0.7)
    ctx:restore() -- Restore original settings

  -- Increment line offset
  offsetY = offsetY + offsetIncrementY

-- Erase background (white)
ctx:set_source_rgb(1.0, 1.0, 1.0)

--~ ctx:set_line_width(0.01)

-- Draw in dark blue
ctx:set_source_rgb(0.0, 0.0, 0.3)
ctx:move_to(5, titleHeight)
-- Display title
ctx:show_text("Directory tree of " .. dirToList)

-- Select font for file names
offsetY = titleHeight * 2

-- Do the job
function DisplayDirectory(dirToList, offsetX)
  for k, v in pairs(dirToList) do
--~ print(k, v)
    if type(v) == "table" then
      -- Sub-directory
      DisplayFile(k, true, offsetX)
      DisplayDirectory(v, offsetX + offsetIncrementX)
      DisplayFile(k, false, offsetX)

DisplayDirectory(dirListing, initialOffsetX)

if outputType == 'svg' then
  --cairo.surface_write_to_png(ctxSurface, outfile)


print("Found " .. fileNb .. " files")

Of course, you can change the styles. I didn't draw the connection lines, I didn't saw it as necessary. I might add them optionally later.

MySQL: Insert datetime into other datetime field

for MYSQL try this

INSERT INTO table1(myDatetimeField)VALUES(STR_TO_DATE('12-01-2014 00:00:00','%m-%d-%Y %H:%i:%s');


select * from table1
output- datetime= 2014-12-01 00:00:00

Dynamically select data frame columns using $ and a character value

Using dplyr provides an easy syntax for sorting the data frames

mtcars %>% arrange(gear, desc(mpg))

It might be useful to use the NSE version as shown here to allow dynamically building the sort list

sort_list <- c("gear", "desc(mpg)")
mtcars %>% arrange_(.dots = sort_list)

Avoid web.config inheritance in child web application using inheritInChildApplications

I put everything into:

<location path="." inheritInChildApplications="false">

except: <configSections/>, <connectionStrings/> and <runtime/>.

There are some cases when we don't want to inherit some secions from <configSections />, but we can't put <section/> tag into <location/>, so we have to create a <secionGroup /> and put our unwanted sections into that group. Section groups can be later inserted into a location tag.

So we have to change this:

  <section name="unwantedSection" />


  <sectionGroup name="myNotInheritedSections">
    <section name="unwantedSection" />

<location path="." inheritInChildApplications="false">
        <unwantedSection />

Pandas split column of lists into multiple columns

Here's another solution using df.transform and df.set_index:

>>> (df['teams']
       .transform([lambda x:x[0], lambda x:x[1]])

  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

HTML5 Canvas: Zooming

IIRC Canvas is a raster style bitmap. it wont be zoomable because there's no stored information to zoom to.

Your best bet is to keep two copies in memory (zoomed and non) and swap them on mouse click.

How to add buttons dynamically to my form?

You aren't creating any buttons, you just have an empty list.

You can forget the list and just create the buttons in the loop.

private void button1_Click(object sender, EventArgs e) 
     int top = 50;
     int left = 100;

     for (int i = 0; i < 10; i++)     
          Button button = new Button();   
          button.Left = left;
          button.Top = top;
          top += button.Height + 2;

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

The major difference between the two is that $_SERVER['SERVER_NAME'] is a server controlled variable, while $_SERVER['HTTP_HOST'] is a user-controlled value.

The rule of thumb is to never trust values from the user, so $_SERVER['SERVER_NAME'] is the better choice.

As Gumbo pointed out, Apache will construct SERVER_NAME from user-supplied values if you don't set UseCanonicalName On.

Edit: Having said all that, if the site is using a name-based virtual host, the HTTP Host header is the only way to reach sites that aren't the default site.

Can we write our own iterator in Java?

Good example for Iterable to compute factorial

FactorialIterable fi = new FactorialIterable(10);
Iterator<Integer> iterator = fi.iterator();
while (iterator.hasNext()){

Short code for Java 1.8

new FactorialIterable(5).forEach(System.out::println);

Custom Iterable class

public class FactorialIterable implements Iterable<Integer> {

    private final FactorialIterator factorialIterator;

    public FactorialIterable(Integer value) {
        factorialIterator = new FactorialIterator(value);

    public Iterator<Integer> iterator() {
        return factorialIterator;

    public void forEach(Consumer<? super Integer> action) {
        Integer last = 0;
        for (Integer t : this) {
            last = t;


Custom Iterator class

public class FactorialIterator implements Iterator<Integer> {

    private final Integer mNumber;
    private Integer mPosition;
    private Integer mFactorial;

    public FactorialIterator(Integer number) {
        this.mNumber = number;
        this.mPosition = 1;
        this.mFactorial = 1;

    public boolean hasNext() {
        return mPosition <= mNumber;

    public Integer next() {
        if (!hasNext())
            return 0;

        mFactorial = mFactorial * mPosition;


        return  mFactorial;

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

I know this has been already answered a long time ago but the answer didnt fix it for me but, I just removed everything from the sources in the buildpath settings and re-added them

Get Filename Without Extension in Python

>>> import os
>>> os.path.splitext("")
('', '.jpg')

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");

public void write(String s) throws IOException {

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes =, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {

What's a good (free) visual merge tool for Git? (on windows)

  • TortoiseMerge (part of ToroiseSVN) is much better than kdiff3 (I use both and can compare);
  • p4merge (from Perforce) works also very well;
  • Diffuse isn't so bad;
  • Diffmerge from SourceGear has only one flaw in handling UTF8-files without BOM, making in unusable for this case.

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

Quoting MSDN:

When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back. When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing.

In practice this means that some of the statements might fail, leaving the transaction 'partially completed', and there might be no sign of this failure for a caller.

A simple example:

SELECT 'Everything is fine'

This code would execute 'successfully' with XACT_ABORT OFF, and will terminate with an error with XACT_ABORT ON ('INSERT INTO t2' will not be executed, and a client application will raise an exception).

As a more flexible approach, you could check @@ERROR after each statement (old school), or use TRY...CATCH blocks (MSSQL2005+). Personally I prefer to set XACT_ABORT ON whenever there is no reason for some advanced error handling.

Pandas index column title or name

You can just get/set the index via its name property

In [7]:
Out[7]: 'Index Title'

In [8]: = 'foo'

In [9]:
Out[9]: 'foo'

In [10]: df
         Column 1
Apples          1
Oranges         2
Puppies         3
Ducks           4

Where to find extensions installed folder for Google Chrome on Mac?

They are found on either one of the below locations depending on how chrome was installed

  • When chrome is installed at the user level, it's located at:

~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions

  • When installed at the root level, it's at:

/Library/Application\ Support/Google/Chrome/Default/Extensions

SQL: Alias Column Name for Use in CASE Statement

  • If you write only equal condition just: Select Case columns1 When 0 then 'Value1' when 1 then 'Value2' else 'Unknown' End

  • If you want to write greater , Less then or equal you must do like this: Select Case When [ColumnsName] >0 then 'value1' When [ColumnsName]=0 Or [ColumnsName]<0 then 'value2' Else 'Unkownvalue' End

From tablename

Thanks Mr.Buntha Khin

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
>>> s[4]

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
hh ee ll ll oo

SQL Server Text type vs. varchar data type

In SQL server 2005 new datatypes were introduced: varchar(max) and nvarchar(max) They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar and nvarchar. Among these advantages are the ability to use string manipulation functions such as substring().

Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.

In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.

As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.

How to split a string with angularJS

You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

angular.module('myModule', [])
    .filter('split', function() {
        return function(input, splitChar, splitIndex) {
            // do some bounds checking here to ensure it has that index
            return input.split(splitChar)[splitIndex];

From here, you can use a filter as you originally intended

{{test | split:',':0}}
{{test | split:',':0}}

More info at (thanks ross)

Plunkr @

Python Variable Declaration

There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic". Variables in Python can hold values of any type, and you can't restrict that.

Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__ method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.

So for example:

class Thing(object):

    def __init__(self, magic):
        self.magic = magic

Easy. Now instances of this class have a magic attribute:

thingo = Thing("More magic")
# thingo.magic is now "More magic"

Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:

class Thing(object):

    magic = "Magic"

    def __init__(self):

Now try:

thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1


class Thing(object):

    magic = ["More", "magic"]

    def __init__(self):

thing1 = Thing()
thing2 = Thing()
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]

This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.

The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__ method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.

How do I set a Windows scheduled task to run in the background?

As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.

It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

enter image description here

enter image description here

enter image description here

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

Do this:

var left: Node? = null

fun show() {
     val left = left
     if (left != null) {
         queue.add(left) // safe cast succeeds

Which seems to be the first option provided by the accepted answer, but that's what you're looking for.

Add item to array in VBScript

this some kind of late but anyway and it is also somewhat tricky

 dim arrr 
  arr= array ("Apples", "Oranges", "Bananas")
 dim temp_var 
 temp_var = join (arr , "||") ' some character which will not occur is regular strings 
 if len(temp_var) > 0 then 
  temp_var = temp_var&"||Watermelons" 
end if 
arr  = split(temp_var , "||") ' here you got new elemet in array ' 
for each x in arr
response.write(x & "<br />")

review and tell me if this can work or initially you save all data in string and later split for array

What are the default color values for the Holo theme on Android 4.0?

If you want the default colors of Android ICS, you just have to go to your Android SDK and look for this path: platforms\android-15\data\res\values\colors.xml.

Here you go:

<!-- For holo theme -->
    <drawable name="screen_background_holo_light">#fff3f3f3</drawable>
    <drawable name="screen_background_holo_dark">#ff000000</drawable>
    <color name="background_holo_dark">#ff000000</color>
    <color name="background_holo_light">#fff3f3f3</color>
    <color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
    <color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
    <color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
    <color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
    <color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
    <color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
    <color name="dim_foreground_holo_dark">#bebebe</color>
    <color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
    <color name="dim_foreground_inverse_holo_dark">#323232</color>
    <color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
    <color name="hint_foreground_holo_dark">#808080</color>
    <color name="dim_foreground_holo_light">#323232</color>
    <color name="dim_foreground_disabled_holo_light">#80323232</color>
    <color name="dim_foreground_inverse_holo_light">#bebebe</color>
    <color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
    <color name="hint_foreground_holo_light">#808080</color>
    <color name="highlighted_text_holo_dark">#6633b5e5</color>
    <color name="highlighted_text_holo_light">#6633b5e5</color>
    <color name="link_text_holo_dark">#5c5cff</color>
    <color name="link_text_holo_light">#0000ee</color>

This for the Background:

<color name="background_holo_dark">#ff000000</color>
<color name="background_holo_light">#fff3f3f3</color>

You won't get the same colors if you look this up in Photoshop etc. because they are set up with Alpha values.

Update for API Level 19:

    <drawable name="screen_background_light">#ffffffff</drawable>
    <drawable name="screen_background_dark">#ff000000</drawable>
    <drawable name="status_bar_closed_default_background">#ff000000</drawable>
    <drawable name="status_bar_opened_default_background">#ff000000</drawable>
    <drawable name="notification_item_background_color">#ff111111</drawable>
    <drawable name="notification_item_background_color_pressed">#ff454545</drawable>
    <drawable name="search_bar_default_color">#ff000000</drawable>
    <drawable name="safe_mode_background">#60000000</drawable>
    <!-- Background drawable that can be used for a transparent activity to
         be able to display a dark UI: this darkens its background to make
         a dark (default theme) UI more visible. -->
    <drawable name="screen_background_dark_transparent">#80000000</drawable>
    <!-- Background drawable that can be used for a transparent activity to
         be able to display a light UI: this lightens its background to make
         a light UI more visible. -->
    <drawable name="screen_background_light_transparent">#80ffffff</drawable>
    <color name="safe_mode_text">#80ffffff</color>
    <color name="white">#ffffffff</color>
    <color name="black">#ff000000</color>
    <color name="transparent">#00000000</color>
    <color name="background_dark">#ff000000</color>
    <color name="background_light">#ffffffff</color>
    <color name="bright_foreground_dark">@android:color/background_light</color>
    <color name="bright_foreground_light">@android:color/background_dark</color>
    <color name="bright_foreground_dark_disabled">#80ffffff</color>
    <color name="bright_foreground_light_disabled">#80000000</color>
    <color name="bright_foreground_dark_inverse">@android:color/bright_foreground_light</color>
    <color name="bright_foreground_light_inverse">@android:color/bright_foreground_dark</color>
    <color name="dim_foreground_dark">#bebebe</color>
    <color name="dim_foreground_dark_disabled">#80bebebe</color>
    <color name="dim_foreground_dark_inverse">#323232</color>
    <color name="dim_foreground_dark_inverse_disabled">#80323232</color>
    <color name="hint_foreground_dark">#808080</color>
    <color name="dim_foreground_light">#323232</color>
    <color name="dim_foreground_light_disabled">#80323232</color>
    <color name="dim_foreground_light_inverse">#bebebe</color>
    <color name="dim_foreground_light_inverse_disabled">#80bebebe</color>
    <color name="hint_foreground_light">#808080</color>
    <color name="highlighted_text_dark">#9983CC39</color>
    <color name="highlighted_text_light">#9983CC39</color>
    <color name="link_text_dark">#5c5cff</color>
    <color name="link_text_light">#0000ee</color>
    <color name="suggestion_highlight_text">#177bbd</color>

    <drawable name="stat_notify_sync_noanim">@drawable/stat_notify_sync_anim0</drawable>
    <drawable name="stat_sys_download_done">@drawable/stat_sys_download_done_static</drawable>
    <drawable name="stat_sys_upload_done">@drawable/stat_sys_upload_anim0</drawable>
    <drawable name="dialog_frame">@drawable/panel_background</drawable>
    <drawable name="alert_dark_frame">@drawable/popup_full_dark</drawable>
    <drawable name="alert_light_frame">@drawable/popup_full_bright</drawable>
    <drawable name="menu_frame">@drawable/menu_background</drawable>
    <drawable name="menu_full_frame">@drawable/menu_background_fill_parent_width</drawable>
    <drawable name="editbox_dropdown_dark_frame">@drawable/editbox_dropdown_background_dark</drawable>
    <drawable name="editbox_dropdown_light_frame">@drawable/editbox_dropdown_background</drawable>

    <drawable name="dialog_holo_dark_frame">@drawable/dialog_full_holo_dark</drawable>
    <drawable name="dialog_holo_light_frame">@drawable/dialog_full_holo_light</drawable>

    <drawable name="input_method_fullscreen_background">#fff9f9f9</drawable>
    <drawable name="input_method_fullscreen_background_holo">@drawable/screen_background_holo_dark</drawable>
    <color name="input_method_navigation_guard">#ff000000</color>

    <!-- For date picker widget -->
    <drawable name="selected_day_background">#ff0092f4</drawable>

    <!-- For settings framework -->
    <color name="lighter_gray">#ddd</color>
    <color name="darker_gray">#aaa</color>

    <!-- For security permissions -->
    <color name="perms_dangerous_grp_color">#33b5e5</color>
    <color name="perms_dangerous_perm_color">#33b5e5</color>
    <color name="shadow">#cc222222</color>
    <color name="perms_costs_money">#ffffbb33</color>

    <!-- For search-related UIs -->
    <color name="search_url_text_normal">#7fa87f</color>
    <color name="search_url_text_selected">@android:color/black</color>
    <color name="search_url_text_pressed">@android:color/black</color>
    <color name="search_widget_corpus_item_background">@android:color/lighter_gray</color>

    <!-- SlidingTab -->
    <color name="sliding_tab_text_color_active">@android:color/black</color>
    <color name="sliding_tab_text_color_shadow">@android:color/black</color>

    <!-- keyguard tab -->
    <color name="keyguard_text_color_normal">#ffffff</color>
    <color name="keyguard_text_color_unlock">#a7d84c</color>
    <color name="keyguard_text_color_soundoff">#ffffff</color>
    <color name="keyguard_text_color_soundon">#e69310</color>
    <color name="keyguard_text_color_decline">#fe0a5a</color>

    <!-- keyguard clock -->
    <color name="lockscreen_clock_background">#ffffffff</color>
    <color name="lockscreen_clock_foreground">#ffffffff</color>
    <color name="lockscreen_clock_am_pm">#ffffffff</color>
    <color name="lockscreen_owner_info">#ff9a9a9a</color>

    <!-- keyguard overscroll widget pager -->
    <color name="kg_multi_user_text_active">#ffffffff</color>
    <color name="kg_multi_user_text_inactive">#ff808080</color>
    <color name="kg_widget_pager_gradient">#ffffffff</color>

    <!-- FaceLock -->
    <color name="facelock_spotlight_mask">#CC000000</color>

    <!-- For holo theme -->
      <drawable name="screen_background_holo_light">#fff3f3f3</drawable>
      <drawable name="screen_background_holo_dark">#ff000000</drawable>
    <color name="background_holo_dark">#ff000000</color>
    <color name="background_holo_light">#fff3f3f3</color>
    <color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
    <color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
    <color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
    <color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
    <color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
    <color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
    <color name="dim_foreground_holo_dark">#bebebe</color>
    <color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
    <color name="dim_foreground_inverse_holo_dark">#323232</color>
    <color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
    <color name="hint_foreground_holo_dark">#808080</color>
    <color name="dim_foreground_holo_light">#323232</color>
    <color name="dim_foreground_disabled_holo_light">#80323232</color>
    <color name="dim_foreground_inverse_holo_light">#bebebe</color>
    <color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
    <color name="hint_foreground_holo_light">#808080</color>
    <color name="highlighted_text_holo_dark">#6633b5e5</color>
    <color name="highlighted_text_holo_light">#6633b5e5</color>
    <color name="link_text_holo_dark">#5c5cff</color>
    <color name="link_text_holo_light">#0000ee</color>

    <!-- Group buttons -->
    <eat-comment />
    <color name="group_button_dialog_pressed_holo_dark">#46c5c1ff</color>
    <color name="group_button_dialog_focused_holo_dark">#2699cc00</color>

    <color name="group_button_dialog_pressed_holo_light">#ffffffff</color>
    <color name="group_button_dialog_focused_holo_light">#4699cc00</color>

    <!-- Highlight colors for the legacy themes -->
    <eat-comment />
    <color name="legacy_pressed_highlight">#fffeaa0c</color>
    <color name="legacy_selected_highlight">#fff17a0a</color>
    <color name="legacy_long_pressed_highlight">#ffffffff</color>

    <!-- General purpose colors for Holo-themed elements -->
    <eat-comment />

    <!-- A light Holo shade of blue -->
    <color name="holo_blue_light">#ff33b5e5</color>
    <!-- A light Holo shade of gray -->
    <color name="holo_gray_light">#33999999</color>
    <!-- A light Holo shade of green -->
    <color name="holo_green_light">#ff99cc00</color>
    <!-- A light Holo shade of red -->
    <color name="holo_red_light">#ffff4444</color>
    <!-- A dark Holo shade of blue -->
    <color name="holo_blue_dark">#ff0099cc</color>
    <!-- A dark Holo shade of green -->
    <color name="holo_green_dark">#ff669900</color>
    <!-- A dark Holo shade of red -->
    <color name="holo_red_dark">#ffcc0000</color>
    <!-- A Holo shade of purple -->
    <color name="holo_purple">#ffaa66cc</color>
    <!-- A light Holo shade of orange -->
    <color name="holo_orange_light">#ffffbb33</color>
    <!-- A dark Holo shade of orange -->
    <color name="holo_orange_dark">#ffff8800</color>
    <!-- A really bright Holo shade of blue -->
    <color name="holo_blue_bright">#ff00ddff</color>
    <!-- A really bright Holo shade of gray -->
    <color name="holo_gray_bright">#33CCCCCC</color>

    <drawable name="notification_template_icon_bg">#3333B5E5</drawable>
    <drawable name="notification_template_icon_low_bg">#0cffffff</drawable>

    <!-- Keyguard colors -->
    <color name="keyguard_avatar_frame_color">#ffffffff</color>
    <color name="keyguard_avatar_frame_shadow_color">#80000000</color>
    <color name="keyguard_avatar_nick_color">#ffffffff</color>
    <color name="keyguard_avatar_frame_pressed_color">#ff35b5e5</color>

    <color name="accessibility_focus_highlight">#80ffff00</color>

Using jquery to get all checked checkboxes with a certain class name

$('input.yourClass:checkbox:checked').each(function () {
    var sThisVal = $(this).val();

This would get all checkboxes of the class name "yourClass". I like this example since it uses the jQuery selector checked instead of doing a conditional check. Personally I would also use an array to store the value, then use them as needed, like:

var arr = [];
$('input.yourClass:checkbox:checked').each(function () {

CSS align one item right with flexbox

To align some elements (headerElement) in the center and the last element to the right (headerEnd).

.headerElement {
    margin-right: 5%;
    margin-left: 5%;
    margin-left: auto;

Set a form's action attribute when submitting?

You can try this:

<form action="/home">_x000D_
  <input type="submit" value="cancel">_x000D_
  <input type="submit" value="login" formaction="/login">_x000D_
  <input type="submit" value="signup" formaction="/signup">_x000D_

How to turn off Wifi via ADB?

Using "svc" through ADB (rooted required):


adb shell su -c 'svc wifi enable'


adb shell su -c 'svc wifi disable'

Using Key Events through ADB:

adb shell am start -a android.intent.action.MAIN -n
adb shell input keyevent 20 & adb shell input keyevent 23

The first line launch "wifi.WifiSettings" activity which open the WiFi Settings page. The second line simulate key presses.

I tested those two lines on a Droid X. But Key Events above probably need to edit in other devices because of different Settings layout.

More info about "keyevents" here.

How to get selected value of a html select with

You need to add a name to your <select> element:

<select id="testSelect" name="testSelect">

It will be posted to the server, and you can see it using:


ArrayList initialization equivalent to array initialization

How about this one.

ArrayList<String> names = new ArrayList<String>();
Collections.addAll(names, "Ryan", "Julie", "Bob");

A Windows equivalent of the Unix tail command

Graphical log viewers, while they might be very good for viewing log files, don't meet the need for a command line utility that can be incorporated into scripts (or batch files). Often such a simple and general-purpose command can be used as part of a specialized solution for a particular environment. Graphical methods don't lend themselves readily to such use.

Python unittest passing arguments

Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:

  • which of the dozen identical USB cards should I use for this test now?
  • which server should I use for this test now?
  • which XXX should I use?

For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.

Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)

import os
import unittest

class MyTest(unittest.TestCase):
    def setUp(self):
        self.var1 = os.environ["VAR1"]
        self.var2 = os.environ["VAR2"]

    def test_01(self):
        print("var1: {}, var2: {}".format(self.var1, self.var2))

Then from the command line (tested on Linux)

$ export VAR1=1
$ export VAR2=2
$ python -m unittest MyTest
var1: 1, var2: 2
Ran 1 test in 0.000s


How to change date format using jQuery?

You can use date.js to achieve this:

var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');

Alternatively, you can do it natively like this:

var dateAr = '2014-01-06'.split('-');_x000D_
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);_x000D_

.keyCode vs. .which

jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:

// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
   event.which = event.charCode != null ? event.charCode : event.keyCode;

An added benefit of .which is that jQuery does it for mouse clicks too:

// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
    event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));

Clicking HTML 5 Video element to play, pause video, breaks play button

I had this same problem and solved it by adding an event handler for the play action in addition to the click action. I hide the controls while playing to avoid the pause button issue.

    var v = document.getElementById('videoID');
          function() { 

    v.onclick = function() {
      if (v.paused) {;
      } else {

Seeking still acts funny though, but at least the confusion with the play control is gone. Hope this helps.

Anyone have a solution to that?

Why can't I define my workbook as an object?

You'll need to open the workbook to refer to it.

Sub Setwbk()

    Dim wbk As Workbook

    Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
        Master Benchmark Data Sheet.xlsx")

End Sub

* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:

Why do I have to "set" it?

Set is how VBA assigns object variables. Since a Range and a Workbook/Worksheet are objects, you must use Set with these.

How to use the COLLATE in a JOIN in SQL Server?

Correct syntax looks like this. See MSDN.

  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p

  ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS 

Using grep to search for hex strings in a file

There's also a pretty handy tool called binwalk, written in python, which provides for binary pattern matching (and quite a lot more besides). Here's how you would search for a binary string, which outputs the offset in decimal and hex (from the docs):

$ binwalk -R "\x00\x01\x02\x03\x04" firmware.bin
377654      0x5C336     Raw string signature

XAMPP installation on Win 8.1 with UAC Warning

change User Account Control setting via control panel

step 1 -: Go to control panel

step 2-: select 'user Accounts'

step 3-: select 'User Accounts' (Control Panel\User Accounts\User Accounts)

step 4 -: select 'Change User Account Control settings'

step 5 -: Drag the slider down to Never notify and after click ok.

Create a branch in Git from another branch

If you want create a new branch from any of the existing branches in Git, just follow the options.

First change/checkout into the branch from where you want to create a new branch. For example, if you have the following branches like:

  • master
  • dev
  • branch1

So if you want to create a new branch called "subbranch_of_b1" under the branch named "branch1" follow the steps:

  1. Checkout or change into "branch1"

    git checkout branch1
  2. Now create your new branch called "subbranch_of_b1" under the "branch1" using the following command.

    git checkout -b subbranch_of_b1 branch1

    The above will create a new branch called subbranch_of_b1 under the branch branch1 (note that branch1 in the above command isn't mandatory since the HEAD is currently pointing to it, you can precise it if you are on a different branch though).

  3. Now after working with the subbranch_of_b1 you can commit and push or merge it locally or remotely.

A sample Graphical Illustration Of Creating Branches Under another Branch

push the subbranch_of_b1 to remote

 git push origin subbranch_of_b1 

rails simple_form - hidden field - create?

try this

= f.input :title, :as => :hidden, :input_html => { :value => "some value" }

Why do we need the "finally" clause in Python?

They are not equivalent. Finally code is run no matter what else happens. It is useful for cleanup code that has to run.

Rename a dictionary key

In Python 3.6 (onwards?) I would go for the following one-liner

test = {'a': 1, 'old': 2, 'c': 3}
old_k = 'old'
new_k = 'new'
new_v = 4  # optional

print(dict((new_k, new_v) if k == old_k else (k, v) for k, v in test.items()))

which produces

{'a': 1, 'new': 4, 'c': 3}

May be worth noting that without the print statement the ipython console/jupyter notebook present the dictionary in an order of their choosing...

Circular (or cyclic) imports in Python

As other answers describe this pattern is acceptable in python:

def dostuff(self):
     from foo import bar

Which will avoid the execution of the import statement when the file is imported by other modules. Only if there is a logical circular dependency, this will fail.

Most Circular Imports are not actually logical circular imports but rather raise ImportError errors, because of the way import() evaluates top level statements of the entire file when called.

These ImportErrors can almost always be avoided if you positively want your imports on top:

Consider this circular import:

App A

# profiles/

from images.serializers import SimplifiedImageSerializer

class SimplifiedProfileSerializer(serializers.Serializer):
    name = serializers.CharField()

class ProfileSerializer(SimplifiedProfileSerializer):
    recent_images = SimplifiedImageSerializer(many=True)

App B

# images/

from profiles.serializers import SimplifiedProfileSerializer

class SimplifiedImageSerializer(serializers.Serializer):
    title = serializers.CharField()

class ImageSerializer(SimplifiedImageSerializer):
    profile = SimplifiedProfileSerializer()

From David Beazleys excellent talk Modules and Packages: Live and Let Die! - PyCon 2015, 1:54:00, here is a way to deal with circular imports in python:

    from images.serializers import SimplifiedImageSerializer
except ImportError:
    import sys
    SimplifiedImageSerializer = sys.modules[__package__ + '.SimplifiedImageSerializer']

This tries to import SimplifiedImageSerializer and if ImportError is raised, because it already is imported, it will pull it from the importcache.

PS: You have to read this entire post in David Beazley's voice.

How to install beautiful soup 4 with python 2.7 on windows

Install pip

Download get-pip. Remember to save it as ""

Now go to the download folder. Right click on then open with python.exe.

You can add system variable by

(by doing this you can use pip and easy_install without specifying path)

1 Clicking on Properties of My Computer

2 Then chose Advanced System Settings

3 Click on Advanced Tab

4 Click on Environment Variables

5 From System Variables >>> select variable path.

6 Click edit then add the following lines at the end of it


(please dont copy this, just go to your python directory and copy the paths similar to this)

NB:- you have to do this once only.

Install beautifulsoup4

Open cmd and type

pip install beautifulsoup4

spring PropertyPlaceholderConfigurer and context:property-placeholder

<context:property-placeholder ... /> is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The <util:properties/> simply factories a java.util.Properties instance that you can inject.

In Spring 3.1 (not 3.0...) you can do something like this:

public class ServiceConfiguration { 

    @Autowired Environment environment; 

    @Bean public javax.sql.DataSource dataSource( ){ 
        String user = this.environment.getProperty("ds.user");

In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:

@Value("${ds.user}") private String user;

If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:

public class MySpring3Configuration {     
        public static PropertyPlaceholderConfigurer configurer() { 
             PropertyPlaceholderConfigurer ppc = ...
             return ppc; 

        public class DataSource dataSource(
                @Value("${ds.user}") String user, 
                @Value("${}") String pw, 
                ...) { 
            DataSource ds = ...
            return ds;

Note that the PPC is defined using a static bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor - it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.

Does adding a duplicate value to a HashSet/HashMap replace the previous value

The first thing you need to know is that HashSet acts like a Set, which means you add your object directly to the HashSet and it cannot contain duplicates. You just add your value directly in HashSet.

However, HashMap is a Map type. That means every time you add an entry, you add a key-value pair.

In HashMap you can have duplicate values, but not duplicate keys. In HashMap the new entry will replace the old one. The most recent entry will be in the HashMap.

Understanding Link between HashMap and HashSet:

Remember, HashMap can not have duplicate keys. Behind the scene HashSet uses a HashMap.

When you attempt to add any object into a HashSet, this entry is actually stored as a key in the HashMap - the same HashMap that is used behind the scene of HashSet. Since this underlying HashMap needs a key-value pair, a dummy value is generated for us.

Now when you try to insert another duplicate object into the same HashSet, it will again attempt to be insert it as a key in the HashMap lying underneath. However, HashMap does not support duplicates. Hence, HashSet will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.


HashMap allows duplicate values, but not keys. HashSet cannot contains duplicates.

To play with whether the addition of an object is successfully completed or not, you can check the boolean value returned when you call .add() and see if it returns true or false. If it returned true, it was inserted.

Running Bash commands in Python

According to the error you are missing a package named swap on the server. This /usr/bin/cwm requires it. If you're on Ubuntu/Debian, install python-swap using aptitude.

Why is there no ForEach extension method on IEnumerable?

I've always wondered that myself, that is why that I always carry this with me:

public static void ForEach<T>(this IEnumerable<T> col, Action<T> action)
    if (action == null)
        throw new ArgumentNullException("action");
    foreach (var item in col)

Nice little extension method.

How to Parse JSON Array with Gson

Type listType = new TypeToken<List<Post>>() {}.getType();
List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType);

Is there a way to use max-width and height for a background image?

You can do this with background-size:

html {
    background: url(images/bg.jpg) no-repeat center center fixed; 
    background-size: cover;

There are a lot of values other than cover that you can set background-size to, see which one works for you:


It works in all modern browsers:

Converting integer to string in Python

For Python 3.6, you can use the f-strings new feature to convert to string and it's faster compared to str() function. It is used like this:

age = 45
strAge = f'{age}'

Python provides the str() function for that reason.

digit = 10
print(type(digit)) # Will show <class 'int'>
convertedDigit = str(digit)
print(type(convertedDigit)) # Will show <class 'str'>

For a more detailed answer, you can check this article: Converting Python Int to String and Python String to Int

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    float:left;/*Add float left*/
    margin :10px;

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.


What value could I insert into a bit type column?

If you're using SQL Server, you can set the value of bit fields with 0 and 1


'true' and 'false' (yes, using strings)

...your_bit_field='false'... => equivalent to 0

AttributeError: can't set attribute in python

items[node.ind] = items[node.ind]._replace(v=node.v)

(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")

Generate signed apk android studio

Read this my answer here

How do I export a project in the Android studio?

This will guide you step by step to generate signed APK and how to create keystore file from Android Studio.

From the link you can do it easily as I added the screenshot of it step by step.

Short answer

If you have Key-store file then you can do same simply.

Go to Build then click on Generate Signed APK