- Programming Questions & Answers Hub For Beginners

Some Of The Best Answers From Latest Asked Questions

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

How do I get the find command to print out the file size with the file name?

You need to use -exec or -printf. Printf works like this:

find . -name *.ear -printf "%p %k KB\n"

-exec is more powerful and lets you execute arbitrary commands - so you could use a version of 'ls' or 'wc' to print out the filename along with other information. 'man find' will show you the available arguments to printf, which can do a lot more than just filesize.

[edit] -printf is not in the official POSIX standard, so check if it is supported on your version. However, most modern systems will use GNU find or a similarly extended version, so there is a good chance it will be implemented.

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?


Where other assemblies that reference your assembly will look. If this number changes, other assemblies have to update their references to your assembly! Only update this version, if it breaks backward compatibility. The AssemblyVersion is required.

I use the format: major.minor. This would result in:

[assembly: AssemblyVersion("1.0")]

If you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc.


Used for deployment. You can increase this number for every deployment. It is used by setup programs. Use it to mark assemblies that have the same AssemblyVersion, but are generated from different builds.

In Windows, it can be viewed in the file properties.

The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.

I use the format:, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in:

[assembly: AssemblyFileVersion("")]

Be aware that System.Version names these parts as!


The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'.

The AssemblyInformationalVersion is optional. If not given, the AssemblyFileVersion is used.

I use the format: major.minor[.patch] [revision as string]. This would result in:

[assembly: AssemblyInformationalVersion("1.0 RC1")]

Sending mail from Python using SMTP

Also if you want to do smtp auth with TLS as opposed to SSL then you just have to change the port (use 587) and do smtp.starttls(). This worked for me:

smtp.connect('YOUR.MAIL.SERVER', 587)

WinForms DataGridView font size

I too experienced same problem in the DataGridView but figured out that the DefaultCell style was inheriting the font of the groupbox (Datagrid is placed in groupbox). So changing the font of the groupbox changed the DefaultCellStyle too.


Setting java locale settings

You could call during init or whatever Locale.setDefault() or -Duser.language=,, and -Duser.variant= at the command line. Here's something on Sun's site.

How do you make a deep copy of an object?

A few people have mentioned using or overriding Object.clone(). Don't do it. Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone.

The schemes that rely on serialization (XML or otherwise) are kludgy.

There is no easy answer here. If you want to deep copy an object you will have to traverse the object graph and copy each child object explicitly via the object's copy constructor or a static factory method that in turn deep copies the child object. Immutables (e.g. Strings) do not need to be copied. As an aside, you should favor immutability for this reason.

How do I use PHP to get the current year?

Get full Year used:

    echo $curr_year = date('Y'); // it will display full year ex. 2017

Or get only two digit of year used like this:

    echo $curr_year = date('y'); // it will display short 2 digit year ex. 17

Equivalent of *Nix 'which' command in PowerShell?

You can install the which command from, along with all of the other UNIX commands.

WPF Data Binding and Validation Rules Best Practices

Also check this article. Supposedly Microsoft released their Enterprise Library (v4.0) from their patterns and practices where they cover the validation subject but god knows why they didn't included validation for WPF, so the blog post I'm directing you to, explains what the author did to adapt it. Hope this helps!

How do I perform an IF...THEN in an SQL SELECT?

I like the use of the CASE statements but the question asked for an IF statement in the SQL Select. What I've used in the past has been:


   if(GENDER = "M","Male","Female") as Gender

FROM ...

It's like the excel or sheets IF statements where there is a conditional followed by the true condition and then the false condition:

if(condition, true, false)

Furthermore, you can nest the if statements (but then use should use a CASE :-)

(Note: this works in MySQLWorkbench but may not work in other platforms)

SQL: Select columns with NULL values only

Here is an updated version of Bryan's query for 2008 and later. It uses INFORMATION_SCHEMA.COLUMNS, adds variables for the table schema and table name. The column data type was added to the output. Including the column data type helps when looking for a column of a particular data type. I didn't added the column widths or anything.

For output the RAISERROR ... WITH NOWAIT is used so text will display immediately instead of all at once (for the most part) at the end like PRINT does.


 @ColumnName sysname
,@DataType nvarchar(128)
,@cmd nvarchar(max)
,@TableSchema nvarchar(128) = 'dbo'
,@TableName sysname = 'TableName';

    c.TABLE_SCHEMA = @TableSchema
    AND c.TABLE_NAME = @TableName;

OPEN getinfo;

FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;

    SET @cmd = N'IF NOT EXISTS (SELECT * FROM ' + @TableSchema + N'.' + @TableName + N' WHERE [' + @ColumnName + N'] IS NOT NULL) RAISERROR(''' + @ColumnName + N' (' + @DataType + N')'', 0, 0) WITH NOWAIT;';
    EXECUTE (@cmd);

    FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;

CLOSE getinfo;

How to determine CPU and memory consumption from inside a process?


Since this is like a "wikipage of code" I want to add some code from the QNX Knowledge base (note: this is not my work, but I checked it and it works fine on my system):

How to get CPU usage in %:

#include <atomic.h>
#include <libc.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/iofunc.h>
#include <sys/neutrino.h>
#include <sys/resmgr.h>
#include <sys/syspage.h>
#include <unistd.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/debug.h>
#include <sys/procfs.h>
#include <sys/syspage.h>
#include <sys/neutrino.h>
#include <sys/time.h>
#include <time.h>
#include <fcntl.h>
#include <devctl.h>
#include <errno.h>

#define MAX_CPUS 32

static float Loads[MAX_CPUS];
static _uint64 LastSutime[MAX_CPUS];
static _uint64 LastNsec[MAX_CPUS];
static int ProcFd = -1;
static int NumCpus = 0;

int find_ncpus(void) {
    return NumCpus;

int get_cpu(int cpu) {
    int ret;
    ret = (int)Loads[ cpu % MAX_CPUS ];
    ret = max(0,ret);
    ret = min(100,ret);
    return( ret );

static _uint64 nanoseconds( void ) {
    _uint64 sec, usec;
    struct timeval tval;
    gettimeofday( &tval, NULL );
    sec = tval.tv_sec;
    usec = tval.tv_usec;
    return( ( ( sec * 1000000 ) + usec ) * 1000 );

int sample_cpus( void ) {
    int i;
    debug_thread_t debug_data;
    _uint64 current_nsec, sutime_delta, time_delta;
    memset( &debug_data, 0, sizeof( debug_data ) );
    for( i=0; i<NumCpus; i++ ) {
        /* Get the sutime of the idle thread #i+1 */
        debug_data.tid = i + 1;
        devctl( ProcFd, DCMD_PROC_TIDSTATUS,
        &debug_data, sizeof( debug_data ), NULL );
        /* Get the current time */
        current_nsec = nanoseconds();
        /* Get the deltas between now and the last samples */
        sutime_delta = debug_data.sutime - LastSutime[i];
        time_delta = current_nsec - LastNsec[i];
        /* Figure out the load */
        Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );
        /* Flat out strange rounding issues. */
        if( Loads[i] < 0 ) {
            Loads[i] = 0;
        /* Keep these for reference in the next cycle */
        LastNsec[i] = current_nsec;
        LastSutime[i] = debug_data.sutime;
    return EOK;

int init_cpu( void ) {
    int i;
    debug_thread_t debug_data;
    memset( &debug_data, 0, sizeof( debug_data ) );
/* Open a connection to proc to talk over.*/
    ProcFd = open( "/proc/1/as", O_RDONLY );
    if( ProcFd == -1 ) {
        fprintf( stderr, "pload: Unable to access procnto: %s\n",strerror( errno ) );
        fflush( stderr );
        return -1;
    i = fcntl(ProcFd,F_GETFD);
    if(i != -1){
        i |= FD_CLOEXEC;
        if(fcntl(ProcFd,F_SETFD,i) != -1){
            /* Grab this value */
            NumCpus = _syspage_ptr->num_cpu;
            /* Get a starting point for the comparisons */
            for( i=0; i<NumCpus; i++ ) {
                * the sutime of idle thread is how much
                * time that thread has been using, we can compare this
                * against how much time has passed to get an idea of the
                * load on the system.
                debug_data.tid = i + 1;
                devctl( ProcFd, DCMD_PROC_TIDSTATUS, &debug_data, sizeof( debug_data ), NULL );
                LastSutime[i] = debug_data.sutime;
                LastNsec[i] = nanoseconds();

void close_cpu(void){
    if(ProcFd != -1){
        ProcFd = -1;

int main(int argc, char* argv[]){
    int i,j;
    printf("System has: %d CPUs\n", NumCpus);
    for(i=0; i<20; i++) {
        for(j=0; j<NumCpus;j++)
        printf("CPU #%d: %f\n", j, Loads[j]);

How to get the free (!) memory:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <err.h>
#include <sys/stat.h>
#include <sys/types.h>

int main( int argc, char *argv[] ){
    struct stat statbuf;
    paddr_t freemem;
    stat( "/proc", &statbuf );
    freemem = (paddr_t)statbuf.st_size;
    printf( "Free memory: %d bytes\n", freemem );
    printf( "Free memory: %d KB\n", freemem / 1024 );
    printf( "Free memory: %d MB\n", freemem / ( 1024 * 1024 ) );
    return 0;

What's the best way to build a string of delimited items in Java?

You can use Java's StringBuilder type for this. There's also StringBuffer, but it contains extra thread safety logic that is often unnecessary.

Microsoft SQL Server 2005 service fails to start

While that error message is on the screen (before the rollback begins) go to Control Panel -> Administrative Tools -> Services and see if the service is actually installed. Also check what account it is using to run as. If it's not using Local System, then double and triple check that the account it's using has rights to the program directory where MS SQL installed to. Connection reset

In my experience, I often encounter the following situations;

  1. If you work in a corporate company, contact the network and security team. Because in requests made to external services, it may be necessary to give permission for the relevant endpoint.

  2. Another issue is that the SSL certificate may have expired on the server where your application is running.

Difference between binary semaphore and mutex

You can clearly remember difference by this:

  1. Mutex lock : is for protecting critical region, Mutex can't be used across processes, only used in single process

  2. Semaphore: is for signalling availability of a resource. Semaphore can be used both across processes and across processes.

How do I check if a given string is a legal/valid file name under Windows?

From MSDN's "Naming a File or Directory," here are the general conventions for what a legal file name is under Windows:

You may use any character in the current code page (Unicode/ANSI above 127), except:

  • < > : " / \ | ? *
  • Characters whose integer representations are 0-31 (less than ASCII space)
  • Any other character that the target file system does not allow (say, trailing periods or spaces)
  • Any of the DOS names: CON, PRN, AUX, NUL, COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9 (and avoid AUX.txt, etc)
  • The file name is all periods

Some optional things to check:

  • File paths (including the file name) may not have more than 260 characters (that don't use the \?\ prefix)
  • Unicode file paths (including the file name) with more than 32,000 characters when using \?\ (note that prefix may expand directory components and cause it to overflow the 32,000 limit)

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

You need to fix your include_path system variable to point to the correct location.

To fix it edit the php.ini file. In that file you will find a line that says, "include_path = ...". (You can find out what the location of php.ini by running phpinfo() on a page.) Fix the part of the line that says, "\xampplite\php\pear\PEAR" to read "C:\xampplite\php\pear". Make sure to leave the semi-colons before and/or after the line in place.

Restart PHP and you should be good to go. To restart PHP in IIS you can restart the application pool assigned to your site or, better yet, restart IIS all together.

What is the best way to merge mp3 files?

Personally I would use something like mplayer with the audio pass though option eg -oac copy

How do I move a file (or folder) from one folder to another in TortoiseSVN?

As mentioned earlier, you'll create the add and delete commands. You can use svn move on both your working copy or the repository url. If you use your working copy, the changes won't be committed - you'll need to commit in a separate operation.

If you svn move a URL, you'll need to supply a --message, and the changes will be reflected in the repository immediately.

Ignore case in Python strings

Your question implies that you don't need Unicode. Try the following code snippet; if it works for you, you're done:

Python 2.5.2 (r252:60911, Aug 22 2008, 02:34:17)
[GCC 4.3.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> locale.setlocale(locale.LC_COLLATE, "en_US")
>>> sorted("ABCabc", key=locale.strxfrm)
['a', 'A', 'b', 'B', 'c', 'C']
>>> sorted("ABCabc", cmp=locale.strcoll)
['a', 'A', 'b', 'B', 'c', 'C']

Clarification: in case it is not obvious at first sight, locale.strcoll seems to be the function you need, avoiding the str.lower or locale.strxfrm "duplicate" strings.

Should I use int or Int32

ECMA-334:2006 C# Language Specification (p18):

Each of the predefined types is shorthand for a system-provided type. For example, the keyword int refers to the struct System.Int32. As a matter of style, use of the keyword is favoured over use of the complete system type name.

Deleting a file in VBA

set a reference to the Scripting.Runtime library and then use the FileSystemObject:

Dim fso as New FileSystemObject, aFile as File

if (fso.FileExists("PathToFile")) then
    aFile = fso.GetFile("PathToFile")
End if

How to clone all remote branches in Git?

For copy-paste into command line:

git checkout master ; remote=origin ; for brname in `git branch -r | grep $remote | grep -v master | grep -v HEAD | awk '{gsub(/^[^\/]+\//,"",$1); print $1}'`; do git branch -D $brname ; git checkout -b $brname $remote/$brname ; done ; git checkout master

For more readibility:

git checkout master ;
remote=origin ;
for brname in `
    git branch -r | grep $remote | grep -v master | grep -v HEAD 
    | awk '{gsub(/^[^\/]+\//,"",$1); print $1}'
`; do
    git branch -D $brname ;
    git checkout -b $brname $remote/$brname ;
done ;
git checkout master

This will:

  1. check out master (so that we can delete branch we are on)
  2. select remote to checkout (change it to whatever remote you have)
  3. loop through all branches of the remote except master and HEAD
    1. delete local branch (so that we can check out force-updated branches)
    2. check out branch from the remote
  4. check out master (for the sake of it)

Based on answer of VonC.

How to import a module given the full path?

You can also do something like this and add the directory that the configuration file is sitting in to the Python load path, and then just do a normal import, assuming you know the name of the file in advance, in this case "config".

Messy, but it works.

configfile = '~/'

import os
import sys


import config

What's the best free C++ profiler for Windows?

Proffy is quite cool:

Disclaimer: I wrote this.

Is Unit Testing worth the effort?

One of the benefits of unit testing is predictability.

Before unit testing I could have predicted to a great degree of accuracy how long it would take to code something, but not how how much time I would need to debug it.

These days, since I can plan what tests I am going to write, I know how long coding is going to take, and at the end of coding, the system is already debugged! This brings predictability to the development process, which remove a lot of the pressure but still retains all the joy!!.

How do you iterate through every file/directory recursively in standard C++?

You can use std::filesystem::recursive_directory_iterator. But beware, this includes symbolic (soft) links. If you want to avoid them you can use is_symlink. Example usage:

size_t directory_size(const std::filesystem::path& directory)
    size_t size{ 0 };
    for (const auto& entry : std::filesystem::recursive_directory_iterator(directory))
        if (entry.is_regular_file() && !entry.is_symlink())
            size += entry.file_size();
    return size;

Apple Cover-flow effect using jQuery or other library?

I tried using the the Jack's Asylum cover flow but it wouldn't let me easily remove and re-add an entire coverflow. I eventually found and not only is it more reliable, it's easier to hook into, uses less markup, and doesn't jitter when flipping through images. It's by far the best I've found, and I've tried several on this page.

How do I quickly rename a MySQL database (change schema name)?

The simplest method is to use HeidiSQL software. It's free and open source. It runs on Windows and on any Linux with Wine (run Windows applications on Linux, BSD, Solaris and Mac OS X).

To download HeidiSQL, goto

To download Wine, goto

To rename a database in HeidiSQL, just right click on the database name and select 'Edit'. Then enter a new name and press 'OK'.

It is so simple.

Tree data structure in C#

Because it isn't mentioned I would like you draw attention the now released .net code-base: specifically the code for a SortedSet that implements a Red-Black-Tree:

This is, however, a balanced tree structure. So my answer is more a reference to what I believe is the only native tree-structure in the .net core library.

When is a CDATA section necessary within a script tag?

A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) and you want to be able to write literal i<10 and a && b instead of i&lt;10 and a &amp;&amp; b, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will probably want to use a CDATA section.

Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue.

For a good writeup on the subject, see

Add a linebreak in an HTML text area

If you're inserting text from a database or such (which one usually do), convert all "<br />"'s to &vbCrLf. Works great for me :)

When does System.gc() do something?

Most JVMs will kick off a GC (depending on the -XX:DiableExplicitGC and -XX:+ExplicitGCInvokesConcurrent switch). But the specification is just less well defined in order to allow better implementations later on.

The spec needs clarification: Bug #6668279: (spec) System.gc() should indicate that we don't recommend use and don't guarantee behaviour

Internally the gc method is used by RMI and NIO, and they require synchronous execution, which: this is currently in discussion:

Bug #5025281: Allow System.gc() to trigger concurrent (not stop-the-world) full collections

How do you launch the JavaScript debugger in Google Chrome?

The most efficient way I have found to get to the javascript debugger is by running this:


What is the best way to implement constants in Java?

That is perfectly acceptable, probably even the standard.

(public/private) static final TYPE NAME = VALUE;

where TYPE is the type, NAME is the name in all caps with underscores for spaces, and VALUE is the constant value;

I highly recommend NOT putting your constants in their own classes or interfaces.

As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.

For example:

public static final Point ORIGIN = new Point(0,0);

public static void main(String[] args){

    ORIGIN.x = 3;


That is legal and ORIGIN would then be a point at (3, 0).

What's the easiest way to install a missing Perl module?

Also see Yes, even you can use CPAN. It shows how you can use CPAN without having root or sudo access.

Unit Testing C Code

Google has excellent testing framework.

And yes, as far as I see it will work with plain C, i.e. doesn't require C++ features (may require C++ compiler, not sure).

How to put text in the upper right, or lower right corner of a "box" using css

  #content { width: 300px; height: 300px; border: 1px solid black; position: relative; }
  .topright { position: absolute; top: 5px; right: 5px; text-align: right; }
  .bottomright { position: absolute; bottom: 5px; right: 5px; text-align: right; }
<div id="content">
  <div class="topright">here</div>
  <div class="bottomright">and here</div>
  Lorem ipsum etc................

Valid characters in a Java class name

You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...

Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.

An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

However, see this question for whether or not you should do that.

How do I set up Vim autoindentation properly for editing Python files?

Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.

In vim type

:help vimrc

and check your path to the _vimrc/.vimrc file with

:echo $HOME

:echo $VIM

Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.

:help source

IsNull function in DB2 SQL?

COALESCE function same ISNULL function Note. you must use COALESCE function with same data type of column that you check is null.

Does a finally block always get executed in Java?

The finally block is always executed unless there is abnormal program termination, either resulting from a JVM crash or from a call to System.exit(0).

On top of that, any value returned from within the finally block will override the value returned prior to execution of the finally block, so be careful of checking all exit points when using try finally.

Remove border from IFrame

1.Via Inline Style set border:0

 <iframe src="display_file.html" style="height: 400px; width:
   100%;border: 0;">HTML iFrame is not compatible with your browser

2. Via Tag Attribute frameBorder Set 0

<iframe src="display_file.html" width="300" height="300" frameborder="0">Browser not compatible.</iframe>

3. if We have multiple I Frame We can give class and Put css in internal or externally.


<iframe src="display_file.html" class="no_border_iframe">
    HTML iFrame is not compatible with your browser 


border: 0; /* or border:none; */

SQL Server 2005 How Create a Unique Constraint?

ALTER TABLE [TableName] ADD CONSTRAINT  [constraintName] UNIQUE ([columns])

Best way to convert text files between character sets?

As described on How do I correct the character encoding of a file? Synalyze It! lets you easily convert on OS X between all encodings supported by the ICU library.

Additionally you can display some bytes of a file translated to Unicode from all the encodings to see quickly which is the right one for your file.

Why aren't Xcode breakpoints functioning?

if you using Xcode Version 11.1 (11A1027) make sure you are not using the app store credential(provisioning profiles) , because in this case build will be installed and no log or debugger will work, it took me hell lot of time to figure it out , updated Xcode has chagned . now build getting installed on the device without any warning.

Error handling in Bash

Reading all the answers on this page inspired me a lot.

So, here's my hint:

file content:




if test "${g_libs[$lib_name]+_}"; then
    return 0
    if test ${#g_libs[@]} == 0; then
        declare -A g_libs


set -o pipefail  # trace ERR through pipes
set -o errtrace  # trace ERR through 'time command' and other functions
set -o nounset   ## set -u : exit the script if you try to use an uninitialised variable
set -o errexit   ## set -e : exit the script if any statement returns a non-true return value

exec 2>"$stderr_log"


function exit_handler ()
    local error_code="$?"

    test $error_code == 0 && return;

    # ------------------------------------------------------------------
    local i=0
    local regex=''
    local mem=''

    local error_file=''
    local error_lineno=''
    local error_message='unknown'

    local lineno=''

    # ------------------------------------------------------------------
    # Color the output if it's an interactive terminal
    test -t 1 && tput bold; tput setf 4                                 ## red bold
    echo -e "\n(!) EXIT HANDLER:\n"

    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #

    # Read last file from the error log
    # ------------------------------------------------------------------
    if test -f "$stderr_log"
            stderr=$( tail -n 1 "$stderr_log" )
            rm "$stderr_log"

    # Managing the line to extract information:
    # ------------------------------------------------------------------

    if test -n "$stderr"
            # Exploding stderr on :
            local shrunk_stderr=$( echo "$stderr" | sed 's/\: /\:/g' )
            local stderr_parts=( $shrunk_stderr )

            # Storing information on the error

            for (( i = 3; i <= ${#stderr_parts[@]}; i++ ))
                    error_message="$error_message "${stderr_parts[$i-1]}": "

            # Removing last ':' (colon character)

            # Trim
            error_message="$( echo "$error_message" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//' )"

    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
    _backtrace=$( backtrace 2 )

    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #

    local lineno=""
    regex='^([a-z]{1,}) ([0-9]{1,})$'

    if [[ $error_lineno =~ $regex ]]

        # The error line was found on the log
        # (e.g. type 'ff' without quotes wherever)
        # --------------------------------------------------------------
            local row="${BASH_REMATCH[1]}"

            echo -e "FILE:\t\t${error_file}"
            echo -e "${row^^}:\t\t${lineno}\n"

            echo -e "ERROR CODE:\t${error_code}"             
            test -t 1 && tput setf 6                                    ## white yellow
            echo -e "ERROR MESSAGE:\n$error_message"

            if [[ "$_backtrace" =~ $regex ]]

                # The file was found on the log but not the error line
                # (could not reproduce this case so far)
                # ------------------------------------------------------
                    echo -e "FILE:\t\t$error_file"
                    echo -e "ROW:\t\tunknown\n"

                    echo -e "ERROR CODE:\t${error_code}"
                    test -t 1 && tput setf 6                            ## white yellow
                    echo -e "ERROR MESSAGE:\n${stderr}"

                # Neither the error line nor the error file was found on the log
                # (e.g. type 'cp ffd fdf' without quotes wherever)
                # ------------------------------------------------------
                    # The error file is the first on backtrace list:

                    # Exploding backtrace on newlines
                    # Substring: I keep only the carriage return
                    # (others needed only for tabbing purpose)
                    local lines=( $_backtrace )



                    if test -n "${lines[1]}"
                            array=( ${lines[1]} )

                            for (( i=2; i<${#array[@]}; i++ ))
                                    error_file="$error_file ${array[$i]}"

                            # Trim
                            error_file="$( echo "$error_file" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//' )"

                    echo -e "FILE:\t\t$error_file"
                    echo -e "ROW:\t\tunknown\n"

                    echo -e "ERROR CODE:\t${error_code}"
                    test -t 1 && tput setf 6                            ## white yellow
                    if test -n "${stderr}"
                            echo -e "ERROR MESSAGE:\n${stderr}"
                            echo -e "ERROR MESSAGE:\n${error_message}"

    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #

    test -t 1 && tput setf 7                                            ## white bold
    echo -e "\n$_backtrace\n"

    # EXITING:
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #

    test -t 1 && tput setf 4                                            ## red bold
    echo "Exiting!"

    test -t 1 && tput sgr0 # Reset terminal

    exit "$error_code"
trap exit_handler EXIT                                                  # ! ! ! TRAP EXIT ! ! !
trap exit ERR                                                           # ! ! ! TRAP ERR ! ! !


function backtrace
    local _start_from_=0

    local params=( "$@" )
    if (( "${#params[@]}" >= "1" ))

    local i=0
    local first=false
    while caller $i > /dev/null
        if test -n "$_start_from_" && (( "$i" + 1   >= "$_start_from_" ))
                if test "$first" == false
                        echo "BACKTRACE IS:"
                caller $i
        let "i=i+1"

return 0

Example of usage:
file content:


source ''

echo "doing something wrong now .."
echo "$foo"

exit 0




doing something wrong now ..


LINE:       6

foo:   unassigned variable

1 main


As you can see from the screenshot below, the output is colored and the error message comes in the used language.

enter image description here

How do you append an int to a string in C++?

cout << text << " " << i << endl;

'^M' character at end of lines

It's caused by the DOS/Windows line-ending characters. Like Andy Whitfield said, the Unix command dos2unix will help fix the problem. If you want more information, you can read the man pages for that command.

What are valid values for the id attribute in HTML?

Hyphens, underscores, periods, colons, numbers and letters are all valid for use with CSS and JQuery. The following should work but it must be unique throughout the page and also must start with a letter [A-Za-z].

Working with colons and periods needs a bit more work but you can do it as the following example shows.

<style type="text/css">
    #i\.Really\.Like\.Cake {
        color: green;
    #i\:Really\:Like\:Cake {
        color: blue;
    <div id="i.Really.Like.Cake">Cake</div>
    <div id="testResultPeriod"></div>

    <div id="i:Really:Like:Cake">Cake</div>
    <div id="testResultColon"></div>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        $(function() {
            var testPeriod = $("#i\\.Really\\.Like\\.Cake");
            $("#testResultPeriod").html("found " + testPeriod.length + " result.");

            var testColon = $("#i\\:Really\\:Like\\:Cake");
            $("#testResultColon").html("found " + testColon.length + " result.");

Why are Python's 'private' methods not actually private?

Why are Python's 'private' methods not actually private?

As I understand it, they can't be private. How could privacy be enforced?

The obvious answer is "private members can only be accessed through self", but that wouldn't work - self is not special in Python, it is nothing more than a commonly-used name for the first parameter of a function.

Does C# have a String Tokenizer like Java's?

_words = new List<string>(YourText.ToLower().Trim('\n', '\r').Split(' ').
            Select(x => new string(x.Where(Char.IsLetter).ToArray()))); 


_words = new List<string>(YourText.Trim('\n', '\r').Split(' ').
            Select(x => new string(x.Where(Char.IsLetterOrDigit).ToArray()))); 

Why is quicksort better than mergesort?

Small additions to quick vs merge sorts.

Also it can depend on kind of sorting items. If access to items, swap and comparisons is not simple operations, like comparing integers in plane memory, then merge sort can be preferable algorithm.

For example , we sort items using network protocol on remote server.

Also, in custom containers like "linked list", the are no benefit of quick sort.
1. Merge sort on linked list, don't need additional memory. 2. Access to elements in quick sort is not sequential (in memory)

Java inner class and static nested class

In simple terms we need nested classes primarily because Java does not provide closures.

Nested Classes are classes defined inside the body of another enclosing class. They are of two types - static and non-static.

They are treated as members of the enclosing class, hence you can specify any of the four access specifiers - private, package, protected, public. We don't have this luxury with top-level classes, which can only be declared public or package-private.

Inner classes aka Non-stack classes have access to other members of the top class, even if they are declared private while Static nested classes do not have access to other members of the top class.

public class OuterClass {
    public static class Inner1 {
    public class Inner2 {

Inner1 is our static inner class and Inner2 is our inner class which is not static. The key difference between them, you can't create an Inner2 instance without an Outer where as you can create an Inner1 object independently.

When would you use Inner class?

Think of a situation where Class A and Class B are related, Class B needs to access Class A members, and Class B is related only to Class A. Inner classes comes into the picture.

For creating an instance of inner class, you need to create an instance of your outer class.

OuterClass outer = new OuterClass();
OuterClass.Inner2 inner = Inner2();


OuterClass.Inner2 inner = new OuterClass().new Inner2();

When would you use static Inner class?

You would define a static inner class when you know that it does not have any relationship with the instance of the enclosing class/top class. If your inner class doesn't use methods or fields of the outer class, it's just a waste of space, so make it static.

For example, to create an object for the static nested class, use this syntax:

OuterClass.Inner1 nestedObject = new OuterClass.Inner1();

The advantage of a static nested class is that it doesn't need an object of the containing class/top class to work. This can help you to reduce the number of objects your application creates at runtime.

Single Form Hide on Startup

Usually you would only be doing this when you are using a tray icon or some other method to display the form later, but it will work nicely even if you never display your main form.

Create a bool in your Form class that is defaulted to false:

private bool allowshowdisplay = false;

Then override the SetVisibleCore method

protected override void SetVisibleCore(bool value)
    base.SetVisibleCore(allowshowdisplay ? value : allowshowdisplay);

Because Application.Run() sets the forms .Visible = true after it loads the form this will intercept that and set it to false. In the above case, it will always set it to false until you enable it by setting allowshowdisplay to true.

Now that will keep the form from displaying on startup, now you need to re-enable the SetVisibleCore to function properly by setting the allowshowdisplay = true. You will want to do this on whatever user interface function that displays the form. In my example it is the left click event in my notiyicon object:

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
        this.allowshowdisplay = true;
        this.Visible = !this.Visible;                

What's the purpose of META-INF?

You can also place static resources in there.

In example:


and get them in web3.0-container via


> Read more

The /META-INF/MANIFEST.MF has a special meaning:

  1. If you run a jar using java -jar myjar.jar org.myserver.MyMainClass you can move the main class definition into the jar so you can shrink the call into java -jar myjar.jar.
  2. You can define Metainformations to packages if you use java.lang.Package.getPackage("org.myserver").getImplementationTitle().
  3. You can reference digital certificates you like to use in Applet/Webstart mode.

How to Detect if I'm Compiling Code with a particular Visual Studio version?

This is a little old but should get you started:

// Automated platform detection

// _WIN32 is used by
// Visual C++
#ifdef _WIN32
#define __NT__

// Define __MAC__ platform indicator
#ifdef macintosh
#define __MAC__

// Define __OSX__ platform indicator
#ifdef __APPLE__
#define __OSX__

// Define __WIN16__ platform indicator 
#ifdef _Windows_
#ifndef __NT__
#define __WIN16__

// Define Windows CE platform indicator
#define __WINCE__

#if (_WIN32_WCE == 300) // for Pocket PC
#define __POCKETPC__
#define __WINCE__
//#if (_WIN32_WCE == 211) // for Palm-size PC 2.11 (Wyvern)
//#if (_WIN32_WCE == 201) // for Palm-size PC 2.01 (Gryphon)  
//#ifdef WIN32_PLATFORM_HPC2000 // for H/PC 2000 (Galileo)

Set 4 Space Indent in Emacs in Text Mode

(setq tab-width 4)
(setq tab-stop-list '(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80))
(setq indent-tabs-mode nil)

Why don't self-closing script elements work?

The self closing script tag won't work, because the script tag can contain inline code, and HTML is not smart enough to turn on or off that feature based on the presence of an attribute.

On the other hand, HTML does have an excellent tag for including references to outside resources: the <link> tag, and it can be self-closing. It's already used to include stylesheets, RSS and Atom feeds, canonical URIs, and all sorts of other goodies. Why not JavaScript?

If you want the script tag to be self enclosed you can't do that as I said, but there is an alternative, though not a smart one. You can use the self closing link tag and link to your JavaScript by giving it a type of text/javascript and rel as script, something like below:

<link type="text/javascript" rel ="script" href="/path/tp/javascript" />

Factory Pattern. When to use factory methods?

It's really a matter of taste. Factory classes can be abstracted/interfaced away as necessary, whereas factory methods are lighter weight (and also tend to be testable, since they don't have a defined type, but they will require a well-known registration point, akin to a service locator but for locating factory methods).

Take a screenshot via a Python script on Linux

Compile all answers in one class. Outputs PIL image.

#!/usr/bin/env python
# encoding: utf-8

Created by Alex Snet on 2011-10-10.
Copyright (c) 2011 CodeTeam. All rights reserved.

import sys
import os

import Image

class screengrab:
    def __init__(self):
            import gtk
        except ImportError:
            self.screen = self.getScreenByGtk

            import PyQt4
        except ImportError:
            self.screen = self.getScreenByQt

            import wx
        except ImportError:
            self.screen = self.getScreenByWx

            import ImageGrab
        except ImportError:
            self.screen = self.getScreenByPIL

    def getScreenByGtk(self):
        import gtk.gdk      
        w = gtk.gdk.get_default_root_window()
        sz = w.get_size()
        pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
        pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
        if pb is None:
            return False
            width,height = pb.get_width(),pb.get_height()
            return Image.fromstring("RGB",(width,height),pb.get_pixels() )

    def getScreenByQt(self):
        from PyQt4.QtGui import QPixmap, QApplication
        from PyQt4.Qt import QBuffer, QIODevice
        import StringIO
        app = QApplication(sys.argv)
        buffer = QBuffer()
        QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')
        strio = StringIO.StringIO()
        del app

    def getScreenByPIL(self):
        import ImageGrab
        img = ImageGrab.grab()
        return img

    def getScreenByWx(self):
        import wx
        wx.App()  # Need to create an App instance before doing anything
        screen = wx.ScreenDC()
        size = screen.GetSize()
        bmp = wx.EmptyBitmap(size[0], size[1])
        mem = wx.MemoryDC(bmp)
        mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
        del mem  # Release bitmap
        #bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
        myWxImage = wx.ImageFromBitmap( myBitmap )
        PilImage = 'RGB', (myWxImage.GetWidth(), myWxImage.GetHeight()) )
        PilImage.fromstring( myWxImage.GetData() )
        return PilImage

if __name__ == '__main__':
    s = screengrab()
    screen = s.screen()

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

All of the correct CSS variations are:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

Remote Linux server to remote linux server dir copy. How?

I used rdiffbackup because it does all you need without any fancy options. It's based on the rsync algorithm. If you only need to copy one time, you can later remove the rdiff-backup-data directory on the destination host.

rdiff-backup user1@host1::/source-dir user2@host2::/dest-dir

from the doc:

rdiff-backup also preserves subdirectories, hard links, dev files, permissions, uid/gid ownership, modification times, extended attributes, acls, and resource forks.

which is an bonus to the scp -p proposals as the -p option does not preserve all (e.g. rights on directories are set badly)

install on ubuntu:

sudo apt-get install rdiff-backup

Is there a way to programmatically minimize a window

this.MdiParent.WindowState = FormWindowState.Minimized;

Tracking CPU and Memory usage per process

Using perfmon.exe, I have tried using the "Private Bytes" counter under "Process" counters for tracking memory usage and it works well.

Biggest differences of Thrift vs Protocol Buffers?

  • Protobuf serialized objects are about 30% smaller than Thrift.
  • Most actions you may want to do with protobuf objects (create, serialize, deserialize) are much slower than thrift unless you turn on option optimize_for = SPEED.
  • Thrift has richer data structures (Map, Set)
  • Protobuf API looks cleaner, though the generated classes are all packed as inner classes which is not so nice.
  • Thrift enums are not real Java Enums, i.e. they are just ints. Protobuf has real Java enums.

For a closer look at the differences, check out the source code diffs at this open source project.

How to implement a queue using two stacks?

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.

pop() -- Removes the element from in front of queue.

peek() -- Get the front element.

empty() -- Return whether the queue is empty.

enter image description here

class MyQueue {

  Stack<Integer> input;
  Stack<Integer> output;

  /** Initialize your data structure here. */
  public MyQueue() {
    input = new Stack<Integer>();
    output = new Stack<Integer>();

  /** Push element x to the back of queue. */
  public void push(int x) {

  /** Removes the element from in front of queue and returns that element. */
  public int pop() {
    return output.pop();

  /** Get the front element. */
  public int peek() {
    if(output.isEmpty()) {
        while(!input.isEmpty()) {
    return output.peek();

  /** Returns whether the queue is empty. */
  public boolean empty() {
    return input.isEmpty() && output.isEmpty();

Split long commands in multiple lines through Windows batch file

(This is basically a rewrite of Wayne's answer but with the confusion around the caret cleared up. So I've posted it as a CW. I'm not shy about editing answers, but completely rewriting them seems inappropriate.)

You can break up long lines with the caret (^), just remember that the caret and the newline that follows it are removed entirely from the command, so if you put it where a space would be required (such as between parameters), be sure to include the space as well (either before the ^, or at the beginning of the next line — that latter choice may help make it clearer it's a continuation).

Examples: (all tested on Windows XP and Windows 7)

xcopy file1.txt file2.txt

can be written as:



xcopy ^
file1.txt ^

or even

opy ^
file1.txt ^

(That last works because there are no spaces betwen the xc and the ^, and no spaces at the beginning of the next line. So when you remove the ^ and the newline, you get...xcopy.)

For readability and sanity, it's probably best breaking only between parameters (be sure to include the space).

Be sure that the ^ is not the last thing in a batch file, as there appears to be a major issue with that.

Are static class variables possible in Python?

@Blair Conrad said static variables declared inside the class definition, but not inside a method are class or "static" variables:

>>> class Test(object):
...     i = 3
>>> Test.i

There are a few gotcha's here. Carrying on from the example above:

>>> t = Test()
>>> t.i     # "static" variable accessed via instance
>>> t.i = 5 # but if we assign to the instance ...
>>> Test.i  # we have not changed the "static" variable
>>> t.i     # we have overwritten Test.i on t by creating a new attribute t.i
>>> Test.i = 6 # to change the "static" variable we do it by assigning to the class
>>> t.i
>>> Test.i
>>> u = Test()
>>> u.i
6           # changes to t do not affect new instances of Test

# Namespaces are one honking great idea -- let's do more of those!
>>> Test.__dict__
{'i': 6, ...}
>>> t.__dict__
{'i': 5}
>>> u.__dict__

Notice how the instance variable t.i got out of sync with the "static" class variable when the attribute i was set directly on t. This is because i was re-bound within the t namespace, which is distinct from the Test namespace. If you want to change the value of a "static" variable, you must change it within the scope (or object) where it was originally defined. I put "static" in quotes because Python does not really have static variables in the sense that C++ and Java do.

Although it doesn't say anything specific about static variables or methods, the Python tutorial has some relevant information on classes and class objects.

@Steve Johnson also answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.

class Test(object):
    def f(arg1, arg2, ...):

@beid also mentioned classmethod, which is similar to staticmethod. A classmethod's first argument is the class object. Example:

class Test(object):
    i = 3 # class (or static) variable
    def g(cls, arg):
        # here we can use 'cls' instead of the class name (Test)
        if arg > cls.i:
            cls.i = arg # would be the same as Test.i = arg1

Pictorial Representation Of Above Example

How to parse a query string into a NameValueCollection in .NET

Just access Request.QueryString. AllKeys mentioned as another answer just gets you an array of keys.

How do I drag and drop files into an application?

Yet another gotcha:

The framework code that calls the Drag-events swallow all exceptions. You might think your event code is running smoothly, while it is gushing exceptions all over the place. You can't see them because the framework steals them.

That's why I always put a try/catch in these event handlers, just so I know if they throw any exceptions. I usually put a Debugger.Break(); in the catch part.

Before release, after testing, if everything seems to behave, I remove or replace these with real exception handling.

Multiple cases in switch statement

Actually I don't like the GOTO command too, but it's in official Microsoft materials, and here are all allowed syntaxes.

If the end point of the statement list of a switch section is reachable, a compile-time error occurs. This is known as the "no fall through" rule. The example

switch (i) {
case 0:
case 1:

is valid because no switch section has a reachable end point. Unlike C and C++, execution of a switch section is not permitted to "fall through" to the next switch section, and the example

switch (i) {
case 0:
case 1:

results in a compile-time error. When execution of a switch section is to be followed by execution of another switch section, an explicit goto case or goto default statement must be used:

switch (i) {
case 0:
   goto case 1;
case 1:
   goto default;

Multiple labels are permitted in a switch-section. The example

switch (i) {
case 0:
case 1:
case 2:

I believe in this particular case, the GOTO can be used, and it's actually the only way to fallthrough.


How to show loading spinner in jQuery?


$.listen('click', '#captcha', function() {
    $('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />');
    $.get("/captcha/new", null, function(data) {
    return false;


#loading { background: url(/image/loading.gif) no-repeat center; }

Send file using POST from a Python script

Yes. You'd use the urllib2 module, and encode using the multipart/form-data content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:

user_agent = "image uploader"
default_message = "Image $current of $total"

import logging
import os
from os.path import abspath, isabs, isdir, isfile, join
import random
import string
import sys
import mimetypes
import urllib2
import httplib
import time
import re

def random_string (length):
    return ''.join (random.choice (string.letters) for ii in range (length + 1))

def encode_multipart_data (data, files):
    boundary = random_string (30)

    def get_content_type (filename):
        return mimetypes.guess_type (filename)[0] or 'application/octet-stream'

    def encode_field (field_name):
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"' % field_name,
                '', str (data [field_name]))

    def encode_file (field_name):
        filename = files [field_name]
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename),
                'Content-Type: %s' % get_content_type(filename),
                '', open (filename, 'rb').read ())

    lines = []
    for name in data:
        lines.extend (encode_field (name))
    for name in files:
        lines.extend (encode_file (name))
    lines.extend (('--%s--' % boundary, ''))
    body = '\r\n'.join (lines)

    headers = {'content-type': 'multipart/form-data; boundary=' + boundary,
               'content-length': str (len (body))}

    return body, headers

def send_post (url, data, files):
    req = urllib2.Request (url)
    connection = httplib.HTTPConnection (req.get_host ())
    connection.request ('POST', req.get_selector (),
                        *encode_multipart_data (data, files))
    response = connection.getresponse ()
    logging.debug ('response = %s', ())
    logging.debug ('Code: %s %s', response.status, response.reason)

def make_upload_file (server, thread, delay = 15, message = None,
                      username = None, email = None, password = None):

    delay = max (int (delay or '0'), 15)

    def upload_file (path, current, total):
        assert isabs (path)
        assert isfile (path)

        logging.debug ('Uploading %r to %r', path, server)
        message_template = string.Template (message or default_message)

        data = {'MAX_FILE_SIZE': '3145728',
                'sub': '',
                'mode': 'regist',
                'com': message_template.safe_substitute (current = current, total = total),
                'resto': thread,
                'name': username or '',
                'email': email or '',
                'pwd': password or random_string (20),}
        files = {'upfile': path}

        send_post (server, data, files) ('Uploaded %r', path)
        rand_delay = random.randint (delay, delay + 5)
        logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay)
        time.sleep (rand_delay)

    return upload_file

def upload_directory (path, upload_file):
    assert isabs (path)
    assert isdir (path)

    matching_filenames = []
    file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE)

    for dirpath, dirnames, filenames in os.walk (path):
        for name in filenames:
            file_path = join (dirpath, name)
            logging.debug ('Testing file_path %r', file_path)
            if (file_path):
                matching_filenames.append (file_path)
       ('Ignoring non-image file %r', path)

    total_count = len (matching_filenames)
    for index, file_path in enumerate (matching_filenames):
        upload_file (file_path, index + 1, total_count)

def run_upload (options, paths):
    upload_file = make_upload_file (**options)

    for arg in paths:
        path = abspath (arg)
        if isdir (path):
            upload_directory (path, upload_file)
        elif isfile (path):
            upload_file (path)
            logging.error ('No such path: %r' % path) ('Done!')

How to copy a file to a remote server in Python using SCP or SSH?

You can do something like this, to handle the host key checking as well

import os
os.system("sshpass -p password scp -o StrictHostKeyChecking=no local_file_path username@hostname:remote_path")

View/edit ID3 data for MP3 files

I wrapped mp3 decoder library and made it available for .net developers. You can find it here:

Included are the samples to convert mp3 file to PCM, and read ID3 tags.

JavaScript to scroll long page to DIV

scrollTop (IIRC) is where in the document the top of the page is scrolled to. scrollTo scrolls the page so that the top of the page is where you specify.

What you need here is some Javascript manipulated styles. Say if you wanted the div off-screen and scroll in from the right you would set the left attribute of the div to the width of the page and then decrease it by a set amount every few seconds until it is where you want.

This should point you in the right direction.

Additional: I'm sorry, I thought you wanted a separate div to 'pop out' from somewhere (sort of like this site does sometimes), and not move the entire page to a section. Proper use of anchors would achieve that effect.

How to create a windows service from java app

I always just use sc.exe (see It should be installed on XP from SP1, and if it's not in your flavor of Vista, you can download load it with the Vista resource kit.

I haven't done anything too complicated with Java, but using either a fully qualified command line argument (x:\java.exe ....) or creating a script with Ant to include depencies and set parameters works fine for me.

How to create batch file in Windows using "start" with a path and command with spaces

Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.

Auto number column in SharePoint list

If you want something beyond the ID column that's there in all lists, you're probably going to have to resort to an Event Receiver on the list that "calculates" what the value of your unique identified should be or using a custom field type that has the required logic embedded in this. Unfortunately, both of these options will require writing and deploying custom code to the server and deploying assemblies to the GAC, which can be frowned upon in environments where you don't have complete control over the servers.

If you don't need the unique identifier to show up immediately, you could probably generate it via a workflow (either with SharePoint Designer or a custom WF workflow built in Visual Studio).

Unfortunately, calculated columns, which seem like an obvious solution, won't work for this purpose because the ID is not yet assigned when the calculation is attempted. If you go in after the fact and edit the item, the calculation may achieve what you want, but on initial creation of a new item it will not be calculated correctly.

Should I add the Visual Studio .suo and .user files to source control?

I wouldn't. Anything that could change per "user" is usually not good in source control. .suo, .user, obj/bin directories

Recursion or Iteration?

I'm going to answer your question by designing a Haskell data structure by "induction", which is a sort of "dual" to recursion. And then I will show how this duality leads to nice things.

We introduce a type for a simple tree:

data Tree a = Branch (Tree a) (Tree a)
            | Leaf a
            deriving (Eq)

We can read this definition as saying "A tree is a Branch (which contains two trees) or is a leaf (which contains a data value)". So the leaf is a sort of minimal case. If a tree isn't a leaf, then it must be a compound tree containing two trees. These are the only cases.

Let's make a tree:

example :: Tree Int
example = Branch (Leaf 1) 
                 (Branch (Leaf 2) 
                         (Leaf 3))

Now, let's suppose we want to add 1 to each value in the tree. We can do this by calling:

addOne :: Tree Int -> Tree Int
addOne (Branch a b) = Branch (addOne a) (addOne b)
addOne (Leaf a)     = Leaf (a + 1)

First, notice that this is in fact a recursive definition. It takes the data constructors Branch and Leaf as cases (and since Leaf is minimal and these are the only possible cases), we are sure that the function will terminate.

What would it take to write addOne in an iterative style? What will looping into an arbitrary number of branches look like?

Also, this kind of recursion can often be factored out, in terms of a "functor". We can make Trees into Functors by defining:

instance Functor Tree where fmap f (Leaf a)     = Leaf (f a)
                            fmap f (Branch a b) = Branch (fmap f a) (fmap f b)

and defining:

addOne' = fmap (+1)

We can factor out other recursion schemes, such as the catamorphism (or fold) for an algebraic data type. Using a catamorphism, we can write:

addOne'' = cata go where
           go (Leaf a) = Leaf (a + 1)
           go (Branch a b) = Branch a b

How do I Validate the File Type of a File Upload?

As an alternative option, could you use the "accept" attribute of HTML File Input which defines which MIME types are acceptable.

Definition here

Forward declaring an enum in C++

If you really don't want your enum to appear in your header file AND ensure that it is only used by private methods, then one solution can be to go with the pimpl principle.

It's a technique that ensure to hide the class internals in the headers by just declaring:

class A 
    void* pImpl;

Then in your implementation file (cpp), you declare a class that will be the representation of the internals.

class AImpl
    AImpl(A* pThis): m_pThis(pThis) {}

    ... all private methods here ...
    A* m_pThis;

You must dynamically create the implementation in the class constructor and delete it in the destructor and when implementing public method, you must use:


There are pros for using pimpl, one is that it decouple your class header from its implementation, no need to recompile other classes when changing one class implementation. Another is that is speeds up your compilation time because your headers are so simple.

But it's a pain to use, so you should really ask yourself if just declaring your enum as private in the header is that much a trouble.

How to replace a character by a newline in Vim

In the syntax s/foo/bar, \r and \n have different meanings, depending on context.


For foo:

\r == "carriage return" (CR / ^M)
\n == matches "line feed" (LF) on Linux/Mac, and CRLF on Windows

For bar:

\r == produces LF on Linux/Mac, CRLF on Windows
\n == "null byte" (NUL / ^@)

When editing files in linux (i.e. on a webserver) that were initially created in a windows environment and uploaded (i.e. FTP/SFTP) - all the ^M's you see in vim, are the CR's which linux does not translate as it uses only LF's to depict a line break.

Longer (with ASCII numbers):

NUL == 0x00 == 0 == Ctrl + @ == ^@ shown in vim
LF == 0x0A == 10 == Ctrl + J
CR == 0x0D == 13 == Ctrl + M == ^M shown in vim

Here is a list of the ASCII control characters. Insert them in Vim via Ctrl + V,Ctrl + ---key---.

In Bash or the other Unix/Linux shells, just type Ctrl + ---key---.

Try Ctrl + M in Bash. It's the same as hitting Enter, as the shell realizes what is meant, even though Linux systems use line feeds for line delimiting.

To insert literal's in bash, prepending them with Ctrl + V will also work.

Try in Bash:

echo ^[[33;1mcolored.^[[0mnot colored.

This uses ANSI escape sequences. Insert the two ^['s via Ctrl + V, Esc.

You might also try Ctrl + V,Ctrl + M, Enter, which will give you this:

bash: $'\r': command not found

Remember the \r from above? :>

This ASCII control characters list is different from a complete ASCII symbol table, in that the control characters, which are inserted into a console/pseudoterminal/Vim via the Ctrl key (haha), can be found there.

Whereas in C and most other languages, you usually use the octal codes to represent these 'characters'.

If you really want to know where all this comes from: The TTY demystified. This is the best link you will come across about this topic, but beware: There be dragons.


Usually foo = \n, and bar = \r.

Force Internet Explorer to use a specific Java Runtime Environment install?

Use the deployment Toolkit's deployJava.js (though this ensures a minimum version, rather than a specific version)

How can I find last row that contains data in a specific column?

Simple and quick:

Dim lastRow as long
lastRow = Cells.Find("*",SearchOrder:=xlByRows,SearchDirection:=xlPrevious).Row

Example use:

cells(lastRow,1)="Ultima Linha, Last Row. Youpi!!!!"


Range("A" & lastRow).Value = "FIM, THE END"

How to remove Firefox's dotted outline on BUTTONS as well as links?

There's no way to remove these dotted focus in Firefox using CSS.

If you have access to the computers where your webapplication works, go to about:config in Firefox and set browser.display.focus_ring_width to 0. Then Firefox won't show any dotted borders at all.

The following bug explains the topic:

SQL MAX of multiple columns?

Either of the two samples below will work:

SELECT  MAX(date_columns) AS max_date
FROM    ( (SELECT   date1 AS date_columns
           FROM     data_table         )
          ( SELECT  date2 AS date_columns
            FROM    data_table
          ( SELECT  date3 AS date_columns
            FROM    data_table
        ) AS date_query

The second is an add-on to lassevk's answer.

SELECT  MAX(MostRecentDate)
FROM    ( SELECT    CASE WHEN date1 >= date2
                              AND date1 >= date3 THEN date1
                         WHEN date2 >= date1
                              AND date2 >= date3 THEN date2
                         WHEN date3 >= date1
                              AND date3 >= date2 THEN date3
                         ELSE date1
                    END AS MostRecentDate
          FROM      data_table
        ) AS date_query 

Refreshing all the pivot tables in my excel workbook with a macro

In certain circumstances you might want to differentiate between a PivotTable and its PivotCache. The Cache has it's own refresh method and its own collections. So we could have refreshed all the PivotCaches instead of the PivotTables.

The difference? When you create a new Pivot Table you are asked if you want it based on a previous table. If you say no, this Pivot Table gets its own cache and doubles the size of the source data. If you say yes, you keep your WorkBook small, but you add to a collection of Pivot Tables that share a single cache. The entire collection gets refreshed when you refresh any single Pivot Table in that collection. You can imagine therefore what the difference might be between refreshing every cache in the WorkBook, compared to refreshing every Pivot Table in the WorkBook.

How can one use multi threading in PHP applications

As of the writing of my current comment, I don't know about the PHP threads. I came to look for the answer here myself, but one workaround is that the PHP program that receives the request from the web server delegates the whole answer formulation to a console application that stores its output, the answer to the request, to a binary file and the PHP program that launched the console application returns that binary file byte-by-byte as the answer to the received request. The console application can be written in any programming language that runs on the server, including those that have proper threading support, including C++ programs that use OpenMP.

One unreliable, dirty, trick is to use PHP for executing a console application, "uname",

uname -a

and print the output of that console command to the HTML output to find out the exact version of the server software. Then install the exact same version of the software to a VirtualBox instance, compile/assemble whatever fully self-contained, preferably static, binaries that one wants and then upload those to the server. From that point onwards the PHP application can use those binaries in the role of the console application that has proper multi-threading. It's a dirty, unreliable, workaround to a situation, when the server administrator has not installed all needed programming language implementations to the server. The thing to watch out for is that at every request that the PHP application receives the console application(s) terminates/exit/get_killed.

As to what the hosting service administrators think of such server usage patterns, I guess it boils down to culture. In Northern Europe the service provider HAS TO DELIVER WHAT WAS ADVERTISED and if execution of console commands was allowed and uploading of non-malware files was allowed and the service provider has a right to kill any server process after a few minutes or even after 30 seconds, then the hosting service administrators lack any arguments for forming a proper complaint. In United States and Western Europe the situation/culture is very different and I believe that there's a great chance that in U.S. and/or Western Europe the hosting service provider will refuse to serve hosting service clients that use the above described trick. That's just my guess, given my personal experience with U.S. hosting services and given what I have heard from others about Western European hosting services. As of the writing of my current comment(2018_09_01) I do not know anything about the cultural norms of the Southern-European hosting service providers, Southern-European network administrators.

How to prompt for user input and read command-line arguments

Use 'raw_input' for input from a console/terminal.

if you just want a command line argument like a file name or something e.g.

$ python file_name.txt

then you can use sys.argv...

import sys
print sys.argv

sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"

If you want to have full on command line options use the optparse module.


What is an efficient way to implement a singleton pattern in Java?

If you do not need lazy loading then simply try:

public class Singleton {
    private final static Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() { return Singleton.INSTANCE; }

    protected Object clone() {
        throw new CloneNotSupportedException();

If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:

public class Singleton {
    private static Singleton instance = null;

    private Singleton() {}

    public static Singleton getInstance() {
        if(null == instance) {
            synchronized(Singleton.class) {
                if(null == instance) {
                    instance = new Singleton();
        return instance;

    protected Object clone() {
        throw new CloneNotSupportedException();

As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.

Sys is undefined

Was having a similar issue, except that my page was consistently generating the Sys is undefined error.

For me the problem stems from the fact that I've just installed the AJAX 1.0 extension for .NET 2.0 but had already created my web project in Visual Studio.

When tried to create AJAX controls I kept encountering this error, I spotted Slace's and MadMax1138s posts here. And figured it was my web.config, I created a new project using the new "AJAX enabled web site" project type, and sure enough the web.config has a large number of customizations necessary to use the AJAX controls.

I just updated that web.config with the web.config updates I had already made myself and dropped it into my existing project and everything worked fine.

What is an unsigned char?

signed char and unsigned char both represent 1byte, but they have different ranges.

   Type        |      range
signed char    |  -128 to +127
unsigned char  |     0 to 255

In signed char if we consider char letter = 'A', 'A' is represent binary of 65 in ASCII/Unicode, If 65 can be stored, -65 also can be stored. There are no negative binary values in ASCII/Unicode there for no need to worry about negative values.


#include <stdio.h>

int main()
    signed char char1 = 255;
    signed char char2 = -128;
    unsigned char char3 = 255;
    unsigned char char4 = -128;

    printf("Signed char(255) : %d\n",char1);
    printf("Unsigned char(255) : %d\n",char3);

    printf("\nSigned char(-128) : %d\n",char2);
    printf("Unsigned char(-128) : %d\n",char4);

    return 0;

Output -:

Signed char(255) : -1
Unsigned char(255) : 255

Signed char(-128) : -128
Unsigned char(-128) : 128

Create instance of generic type in Java?

You can do this now and it doesn't require a bunch of reflection code.


public class Q26289147
    public static void main(final String[] args) throws IllegalAccessException, InstantiationException
        final StrawManParameterizedClass<String> smpc = new StrawManParameterizedClass<String>() {};
        final String string = (String) smpc.type.getRawType().newInstance();
        System.out.format("string = \"%s\"",string);

    static abstract class StrawManParameterizedClass<T>
        final TypeToken<T> type = new TypeToken<T>(getClass()) {};

Of course if you need to call the constructor that will require some reflection, but that is very well documented, this trick isn't!

Here is the JavaDoc for TypeToken.