Programs & Examples On #Zlib

zlib is a library used for data compression. Also a crucial component of many software platforms including Linux, Mac OS X, and the iOS

How are zlib, gzip and zip related? What do they have in common and how are they different?

ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.

Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of .tgz or .tar.gz and is commonly called a tarball.

zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.

no module named zlib

My objective was to create a new Django project from the command line in Ubuntu, like so: startproject mysite

I have python2.7.5 installed. I got this error:

ImportError: No module named zlib

For hours I could not find a solution, until now!

Here is a link to the solution -

I followed and executed instruction in Section 1.1 and it is working perfectly! It is an easy solution.

Compilation error - missing zlib.h

In openSUSE 19.2 installing the patterns-hpc-development_node package fixed this issue for me.

Simple way to unzip a .zip file using zlib

Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.

Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.

// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>

#include "unzip.h"

#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192

int main( int argc, char **argv )
    if ( argc < 2 )
        printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
        return -1;

    // Open the zip file
    unzFile *zipfile = unzOpen( argv[ 1 ] );
    if ( zipfile == NULL )
        printf( "%s: not found\n" );
        return -1;

    // Get info about the zip file
    unz_global_info global_info;
    if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
        printf( "could not read file global info\n" );
        unzClose( zipfile );
        return -1;

    // Buffer to hold data read from the zip file.
    char read_buffer[ READ_SIZE ];

    // Loop to extract all files
    uLong i;
    for ( i = 0; i < global_info.number_entry; ++i )
        // Get info about current file.
        unz_file_info file_info;
        char filename[ MAX_FILENAME ];
        if ( unzGetCurrentFileInfo(
            NULL, 0, NULL, 0 ) != UNZ_OK )
            printf( "could not read file info\n" );
            unzClose( zipfile );
            return -1;

        // Check if this entry is a directory or file.
        const size_t filename_length = strlen( filename );
        if ( filename[ filename_length-1 ] == dir_delimter )
            // Entry is a directory, so create it.
            printf( "dir:%s\n", filename );
            mkdir( filename );
            // Entry is a file, so extract it.
            printf( "file:%s\n", filename );
            if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
                printf( "could not open file\n" );
                unzClose( zipfile );
                return -1;

            // Open a file to write out the data.
            FILE *out = fopen( filename, "wb" );
            if ( out == NULL )
                printf( "could not open destination file\n" );
                unzCloseCurrentFile( zipfile );
                unzClose( zipfile );
                return -1;

            int error = UNZ_OK;
                error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
                if ( error < 0 )
                    printf( "error %d\n", error );
                    unzCloseCurrentFile( zipfile );
                    unzClose( zipfile );
                    return -1;

                // Write data to file.
                if ( error > 0 )
                    fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
            } while ( error > 0 );

            fclose( out );

        unzCloseCurrentFile( zipfile );

        // Go the the next entry listed in the zip file.
        if ( ( i+1 ) < global_info.number_entry )
            if ( unzGoToNextFile( zipfile ) != UNZ_OK )
                printf( "cound not read next file\n" );
                unzClose( zipfile );
                return -1;

    unzClose( zipfile );

    return 0;

I built and tested it with MinGW/MSYS on Windows like this:

contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/

file_put_contents: Failed to open stream, no such file or directory

There is definitly a problem with the destination folder path.

Your above error message says, it wants to put the contents to a file in the directory /files/grantapps/, which would be beyond your vhost, but somewhere in the system (see the leading absolute slash )

You should double check:

  • Is the directory /home/username/public_html/files/grantapps/ really present.
  • Contains your loop and your file_put_contents-Statement the absolute path /home/username/public_html/files/grantapps/

batch file to copy files to another location?

@echo off
xcopy ...

Replace ... with the appropriate xcopy arguments to copy what you want copied.

dynamic_cast and static_cast in C++

More than code in C, I think that an english definition could be enough:

Given a class Base of which there is a derived class Derived, dynamic_cast will convert a Base pointer to a Derived pointer if and only if the actual object pointed at is in fact a Derived object.

class Base { virtual ~Base() {} };
class Derived : public Base {};
class Derived2 : public Base {};
class ReDerived : public Derived {};

void test( Base & base )

int main() {
   Base b;
   Derived d;
   Derived2 d2;
   ReDerived rd;

   test( b );   // throw: b is not a Derived object
   test( d );   // ok
   test( d2 );  // throw: d2 is not a Derived object
   test( rd );  // ok: rd is a ReDerived, and thus a derived object

In the example, the call to test binds different objects to a reference to Base. Internally the reference is downcasted to a reference to Derived in a typesafe way: the downcast will succeed only for those cases where the referenced object is indeed an instance of Derived.

What does .shape[] do in "for i in range(Y.shape[0])"?

In Python shape() is use in pandas to give number of row/column:

Number of rows is given by:

train = pd.read_csv('fine_name') //load the data

Number of columns is given by


How to check if type is Boolean

You can use pure Javascript to achieve this:

var test = true;
if (typeof test === 'boolean')
   console.log('test is a boolean!');

Use of contains in Java ArrayList<String>

Perhaps you need to post the code that caused your exception. If the above is all you have, perhaps you just failed to actually initialise the array.

Using contains here should work though.

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.


  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

Setting onSubmit in React.js

<form onSubmit={(e) => {this.doSomething(); e.preventDefault();}}></form>

it work fine for me

number_format() with MySQL

CREATE DEFINER=`yourfunctionname`@`%` FUNCTION `money`(
     `betrag` DECIMAL(10,2)

 RETURNS varchar(128) CHARSET latin1
     select replace(format(cast(betrag as char),2),',',"'") as betrag

will creating a MySql-Function with this Code:

 select replace(format(cast(amount as char),2),',',"'") as amount_formated

overlay a smaller image on a larger image python OpenCv

When attempting to write to the destination image using any of these answers above and you get the following error:

ValueError: assignment destination is read-only

A quick potential fix is to set the WRITEABLE flag to true.


A full list of all the new/popular databases and their uses?

I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.

Laravel 5 PDOException Could Not Find Driver

sudo apt-get update

For Mysql Database

sudo apt-get install php-mysql

For PostgreSQL Database

sudo apt-get install php-pgsql


php artisan migrate

Classpath including JAR within a JAR

I use maven for my java builds which has a plugin called the maven assembly plugin.

It does what your asking, but like some of the other suggestions describe - essentially exploding all the dependent jars and recombining them into a single jar

MySQL Multiple Where Clause

May be using this query you don't get any result or empty result. You need to use OR instead of AND in your query like below.

$query = mysql_query("SELECT image_id FROM list WHERE (style_id = 24 AND style_value = 'red') OR (style_id = 25 AND style_value = 'big') OR (style_id = 27 AND style_value = 'round');

Try out this query.

Remove scrollbars from textarea

For MS IE 10 you'll probably find you need to do the following:

-ms-overflow-style: none

See the following:

How to refresh a Page using react-route Link

I ended up keeping Link and adding the reload to the Link's onClick event with a timeout like this:

function refreshPage() {
    }, 500);
    console.log('page to reload')

<Link to={{pathname:"/"}} onClick={refreshPage}>Home</Link>

without the timeout, the refresh function would run first

Find all table names with column name?

Try Like This: For SQL SERVER 2008+

SELECT AS ColName, AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE LIKE '%MyColumnaName%'



Or Something Like This:

SELECT name  
FROM sys.tables 
              FROM syscolumns 
              WHERE name like '%COlName%' )

How to vertically center a "div" element for all browsers using CSS?

.center {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%); /* (x, y)  => position */_x000D_
  -ms-transform: translate(-50%, -50%); /* IE 9 */_x000D_
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */    _x000D_
.vertical {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  //left: 0;_x000D_
  transform: translate(0, -50%); /* (x, y) => position */_x000D_
.horizontal {_x000D_
  position: absolute;_x000D_
  //top: 0;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, 0); /* (x, y)  => position */_x000D_
div {_x000D_
  padding: 1em;_x000D_
  background-color: grey; _x000D_
  color: white;_x000D_
  <div class="vertical">Vertically left</div>_x000D_
  <div class="horizontal">Horizontal top</div>_x000D_
  <div class="center">Vertically Horizontal</div>  _x000D_

Related: Center a Image

What is the difference between ng-if and ng-show/ng-hide

One important thing to note about ng-if and ng-show is that when using form controls it is better to use ng-if because it completely removes the element from the dom.

This difference is important because if you create an input field with required="true" and then set ng-show="false" to hide it, Chrome will throw the following error when the user tries to submit the form:

An invalid form control with name='' is not focusable.

The reason being the input field is present and it is required but since it is hidden Chrome cannot focus on it. This can literally break your code as this error halts script execution. So be careful!

scp with port number specified

There are many answers, but you should just be able to keep it simple. Make sure you know what port SSH is listening on, and define it. Here is what I just used to replicate your problem.

scp -P 12222 file.7z [email protected]:/home/user/Downloads It worked out well.

Firebase (FCM) how to get token

The team behind Firebase Android SDK change API a little bit. I've implemented "Token to Server" logic like this:

In my instance of FirebaseMessagingService:

public class FirebaseCloudMessagingService extends FirebaseMessagingService {


    public void onNewToken(String token) {
        // sending token to server here



Keep in mind that token is per device, and it can be updated by Firebase regardless of your login logic. So, if you have Login and Logout functionality, you have to consider extra cases:

  1. When a new user logs in, you need to bind token to the new user (send it to the server). Because token might be updated during the session of old user and server doesn't know token of the new user.
  2. When the user logs out, you need to unbind token. Because user should not receive notifications/messages anymore.

Using new API, you can get token like this:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String token = instanceIdResult.getToken();
            // send it to server

Good luck!

Read pdf files with php

Check out FPDF (with FPDI):

These will let you open an pdf and add content to it in PHP. I'm guessing you can also use their functionality to search through the existing content for the values you need.

Another possible library is TCPDF:

Update to add a more modern library: PDF Parser

How to sort a collection by date in MongoDB?

collection.find().sort('date':1).exec(function(err, doc) {});

this worked for me


C linked list inserting node at the end

The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till end and then change the next of last node to new node.

/* Given a reference (pointer to pointer) to the head
   of a list and an int, appends a new node at the end  */

    void append(struct node** head_ref, int new_data)
    /* 1. allocate node */
         struct node* new_node = (struct node*) malloc(sizeof(struct node));

        struct node *last = *head_ref;  /* used in step 5*/

    /* 2. put in the data  */
        new_node->data  = new_data;

    /* 3. This new node is going to be the last node, so make next 
          of it as NULL*/
        new_node->next = NULL;

    /* 4. If the <a href="#">Linked List</a> is empty, then make the new node as head */
        if (*head_ref == NULL)
       *head_ref = new_node;

    /* 5. Else traverse till the last node */
        while (last->next != NULL)
        last = last->next;

    /* 6. Change the next of last node */
        last->next = new_node;

Rounding a double value to x number of decimal places in swift

In Swift 3.0 and Xcode 8.0:

extension Double {
    func roundTo(places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor

Use this extension like so:

let doubleValue = 3.567
let roundedValue = doubleValue.roundTo(places: 2)
print(roundedValue) // prints 3.56

Responsively change div size keeping aspect ratio

You can do this using pure CSS; no JavaScript needed. This utilizes the (somewhat counterintuitive) fact that padding-top percentages are relative to the containing block's width. Here's an example:

.wrapper {_x000D_
  width: 50%;_x000D_
  /* whatever width you want */_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
.wrapper:after {_x000D_
  padding-top: 56.25%;_x000D_
  /* 16:9 ratio */_x000D_
  display: block;_x000D_
  content: '';_x000D_
.main {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  /* fill parent */_x000D_
  background-color: deepskyblue;_x000D_
  /* let's see it! */_x000D_
  color: white;_x000D_
<div class="wrapper">_x000D_
  <div class="main">_x000D_
    This is your div with the specified aspect ratio._x000D_

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Seems bit strange code. To get string from Utf8 byte stream all you need to do is:

string str = Encoding.UTF8.GetString(utf8ByteArray);

If you need to save iso-8859-1 byte stream to somewhere then just use: additional line of code for previous:

byte[] iso88591data = Encoding.GetEncoding("ISO-8859-1").GetBytes(str);

Tomcat manager/html is not available?

You have to check if you have the folder with name manager inside the folder webapps in your tomcat.

Rubens-MacBook-Pro:tomcat rfanjul$ ls -la webapps/
total 16
drwxr-xr-x   8 rfanjul  staff   272 21 May 12:20 .
drwxr-xr-x  14 rfanjul  staff   476 21 May 12:22 ..
-rw-r--r--@  1 rfanjul  staff  6148 21 May 12:20 .DS_Store
drwxr-xr-x  19 rfanjul  staff   646 17 Feb 15:13 ROOT
drwxr-xr-x  51 rfanjul  staff  1734 17 Feb 15:13 docs
drwxr-xr-x   6 rfanjul  staff   204 17 Feb 15:13 examples
drwxr-xr-x   7 rfanjul  staff   238 17 Feb 15:13 host-manager
drwxr-xr-x   8 rfanjul  staff   272 17 Feb 15:13 manager

After that you will be sure that you have this permmint for you user in the file conf/tomcat-users.xml:

<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="test" password="test" roles="admin-gui,manager-gui"/>

restart tomcat and stat tomcat again.

sh bin/ 
sh bin/

I hope that will works fine for you.

Why can't I check if a 'DateTime' is 'Nothing'?

DateTime is a value type, which means it always has some value.

It's like an integer - it can be 0, or 1, or less than zero, but it can never be "nothing".

If you want a DateTime that can take the value Nothing, use a Nullable DateTime.

Can a variable number of arguments be passed to a function?

Another way to go about it, besides the nice answers already mentioned, depends upon the fact that you can pass optional named arguments by position. For example,

def f(x,y=None):
    if y is not None:


In [11]: f(1,2)

In [12]: f(1)

Enter export password to generate a P12 certificate

I know this thread has been idle for a while, but I just wanted to add my two cents to supplement jariq's comment...

Per manual, you don't necessary want to use -password option.

Let's say mykey.key has a password and your want to protect iphone-dev.p12 with another password, this is what you'd use:

pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -passin pass:password_for_mykey -passout pass:password_for_iphone_dev

Have fun scripting!!

Is a DIV inside a TD a bad idea?

As everyone mentioned, it might not be a good idea for layout purposes. I arrived to this question because I was wondering the same and I only wanted to know if it would be valid code.

Since it's valid, you can use it for other purposes. For example, what I'm going to use it for is to put some fancy "CSSed" divs inside table rows and then use a quick jQuery function to allow the user to sort the information by price, name, etc. This way, the only layout table will give me is the "vertical order", but I'll control width, height, background, etc of the divs by CSS.

Best way to store date/time in mongodb

One datestamp is already in the _id object, representing insert time

So if the insert time is what you need, it's already there:

Login to mongodb shell

ubuntu@ip-10-0-1-223:~$ mongo
MongoDB shell version: 2.4.9
connecting to:

Create your database by inserting items

> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})

Lets make that database the one we are on now

> use penguins
switched to db penguins

Get the rows back:

> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }

Get each row in yyyy-MM-dd HH:mm:ss format:

> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53

If that last one-liner confuses you I have a walkthrough on how that works here:

Alphabet range in Python

If you are looking to an equivalent of letters[1:10] from R, you can use:

import string

AppSettings get value from .config file

Coming back to this one after a long time...

Given the demise of ConfigurationManager, for anyone still looking for an answer to this try (for example):

AppSettingsReader appsettingsreader = new AppSettingsReader();
string timeAsString = (string)(new AppSettingsReader().GetValue("Service.Instance.Trigger.Time", typeof(string)));

Requires System.Configuration of course.

(Editted the code to something that actually works and is simpler to read)

Getting last day of the month in a given string date

Java 8 and above.

By using convertedDate.getMonth().length(convertedDate.isLeapYear()) where convertedDate is an instance of LocalDate.

String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(

Java 7 and below.

By using getActualMaximum method of java.util.Calendar:

String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));

How do I write good/correct package files

__all__ is very good - it helps guide import statements without automatically importing modules

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave files empty.

for example: - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder


then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

How can you find out which process is listening on a TCP or UDP port on Windows?

The -b switch mentioned in most answers requires you to have administrative privileges on the machine. You don't really need elevated rights to get the process name!

Find the pid of the process running in the port number (e.g., 8080)

netstat -ano | findStr "8080"

Find the process name by pid

tasklist /fi "pid eq 2216"

find process by TCP/IP port

How to make a function wait until a callback has been called using node.js

It's 2020 and chances are the API has already a promise-based version that works with await. However, some interfaces, especially event emitters will require this workaround:

// doesn't wait
let value;
someEventEmitter.once((e) => { value = e.value; });
// waits
let value = await new Promise((resolve) => {
  someEventEmitter.once('event', (e) => { resolve(e.value); });

In this particular case it would be:

let response = await new Promise((resolve) => {
  myAPI.exec('SomeCommand', (response) => { resolve(response); });

Await has been in new Node.js releases for the past 3 years (since v7.6).

Pass multiple parameters to rest API - Spring

you can pass multiple params in url like


and in order to get this query fields , you can use map like

    @RequestMapping(method = RequestMethod.GET, value = "/custom")
    public String controllerMethod(@RequestParam Map<String, String> customQuery) {

        System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
        System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
        System.out.println("customQuery = price " + customQuery.containsKey("price"));
        System.out.println("customQuery = other " + customQuery.containsKey("other"));
        System.out.println("customQuery = sort " + customQuery.containsKey("sort"));

        return customQuery.toString();

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.

As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
    int a;
    int b;
    int c;

auto compare( Foo const& x, Foo const& y )
    -> int
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.

With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

Xcode Objective-C | iOS: delay function / NSTimer help?

I would like to add a bit the answer by Avner Barr. When using int64, it appears that when we surpass the 1.0 value, the function seems to delay differently. So I think at this point, we should use NSTimeInterval.

So, the final code is:

NSTimeInterval delayInSeconds = 0.05;

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

//do your tasks here


node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

var https = require('https');
https.globalAgent.options.secureProtocol = 'SSLv3_method';

How to convert string to long

You can also try following,

long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);

How to hide 'Back' button on navigation bar on iPhone?

try this one - self.navigationController?.navigationItem.hidesBackButton = true

Usage of sys.stdout.flush() method

import sys
for x in range(10000):
    print "HAPPY >> %s <<\r" % str(x),

Easy way to test a URL for 404 in PHP?

As strager suggests, look into using cURL. You may also be interested in setting CURLOPT_NOBODY with curl_setopt to skip downloading the whole page (you just want the headers).

onCreateOptionsMenu inside Fragments

try this,

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(, menu);

Finally, in onCreateView method, add this line to make the options appear in your Toolbar


Rails - controller action name to string

I just did the same. I did it in helper controller, my code is:

def get_controller_name

def get_action_name

These methods will return current contoller and action name. Hope it helps

What is "entropy and information gain"?

I really recommend you read about Information Theory, bayesian methods and MaxEnt. The place to start is this (freely available online) book by David Mackay:

Those inference methods are really far more general than just text mining and I can't really devise how one would learn how to apply this to NLP without learning some of the general basics contained in this book or other introductory books on Machine Learning and MaxEnt bayesian methods.

The connection between entropy and probability theory to information processing and storing is really, really deep. To give a taste of it, there's a theorem due to Shannon that states that the maximum amount of information you can pass without error through a noisy communication channel is equal to the entropy of the noise process. There's also a theorem that connects how much you can compress a piece of data to occupy the minimum possible memory in your computer to the entropy of the process that generated the data.

I don't think it's really necessary that you go learning about all those theorems on communication theory, but it's not possible to learn this without learning the basics about what is entropy, how it's calculated, what is it's relationship with information and inference, etc...

Batch script loop

for /l is your friend:

for /l %x in (1, 1, 100) do echo %x

Starts at 1, steps by one, and finishes at 100.

Use two %s if it's in a batch file

for /l %%x in (1, 1, 100) do echo %%x

(which is one of the things I really really hate about windows scripting)

If you have multiple commands for each iteration of the loop, do this:

for /l %x in (1, 1, 100) do (
   echo %x
   copy %x.txt z:\whatever\etc

or in a batch file

for /l %%x in (1, 1, 100) do (
   echo %%x
   copy %%x.txt z:\whatever\etc

/l denotes that the for command will operate in a numerical fashion, rather than operating on a set of files
%x is the loops variable
(starting value, increment of value, end condition[inclusive] )

Detect key input in Python

You could make a little Tkinter app:

import Tkinter as tk

def onKeyPress(event):
    text.insert('end', 'You pressed %s\n' % (event.char, ))

root = tk.Tk()
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
root.bind('<KeyPress>', onKeyPress)

Laravel - Model Class not found

I had the same error in Laravel 5.2, turns out the namespace is incorrect in the model class definition.

I created my model using the command:

php artisan make:model myModel

By default, Laravel 5 creates the model under App folder, but if you were to move the model to another folder like I did, you must change the the namespace inside the model definition too:

namespace App\ModelFolder;

To include the folder name when creating the model you could use (don't forget to use double back slashes):

php artisan make:model ModelFolder\\myModel

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))


Number of periods = 36.55539635919235

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

Following the official installation guide for Windows C++ compilers:

to upgrade setuptools and install specific Microsoft Visual C++ compiler.

It has already contains some points refered in other answer.

SQL "select where not in subquery" returns no results

select *,
(select COUNT(ID)  from ProductMaster where ProductMaster.CatID = CategoryMaster.ID) as coun 
from CategoryMaster

Remove first Item of the array (like popping from stack)

There is a function called shift(). It will remove the first element of your array.

There is some good documentation and examples.

node.js Error: connect ECONNREFUSED; response from server

If you have stopped the mongod.exe service from the task manager, you need to restart the service. In my case I stopped the service from task manager and on restart it doesn't automatically started.

How can I use Bash syntax in Makefile targets?

If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.

JavaFX Application Icon

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("/icon.png" )));

You can add more than one icon with different sizes using this method.The images should be different sizes of the same image and the best size will be chosen. eg. 16x16, 32,32

How to extract HTTP response body from a Python requests call?

Your code is correct. I tested:

r = requests.get("")

And it returned plenty of content. Check the url, try "". Cheers!

GLYPHICONS - bootstrap icon font hex value

If you want to use glyph icons with bootstrap 2.3.2, Add the font files from bootstrap 3 to your project folder then copy this to your css file

 @font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

Starting the week on Monday with isoWeekday()

try using begin.startOf('isoWeek'); instead of begin.startOf('week');

Passing arguments to AsyncTask, and returning results

You can receive returning results like that: AsyncTask class

protected Boolean doInBackground(Void... params) {
    if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) {
        try {
            throw new SQLException("Database credentials missing");
        } catch (SQLException e) {

    try {
    } catch (ClassNotFoundException e) {

    try {
        this.conn = DriverManager.getConnection( + ':' + this.port + '/' + this.dbName, this.user, this.pass);
    } catch (SQLException e) {

    return true;

receiving class:

boolean result =_store.get();

Hoping it will help.

Toggle Checkboxes on/off

The most basic example would be:

// get DOM elements_x000D_
var checkbox = document.querySelector('input'),_x000D_
    button = document.querySelector('button');_x000D_
// bind "cilck" event on the button_x000D_
button.addEventListener('click', toggleCheckbox);_x000D_
// when clicking the button, toggle the checkbox_x000D_
function toggleCheckbox(){_x000D_
  checkbox.checked = !checkbox.checked;_x000D_
<input type="checkbox">_x000D_
<button>Toggle checkbox</button>

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;

What's the best way to convert a number to a string in JavaScript?

I think it depends on the situation but anyway you can use the .toString() method as it is very clear to understand.

CALL command vs. START with /WAIT option

For exe files, I suppose the differences are nearly unimportant.
But to start an exe you don't even need CALL.

When starting another batch it's a big difference,
as CALL will start it in the same window and the called batch has access to the same variable context.
So it can also change variables which affects the caller.

START will create a new cmd.exe for the called batch and without /b it will open a new window.
As it's a new context, variables can't be shared.


Using start /wait <prog>
- Changes of environment variables are lost when the <prog> ends
- The caller waits until the <prog> is finished

Using call <prog>
- For exe it can be ommited, because it's equal to just starting <prog>
- For an exe-prog the caller batch waits or starts the exe asynchronous, but the behaviour depends on the exe itself.
- For batch files, the caller batch continues, when the called <batch-file> finishes, WITHOUT call the control will not return to the caller batch


Using CALL can change the parameters (for batch and exe files), but only when they contain carets or percent signs.

call myProg param1 param^^2 "param^3" %%path%%

Will be expanded to (from within an batch file)

myProg param1 param2 param^^3 <content of path>

Javascript Image Resize

Tried the following code, worked OK on IE6 on WinXP Pro SP3.

function Resize(imgId)
  var img = document.getElementById(imgId);
  var w = img.width, h = img.height;
  w /= 2; h /= 2;
  img.width = w; img.height = h;

Also OK in FF3 and Opera 9.26.

Best way to "negate" an instanceof

No, there is no better way; yours is canonical.

$(document).on("click"... not working?

This works:

<div id="start-element">Click Me</div>

$(document).on("click","#test-element",function() {

$(document).on("click","#start-element",function() {
    $(this).attr("id", "test-element");

Here is the Fiddle

ERROR 2003 (HY000): Can't connect to MySQL server (111)

I had the same problem trying to connect to a remote mysql db.

I fixed it by opening the firewall on the db server to allow traffic through:

sudo ufw allow mysql

Is Secure.ANDROID_ID unique for each device?

With Android O the behaviour of the ANDROID_ID will change. The ANDROID_ID will be different per app per user on the phone.

Taken from:

Android ID

In O, Android ID (Settings.Secure.ANDROID_ID or SSAID) has a different value for each app and each user on the device. Developers requiring a device-scoped identifier, should instead use a resettable identifier, such as Advertising ID, giving users more control. Advertising ID also provides a user-facing setting to limit ad tracking.

Additionally in Android O:

  • The ANDROID_ID value won't change on package uninstall/reinstall, as long as the package name and signing key are the same. Apps can rely on this value to maintain state across reinstalls.
  • If an app was installed on a device running an earlier version of Android, the Android ID remains the same when the device is updated to Android O, unless the app is uninstalled and reinstalled.
  • The Android ID value only changes if the device is factory reset or if the signing key rotates between uninstall and
    reinstall events.
  • This change is only required for device manufacturers shipping with Google Play services and Advertising ID. Other device manufacturers may provide an alternative resettable ID or continue to provide ANDROID ID.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Could me multiple reason for this. But you want might forget to add as @Bean for component which you have did @Autowired.

In my case, i have forgot to decorate with @Bean which causing this issue.

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

Plot 3D data in R

If you're working with "real" data for which the grid intervals and sequence cannot be guaranteed to be increasing or unique (hopefully the (x,y,z) combinations are unique at least, even if these triples are duplicated), I would recommend the akima package for interpolating from an irregular grid to a regular one.

Using your definition of data:

im <- with(data,interp(x,y,z))

enter image description here

And this should work not only with image but similar functions as well.

Note that the default grid to which your data is mapped to by akima::interp is defined by 40 equal intervals spanning the range of x and y values:

> formals(akima::interp)[c("xo","yo")]
seq(min(x), max(x), length = 40)

seq(min(y), max(y), length = 40)

But of course, this can be overridden by passing arguments xo and yo to akima::interp.

Best way to use PHP to encrypt and decrypt passwords?

You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. This answer explains how to properly implement password hashing in PHP. Still, here is how you would encrypt/decrypt:

$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces

To Encrypt:

$iv = mcrypt_create_iv(
    mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),

$encrypted = base64_encode(
    $iv .
        hash('sha256', $key, true),

To Decrypt:

$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));

$decrypted = rtrim(
        hash('sha256', $key, true),
        substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),

Warning: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. You should not rely on unauthenticated encryption for security, especially since the code as provided is vulnerable to padding oracle attacks.

See also:

Also, don't just use a "password" for an encryption key. Encryption keys are random strings.

Demo at

echo 'Encrypted:' . "\n";
var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688="

echo "\n";

echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "

Insert string at specified position

$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);

What's the quickest way to multiply multiple cells by another number?

  1. Enter the multiplier in a cell
  2. Copy that cell to the clipboard
  3. Select the range you want to multiply by the multiplier
  4. (Excel 2003 or earlier) Choose Edit | Paste Special | Multiply

    (Excel 2007 or later) Click on the Paste down arrow | Paste Special | Multiply

How to calculate the running time of my program?

Use System.nanoTime to get the current time.

long startTime = System.nanoTime();
.....your program....
long endTime   = System.nanoTime();
long totalTime = endTime - startTime;

The above code prints the running time of the program in nanoseconds.

How to find current transaction level?

Run this:

SELECT CASE transaction_isolation_level 
WHEN 0 THEN 'Unspecified' 
WHEN 1 THEN 'ReadUncommitted' 
WHEN 2 THEN 'ReadCommitted' 
WHEN 3 THEN 'Repeatable' 
WHEN 4 THEN 'Serializable' 
FROM sys.dm_exec_sessions 
where session_id = @@SPID reference for the constant values.

How to use document.getElementByName and getElementByTag?

If you have given same text name for both of your Id and Name properties you can give like document.getElementByName('frmMain')[index] other wise object required error will come.And if you have only one table in your page you can use document.getElementBytag('table')[index].


You can replace the index according to your form, if its first form place 0 for index.

How can I convert JSON to a HashMap using Gson?

I had the exact same question and ended up here. I had a different approach that seems much simpler (maybe newer versions of gson?).

    Gson gson = new Gson();
    Map jsonObject = (Map) gson.fromJson(data, Object.class);

with the following json

  "map-00": {
    "array-00": [
     "value": "entry-02"

The following

    Map map00 = (Map) jsonObject.get("map-00");
    List array00 = (List) map00.get("array-00");
    String value = (String) map00.get("value");
    for (int i = 0; i < array00.size(); i++) {
        System.out.println("map-00.array-00[" + i + "]= " + array00.get(i));
    System.out.println("map-00.value = " + value);


map-00.array-00[0]= entry-00
map-00.array-00[1]= entry-01
map-00.value = entry-02

You could dynamically check using instanceof when navigating your jsonObject. Something like

Map json = gson.fromJson(data, Object.class);
if(json.get("field") instanceof Map) {
  Map field = (Map)json.get("field");
} else if (json.get("field") instanceof List) {
  List field = (List)json.get("field");
} ...

It works for me, so it must work for you ;-)

Get width/height of SVG element

SVG has properties width and height. They return an object SVGAnimatedLength with two properties: animVal and baseVal. This interface is used for animation, where baseVal is the value before animation. From what I can see, this method returns consistent values in both Chrome and Firefox, so I think it can also be used to get calculated size of SVG.

HTTP Get with 204 No Content: Is that normal

Your current combination of a POST with an HTTP 204 response is fine.

Using a POST as a universal replacement for a GET is not supported by the RFC, as each has its own specific purpose and semantics.

The purpose of a GET is to retrieve a resource. Therefore, while allowed, an HTTP 204 wouldn't be the best choice since content IS expected in the response. An HTTP 404 Not Found or an HTTP 410 Gone would be better choices if the server was unable to provide the requested resource.

The RFC also specifically calls out an HTTP 204 as an appropriate response for PUT, POST and DELETE, but omits it for GET.

See the RFC for the semantics of GET.

There are other response codes that could also be returned, indicating no content, that would be more appropriate than an HTTP 204.

For example, for a conditional GET you could receive an HTTP 304 Not Modified response which would contain no body content.

How to use multiple conditions (With AND) in IIF expressions in ssrs

Could you try this out?

=IIF((Fields!OpeningStock.Value=0) AND (Fields!GrossDispatched.Value=0) AND 
(Fields!TransferOutToMW.Value=0) AND (Fields!TransferOutToDW.Value=0) AND 
(Fields!TransferOutToOW.Value=0) AND (Fields!NetDispatched.Value=0) AND (Fields!QtySold.Value=0) 
AND (Fields!StockAdjustment.Value=0) AND (Fields!ClosingStock.Value=0),True,False)

Note: Setting Hidden to False will make the row visible

Dead simple example of using Multiprocessing Queue, Pool and Locking

This might be not 100% related to the question, but on my search for an example of using multiprocessing with a queue this shows up first on google.

This is a basic example class that you can instantiate and put items in a queue and can wait until queue is finished. That's all I needed.

from multiprocessing import JoinableQueue
from multiprocessing.context import Process

class Renderer:
    queue = None

    def __init__(self, nb_workers=2):
        self.queue = JoinableQueue()
        self.processes = [Process(target=self.upload) for i in range(nb_workers)]
        for p in self.processes:

    def render(self, item):

    def upload(self):
        while True:
            item = self.queue.get()
            if item is None:

            # process your item here


    def terminate(self):
        """ wait until queue is empty and terminate processes """
        for p in self.processes:

r = Renderer()

MySQL Error 1093 - Can't specify target table for update in FROM clause

how about this query hope it helps

DELETE FROM story_category LEFT JOIN (SELECT FROM category) cat ON = WHERE IS NULL

Posting JSON Data to ASP.NET MVC

I see everyone here "took the long route!". As long as you are using MVC, I strongly recommend you to use the easiest method over all which is Newtonsoft.JSON... Also If you dont wanna use libraries check the answer links below. I took a good research time for this to solve the issue for my self and these are the solutions I found;

First implement the Newtonsoft.Json:

using Newtonsoft.Json;

Prepare your Ajax request:

    dataType: "json",
    contentType: "application/json",            
    type: 'POST',
    url: '/Controller/Action',
    data: { 'items': JSON.stringify(lineItems), 'id': documentId }

Then go for your result class:

public ActionResult SaveData(string incoming, int documentId){
    // DeSerialize into your Model as your Model Array
    LineItem[] jsr = JsonConvert.DeserializeObject<LineItem[]>(Temp);
    foreach(LineItem item in jsr){
        // save some stuff
    return Json(new { success = true, message = "Some message" });

See the trick up there? Instead of using JsonResult I used regular ActionResult with a string which includes json string. Then deserialized into my Model so I can use this in any action method I have.

Plus sides of this method is :

  1. Easier to pass between actions,
  2. Lesser and more clear usage of code,
  3. No need to change your model,
  4. Simple implementation with JSON.stringify(Model)
  5. Passing only string

Down sides of this method is :

  1. Passing only string
  2. Deserialization process

Also check these questions and answers which are really helpfull:

another method :

and another method :

Powershell script does not run via Scheduled Tasks

after trying a lot of time...

task scheduler : powershell.exe -noexit & .\your_script.ps1

be sure to put your script in this folder : windows\system32

good luck !

What is the difference between task and thread?

In computer science terms, a Task is a future or a promise. (Some people use those two terms synonymously, some use them differently, nobody can agree on a precise definition.) Basically, a Task<T> "promises" to return you a T, but not right now honey, I'm kinda busy, why don't you come back later?

A Thread is a way of fulfilling that promise. But not every Task needs a brand-new Thread. (In fact, creating a thread is often undesirable, because doing so is much more expensive than re-using an existing thread from the thread pool. More on that in a moment.) If the value you are waiting for comes from the filesystem or a database or the network, then there is no need for a thread to sit around and wait for the data when it can be servicing other requests. Instead, the Task might register a callback to receive the value(s) when they're ready.

In particular, the Task does not say why it is that it takes such a long time to return the value. It might be that it takes a long time to compute, or it might that it takes a long time to fetch. Only in the former case would you use a Thread to run a Task. (In .NET, threads are freaking expensive, so you generally want to avoid them as much as possible and really only use them if you want to run multiple heavy computations on multiple CPUs. For example, in Windows, a thread weighs 12 KiByte (I think), in Linux, a thread weighs as little as 4 KiByte, in Erlang/BEAM even just 400 Byte. In .NET, it's 1 MiByte!)

implements Closeable or implements AutoCloseable

AutoCloseable (introduced in Java 7) makes it possible to use the try-with-resources idiom:

public class MyResource implements AutoCloseable {

    public void close() throws Exception {


Now you can say:

try (MyResource res = new MyResource()) {
    // use resource here

and JVM will call close() automatically for you.

Closeable is an older interface. For some reason To preserve backward compatibility, language designers decided to create a separate one. This allows not only all Closeable classes (like streams throwing IOException) to be used in try-with-resources, but also allows throwing more general checked exceptions from close().

When in doubt, use AutoCloseable, users of your class will be grateful.

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit
  3. You will be prompted to enter a new password.

Cannot read property 'length' of null (javascript)

This also works - evaluate, if capital is defined. If not, this means, that capital is undefined or null (or other value, that evaluates to false in js)

if (capital && capital.length < 1) {do your stuff}

How to make HTML table cell editable?

Just insert <input> element in <td> dynamically, on cell click. Only simple HTML and Javascript. No need for contentEditable , jquery, HTML5

Use basic authentication with jQuery and Ajax

How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax call.

  type: "GET",
  url: "index1.php",
  dataType: 'json',
  username: username,
  password: password,
  data: '{ "comment" }',
  success: function (){
    alert('Thanks for your comment!'); 

EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized response, instead of setRequestHeader (pre -1.7) use 'headers':

  type: "GET",
  url: "index1.php",
  dataType: 'json',
  headers: {
    "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
  data: '{ "comment" }',
  success: function (){
    alert('Thanks for your comment!'); 

Skip first couple of lines while reading lines in Python file

If you don't want to read the whole file into memory at once, you can use a few tricks:

With next(iterator) you can advance to the next line:

with open("filename.txt") as f:
     for line in f:

Of course, this is slighly ugly, so itertools has a better way of doing this:

from itertools import islice

with open("filename.txt") as f:
    # start at line 17 and never stop (None), until the end
    for line in islice(f, 17, None):

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

Paging with Oracle

Something like this should work: From Frans Bouma's Blog

    SELECT a.*, rownum r__
        ORDER BY OrderDate DESC, ShippingDate DESC
    ) a
    WHERE rownum < ((pageNumber * pageSize) + 1 )
WHERE r__ >= (((pageNumber-1) * pageSize) + 1)

VB.NET: how to prevent user input in a ComboBox

Using 'DropDownList' for the 'DropDownStyle' property of the combo box doesn't work as it changes the look and feel of the combo box. I am using Visual Studio 2019 Community Edition.

Using 'e.Handled = True' also doesn't work either as it still allows user input. Using 'False' for the 'Enabled' property of the combo box also doesn't work too because it stops the user from being able to use the combo box.

All of the "solutions" that have been proposed above are complete rubbish. What really works is this following code which restricts user input to certain keys such as up / down (for navigating through the list of all available choices in the combo box), suppressing all other key inputs:-

Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles 
    REM The following code is executed whenever the user has pressed
    REM a key.  Added on Wednesday 1st January 2020.

    REM Determine what key the user has pressed.  Added on Wednesday
    REM 1st January 2020.
    Select Case e.KeyCode
        Case Keys.Down, Keys.Up
            REM This section is for whenever the user has pressed either
            REM the arrow down key or arrow up key.  Added on Wednesday
            REM 1st January 2020.

        Case Else
            REM This section is for whenever the user has pressed any
            REM other key.  Added on Wednesday 1st January 2020.

            REM Cancelling the key that the user has pressed.  Added on
            REM Wednesday 1st January 2020.
            e.SuppressKeyPress = True

    End Select

End Sub

Relationship between hashCode and equals method in Java

The problem you will have is with collections where unicity of elements is calculated according to both .equals() and .hashCode(), for instance keys in a HashMap.

As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode().

If you have two objects which are .equals(), but have different hash codes, you lose!

The part of the contract here which is important is: objects which are .equals() MUST have the same .hashCode().

This is all documented in the javadoc for Object. And Joshua Bloch says you must do it in Effective Java. Enough said.

Setting CSS pseudo-class rules from JavaScript

Switching stylesheets in and out is the way to do it. Here is a library to build stylesheets dynamically, so you can set styles on the fly:

TypeError: can only concatenate list (not "str") to list

Let me fix your code

inventory=["sword", "potion", "armour", "bow"]
print("\ncommands: use (remove) and pickup (add)")
selection=input("choose a command [use/pickup]")

if selection == "use":
    inventory.remove(input("What do you want to use? "))
elif selection == "pickup":
    add=input("What do you want to pickup? ")
    newinv=inventory+[str(add)] #use '[str(add)]' or list(str(add))

The error is you are adding string and list, you should use list or [] to make the string become list type

Unable to set default python version to python3 in ubuntu

Set priority for default python in Linux terminal by adding this:

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 1

Here, we set python3 to have priority 10 and python2 to priority 1. This will make python3 the default python. If you want Python2 as default then make a priority of python2 higher then python3

Java count occurrence of each item in an array

You can use HashMap, where Key is your string and value - count.

What are some ways of accessing Microsoft SQL Server from Linux?

Mono contains an ADO.NET provider that should do this for you. I don't know if there is a command line utility for it, but you could definitely wrap up some C# to do the queries if there isn't.

Have a look at and

How to change the color of a button?

For the text color add:

android:textColor="<hex color>"

For the background color add:

android:background="<hex color>"

From API 21 you can use:

android:backgroundTint="<hex color>"

Note: If you're going to work with android/java you really should learn how to google ;)
How to customize different buttons in Android

What is the difference between String.slice and String.substring?

Ben Nadel has written a good article about this, he points out the difference in the parameters to these functions:

String.slice( begin [, end ] )
String.substring( from [, to ] )
String.substr( start [, length ] )

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn't.

Here is his article about this.

Find the number of columns in a table

 WHERE table_catalog = 'database_name' -- the database
   AND table_name = 'table_name'

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    // String and Sink setup
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    // Dump Plain Text
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    // Create Cipher Text
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );

    // Dump Cipher Text
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";

    std::cout << std::endl << std::endl;

    // Decrypt
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );

    // Dump Decrypted Text
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Setting Remote Webdriver to run tests in a remote computer using Java

This issue came for me due to the fact that .. i was running server with selenium-server-standalone-2.32.0 and client registered with selenium-server-standalone-2.37.0 .. When i made both selenium-server-standalone-2.32.0 and ran then things worked fine

How do I get an empty array of any size in python?

If you (or other searchers of this question) were actually interested in creating a contiguous array to fill with integers, consider bytearray and memoryivew:

# cast() is available starting Python 3.3
size = 10**6 
ints = memoryview(bytearray(size)).cast('i') 

ints.contiguous, ints.itemsize, ints.shape
# (True, 4, (250000,))

# 0

ints[0] = 16
# 16

How to use the CancellationToken property?

You have to pass the CancellationToken to the Task, which will periodically monitors the token to see whether cancellation is requested.

// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;  

// Task need to be cancelled with CancellationToken 
Task task = Task.Run(async () => {     
  while(!token.IsCancellationRequested) {
      await Task.Delay(1000);
}, token);

Console.WriteLine("Press enter to stop the task"); 

In this case, the operation will end when cancellation is requested and the Task will have a RanToCompletion state. If you want to be acknowledged that your task has been cancelled, you have to use ThrowIfCancellationRequested to throw an OperationCanceledException exception.

Task task = Task.Run(async () =>             
    while (!token.IsCancellationRequested) {
         await Task.Delay(1000);                
}, token)
.ContinueWith(t =>
      t.Exception?.Handle(e => true);
      Console.WriteLine("You have canceled the task");
Console.WriteLine("Press enter to stop the task");                 

Hope this helps to understand better.

Conda: Installing / upgrading directly from github

I found a reference to this in condas issues. The following should now work.

name: sample_env
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+

How do I add an integer value with javascript (jquery) to a value that's returning a string?

Your code should like this:

<span id="replies">8</span>

var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;

Hacks N Tricks

How to efficiently remove duplicates from an array without using Set

If you are looking to remove duplicates using the same array and also keeping the time complexity of O(n). Then this should do the trick. Also, would only work if the array is sorted.

function removeDuplicates_sorted(arr){

let j = 0; 

for(let x = 0; x < arr.length - 1; x++){
    if(arr[x] != arr[x + 1]){ 
        arr[j++] = arr[x];

arr[j++] = arr[arr.length - 1];
arr.length = j;

return arr;


Here is for an unsorted array, its O(n) but uses more space complexity then the sorted.

function removeDuplicates_unsorted(arr){

let map = {};
let j = 0;

for(var numbers of arr){
        map[numbers] = 1;
        arr[j++] = numbers;

arr.length = j;

return arr;


How to setup virtual environment for Python in VS Code?

I had the same problem and the solution was pretty easy:

"If you create a new conda environment while VS Code is running, use the Reload Window command to refresh the environment list shown with Python: Select Interpreter; otherwise you may not see the environment there. It might take a short time to appear; if you don't see it at first, wait 15 seconds then try using the command again."

That's written on Vscode site

Note: to Reload Window: ctrl+shift+p in Vscode, then write reload window

How to lose margin/padding in UITextView?

[firstNameTextField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];

Is there a way to represent a directory tree in a Github

None of the above solution worked for me completely on my mac.

The best solution I found this is to use the utility created here.

Once you have installed the utility npm install md-file-tree -g then you can simply run to get all files tree

md-file-tree . >

Java constant examples (Create a java file having only constants)

- Create a Class with public static final fields.

- And then you can access these fields from any class using the Class_Name.Field_Name.

- You can declare the class as final, so that the class can't be extended(Inherited) and modify....

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

You could just simply do the following

In your js

$ = 0;

In your template

<div id="number-{{$}}"></div>

which will render

<div id="number-0"></div>

It is not necessary to concatenate inside double curly brackets.

Version of Apache installed on a Debian machine

I tried running the command "httpd -V" and "apachectl -V", but I could not execute and was getting the error:

-ksh: php: not found [No such file or directory]

Then I tried another way. I went to the Apache directory on my server and then tried executing the command:

./apachectl -v

This worked for me and returned the output:

Server version: Apache/2.2.20 (Unix)
Server built:   Sep  6 2012 17:22:16

I hope this helps.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

All those answers didnt help me, BUT I found another solution.

I had an Entity A containing a List of Entity B. Entity B contained a List of Entity C.

I was trying to update Entity A and B. It worked. But when updating Entity C, I got the mentioned error. In entity B I had an annotation like this:

@OneToMany(mappedBy = "entity_b", cascade = [CascadeType.ALL] , orphanRemoval = true)
var c: List<EntityC>?,

I simply removed orphanRemoval and the update worked.

How to extract hours and minutes from a datetime.datetime object?

If the time is 11:03, then the accepted answer will print 11:3.

You could zero-pad the minutes:

"Created at {:d}:{:02d}".format(tdate.hour, tdate.minute)

Or go another way and use tdate.time() and only take the hour/minute part:


Encoding Error in Panda read_csv

This works in Mac as well you can use

df= pd.read_csv('Region_count.csv', encoding ='latin1')

How to printf "unsigned long" in C?

Out of all the combinations you tried, %ld and %lu are the only ones which are valid printf format specifiers at all. %lu (long unsigned decimal), %lx or %lX (long hex with lowercase or uppercase letters), and %lo (long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the % and the l).

GridView sorting: SortDirection always Ascending

This is probably going to bet buried here but the solution I came up with which works great for my situation:

Form Load Event looks like this:

private DataTable DataTable1;
protected void Page_Load(object sender, EventArgs e)
  DataTable1 = GetDataFromDatabase();
  this.GridView1.DataSource = DataTable1.DefaultView;

Add two hidden fields on to the page:

<asp:HiddenField runat="server" ID="lastSortDirection" />
<asp:HiddenField runat="server" ID="lastSortExpression" />

Add the following to your asp:GridView object:

AllowSorting="True" OnSorting="GridView1_Sorting"

Use the following GridView Sorting Event

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    if (lastSortExpression.Value == e.SortExpression.ToString())
        if (lastSortDirection.Value == SortDirection.Ascending.ToString())
            e.SortDirection = SortDirection.Descending;
            e.SortDirection = SortDirection.Ascending;
        lastSortDirection.Value = e.SortDirection.ToString();
        lastSortExpression.Value = e.SortExpression;
        lastSortExpression.Value = e.SortExpression;
        e.SortDirection = SortDirection.Ascending;
        lastSortDirection.Value = e.SortDirection.ToString();

    DataView dv = DataTable1.DefaultView;
    if (e.SortDirection == SortDirection.Ascending)
        dv.Sort = e.SortExpression;
        dv.Sort = e.SortExpression + " DESC";

    DataTable1 = dv.ToTable();
    GridView1.DataSource = DataTable1.DefaultView;

Now every column in my gridview is sorted without needing any further changes if any of the columns change.

SQL Server : Columns to Rows

The opposite of this is to flatten a column into a csv eg

SELECT STRING_AGG ([value],',') FROM STRING_SPLIT('Akio,Hiraku,Kazuo', ',')

How do I drag and drop files into an application?

Some sample code:

  public partial class Form1 : Form {
    public Form1() {
      this.AllowDrop = true;
      this.DragEnter += new DragEventHandler(Form1_DragEnter);
      this.DragDrop += new DragEventHandler(Form1_DragDrop);

    void Form1_DragEnter(object sender, DragEventArgs e) {
      if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;

    void Form1_DragDrop(object sender, DragEventArgs e) {
      string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
      foreach (string file in files) Console.WriteLine(file);

How to check cordova android version of a cordova/phonegap project?


cordova -v 

to see the currently running version. Run the npm info command

npm info cordova

for a longer listing that includes the current version along with other available version numbers

How to implement private method in ES6 class with Traceur

I came up with what I feel is a much better solution allowing:

  • no need for 'this._', that/self, weakmaps, symbols etc. Clear and straightforward 'class' code

  • private variables and methods are really private and have the correct 'this' binding

  • No use of 'this' at all which means clear code that is much less error prone

  • public interface is clear and separated from the implementation as a proxy to private methods

  • allows easy composition

with this you can do:

function Counter() {_x000D_
  // public interface_x000D_
  const proxy = {_x000D_
    advance,  // advance counter and get new value_x000D_
    reset,    // reset value_x000D_
    value     // get value_x000D_
  // private variables and methods_x000D_
  let count=0;_x000D_
  function advance() {_x000D_
    return ++count;_x000D_
  function reset(newCount) {_x000D_
    count=(newCount || 0);_x000D_
  function value() {_x000D_
    return count;_x000D_
  return proxy;_x000D_
let counter=Counter.New();_x000D_
console.log(counter instanceof Counter); // true_x000D_
console.log('Counter next = '+counter.advance()); // 101_x000D_
console.log(Object.getOwnPropertyNames(counter)); // ["advance", "reset", "value"]
<script src=""></script>

see New for the code and more elaborate examples including constructor and composition

Run .php file in Windows Command Prompt (cmd)

You should declare Environment Variable for PHP in path, so you could use like this:

C:\Path\to\somewhere>php cli.php

You can do it like this

Formatting floats without trailing zeros

Me, I'd do ('%f' % x).rstrip('0').rstrip('.') -- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as %g, but, it works (and I don't know how to force %g to never use scientific notation;-).

How can I get zoom functionality for images?

This is a very late addition to this thread but I've been working on an image view that supports zoom and pan and has a couple of features I haven't found elsewhere. This started out as a way of displaying very large images without causing OutOfMemoryErrors, by subsampling the image when zoomed out and loading higher resolution tiles when zoomed in. It now supports use in a ViewPager, rotation manually or using EXIF information (90° stops), override of selected touch events using OnClickListener or your own GestureDetector or OnTouchListener, subclassing to add overlays, pan while zooming, and fling momentum.

It's not intended as a general use replacement for ImageView so doesn't extend it, and doesn't support display of images from resources, only assets and external files. It requires SDK 10.

Source is on GitHub, and there's a sample that illustrates use in a ViewPager.

Get to UIViewController from UIView?

Don't forget that you can get access to the root view controller for the window that the view is a subview of. From there, if you are e.g. using a navigation view controller and want to push a new view onto it:

    [[[[self window] rootViewController] navigationController] pushViewController:newController animated:YES];

You will need to set up the rootViewController property of the window properly first, however. Do this when you first create the controller e.g. in your app delegate:

-(void) applicationDidFinishLaunching:(UIApplication *)application {
    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    RootViewController *controller = [[YourRootViewController] alloc] init];
    [window setRootViewController: controller];
    navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
    [controller release];
    [window addSubview:[[self navigationController] view]];
    [window makeKeyAndVisible];

How do you get centered content using Twitter Bootstrap?

The class .show-grid is applying center aligned text in the example in the link.

You can always add style="text-align:center" to your row div or some other class I would think.

Check If array is null or not in php

you can use


to check if the main array is empty or not.

But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See


if (empty($result) || !isset($result['Tags'])) {
    return false;
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
    return false;
return ($result['Tags']->count());

ssl.SSLError: tlsv1 alert protocol version

None of the accepted answers pointed me in the right direction, and this is still the question that comes up when searching the topic, so here's my (partially) successful saga.

Background: I run a Python script on a Beaglebone Black that polls the cryptocurrency exchange Poloniex using the python-poloniex library. It suddenly stopped working with the TLSV1_ALERT_PROTOCOL_VERSION error.

Turns out that OpenSSL was fine, and trying to force a v1.2 connection was a huge wild goose chase - the library will use the latest version as necessary. The weak link in the chain was actually Python, which only defined ssl.PROTOCOL_TLSv1_2, and therefore started supporting TLS v1.2, since version 3.4.

Meanwhile, the version of Debian on the Beaglebone considers Python 3.3 the latest. The workaround I used was to install Python 3.5 from source (3.4 might have eventually worked too, but after hours of trial and error I'm done):

sudo apt-get install build-essential checkinstall
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
sudo tar xzf Python-3.5.4.tgz
cd Python-3.5.4
sudo make altinstall

Maybe not all those packages are strictly necessary, but installing them all at once saves a bunch of retries. The altinstall prevents the install from clobbering existing python binaries, installing as python3.5 instead, though that does mean you have to re-install additional libraries. The ./configure took a good five or ten minutes. The make took a couple of hours.

Now this still didn't work until I finally ran

sudo -H pip3.5 install requests[security]

Which also installs pyOpenSSL, cryptography and idna. I suspect pyOpenSSL was the key, so maybe pip3.5 install -U pyopenssl would have been sufficient but I've spent far too long on this already to make sure.

So in summary, if you get TLSV1_ALERT_PROTOCOL_VERSION error in Python, it's probably because you can't support TLS v1.2. To add support, you need at least the following:

  • OpenSSL 1.0.1
  • Python 3.4
  • requests[security]

This has got me past TLSV1_ALERT_PROTOCOL_VERSION, and now I get to battle with SSL23_GET_SERVER_HELLO instead.

Turns out this is back to the original issue of Python selecting the wrong SSL version. This can be confirmed by using this trick to mount a requests session with ssl_version=ssl.PROTOCOL_TLSv1_2. Without it, SSLv23 is used and the SSL23_GET_SERVER_HELLO error appears. With it, the request succeeds.

The final battle was to force TLSv1_2 to be picked when the request is made deep within a third party library. Both this method and this method ought to have done the trick, but neither made any difference. My final solution is horrible, but effective. I edited /usr/local/lib/python3.5/site-packages/urllib3/util/ and changed

def resolve_ssl_version(candidate):
    like resolve_cert_reqs
    if candidate is None:
        return PROTOCOL_SSLv23

    if isinstance(candidate, str):
        res = getattr(ssl, candidate, None)
        if res is None:
            res = getattr(ssl, 'PROTOCOL_' + candidate)
        return res

    return candidate


def resolve_ssl_version(candidate):
    like resolve_cert_reqs
    if candidate is None:
        return ssl.PROTOCOL_TLSv1_2

    if isinstance(candidate, str):
        res = getattr(ssl, candidate, None)
        if res is None:
            res = getattr(ssl, 'PROTOCOL_' + candidate)
        return res

    return candidate

and voila, my script can finally contact the server again.

How to set opacity to the background color of a div?

I think rgba is the quickest and easiest!

background: rgba(225, 225, 225, .8)

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

Put the desired launcher image (.png) in drawable folder.

In AndroidManifest.xml, add


under application tag.

How to get number of video views with YouTube API?

Why using any api key to retrieve a portion of public html!

Simplest unix command line demonstrative example, using curl, grep and cut.

curl | grep watch7-views-info | cut -d">" -f8 | cut -d"<" -f1

Yes, it get the full html page, this loss has no meaning against the countless advantages.

How do you change the text in the Titlebar in Windows Forms?

this.Text = "Your Text Here"

Place this under Initialize Component and it should change on form load.

Variably modified array at file scope

Imho this is a flaw in many c compilers. I know for a fact that the compilers i worked with do not store a "static const"variable at an adress but replace the use in the code by the very constant. This can be verified as you will get the same checksum for the produced code when you use a preprocessors #define directive and when you use a static const variable.

Either way you should use static const variables instead of #defines whenever possible as the static const is type safe.

Add SUM of values of two LISTS into new LIST

My answer is repeated with Thiru's that answered it in Mar 17 at 9:25.

It was simpler and quicker, here are his solutions:

The easy way and fast way to do this is:

 three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:

 from numpy import sum
 three = sum([first,second], axis=0) # array([7,9,11,13,15])

You need numpy!

numpy array could do some operation like vectors

import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]

How do I add space between items in an ASP.NET RadioButtonList

<asp:RadioButtonList ID="rbn" runat="server" RepeatLayout="Table" RepeatColumns="2"
                        Width="100%" >
                        <asp:ListItem Text="1"></asp:ListItem>
                        <asp:ListItem Text="2"></asp:ListItem>
                        <asp:ListItem Text="3"></asp:ListItem>
                        <asp:ListItem Text="4"></asp:ListItem>

How to force composer to reinstall a library?

I didn't want to delete all the packages in vendor/ directory, so here is how I did it:

  1. rm -rf vendor/package-i-messed-up
  2. composer install again

Loop through an array in JavaScript

There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.

var i = 0,

// Note this is weak to sparse arrays or falsey values
for ( ; item = myStringArray[i++] ; ){
    item; // This is the string at the index.

Or if you really want to get the id and have a really classical for loop:

var i = 0,
    len = myStringArray.length; // Cache the length

for ( ; i < len ; i++ ){
    myStringArray[i]; // Don't use this if you plan on changing the length of the array

Modern browsers all support iterator methods forEach, map, reduce, filter and a host of other methods on the Array prototype.

PHP - Session destroy after closing browser

If you are confused what to do, just refer to the manual of session_destroy() function:

There you can find some more features of session_destroy().

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

Check if a given key already exists in a dictionary and increment it

As you can see from the many answers, there are several solutions. One instance of LBYL (look before you leap) has not been mentioned yet, the has_key() method:

my_dict = {}

def add (key):
    if my_dict.has_key(key):
        my_dict[key] += 1
        my_dict[key] = 1

if __name__ == '__main__':
    print my_dict

How to exit an if clause

Effectively what you're describing are goto statements, which are generally panned pretty heavily. Your second example is far easier to understand.

However, cleaner still would be:

if some_condition:
   if condition_a:


def your_function2():
   if condition_b:
       # do something
       # and then exit the outer if block
       # more code here

What's the difference between TRUNCATE and DELETE in SQL

TRUNCATE is fast, DELETE is slow.

Although, TRUNCATE has no accountability.

Case-Insensitive List Search

Based on Lance Larsen answer - here's an extension method with the recommended string.Compare instead of string.Equals

It is highly recommended that you use an overload of String.Compare that takes a StringComparison parameter. Not only do these overloads allow you to define the exact comparison behavior you intended, using them will also make your code more readable for other developers. [Josh Free @ BCL Team Blog]

public static bool Contains(this List<string> source, string toCheck, StringComparison comp)
       source != null &&
       !string.IsNullOrEmpty(toCheck) &&
       source.Any(x => string.Compare(x, toCheck, comp) == 0);

How to embed a .mov file in HTML?

Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag


<video controls="controls" width="800" height="600" 
       name="Video Name" src=""></video>

This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)

Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)

How to delete a stash created with git stash create?

git stash drop takes no parameter - which drops the top stash - or a stash reference which looks like: stash@{n} which n nominates which stash to drop. You can't pass a commit id to git stash drop.

git stash drop            # drop top hash, stash@{0}
git stash drop stash@{n}  # drop specific stash - see git stash list

Dropping a stash will change the stash@{n} designations of all stashes further down the stack.

I'm not sure why you think need to drop a stash because if you are using stash create a stash entry isn't created for your "stash" so there isn't anything to drop.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

To share my experience :

Git (my own install) was looking for the key named 'id_rsa'.

So I tried to rename my keys to 'id_rsa' and '' and it worked.

Btw, I'm sure there is an other way to do it but I didn't look deeper yet.

Control the size of points in an R scatterplot?

pch=20 returns a symbol sized between "." and 19.

It's a filled symbol (which is probably what you want).

Aside from that, even the base graphics system in R allows a user fine-grained control over symbol size, color, and shape. E.g.,

dfx = data.frame(ev1=1:10, ev2=sample(10:99, 10), ev3=10:1)

with(dfx, symbols(x=ev1, y=ev2, circles=ev3, inches=1/3,
                  ann=F, bg="steelblue2", fg=NULL))

Graph example

Margin between items in recycler view Android

Use CompatPadding in CardView Item

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

Here is one command that displays the number of threads of a given process :

ps -L -o pid= -p <pid> | wc -l

Unlike the other ps based answers, there is here no need to substract 1 from its output as there is no ps header line thanks to the -o pid=option.

Zoom in on a point (using scale and translate)

One important thing... if you have something like:

body {
  zoom: 0.9;

You need make the equivilent thing in canvas:

canvas {
  zoom: 1.1;

Split function in oracle to comma separated values with automatic sequence

This function returns the nth part of input string MYSTRING. Second input parameter is separator ie., SEPARATOR_OF_SUBSTR and the third parameter is Nth Part which is required.

Note: MYSTRING should end with the separator.


Hope this helps some body, you can use this function like this in a loop to get all the values separated:

    -- do some thing

Here NO_OF_RECORDS,PK_RECORD are temp variables.

Hope this helps.

inline if statement java, why is not working

(inline if) in java won't work if you are using 'if' statement .. the right syntax is in the following example:

int y = (c == 19) ? 7 : 11 ; 


String y = (s > 120) ? "Slow Down" : "Safe";

as You can see the type of the variable Y is the same as the return value ...

in your case it is better to use the normal if statement not inline if as it is in the pervious answer without "?"

if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

You can reinvent the wheel as well:

def fold(f, l, a):
    f: the function to apply
    l: the list to fold
    a: the accumulator, who is also the 'zero' on the first call
    return a if(len(l) == 0) else fold(f, l[1:], f(a, l[0]))

print "Sum:", fold(lambda x, y : x+y, [1,2,3,4,5], 0)

print "Any:", fold(lambda x, y : x or y, [False, True, False], False)

print "All:", fold(lambda x, y : x and y, [False, True, False], True)

# Prove that result can be of a different type of the list's elements
print "Count(x==True):", 
print fold(lambda x, y : x+1 if(y) else x, [False, True, True], 0)

How do I remove javascript validation from my eclipse project?

I actually like MY JavaScript files to be validated, but I definitely don't want to validate and deal with trivial warnings with third party libraries.

That's why I think that turning off validation all together is too drastic. Fortunately with Eclipse, you can selectively remove some JavaScript sources from validation.

  1. Right-click your project.
  2. Navigate to: Properties ? JavaScript ? Include Path
  3. Select Source tab. (It looks identical to Java Build Path Source tab.)
  4. Expand JavaScript source folder.
  5. Highlight Excluded pattern.
  6. Press the Edit button.
  7. Press the Add button next to Exclusion patterns box.
  8. You may either type Ant-style wildcard pattern, or click Browse button to mention the JavaScript source by name.

The information about JavaScript source inclusion/exclusion is saved into .settings/.jsdtscope file. Do not forget to add it to your SCM.

Here is how configuration looks with jQuery files removed from validation:

Eclipse - Project Properties - JavaScript - Include Path

ASP.NET Core 1.0 on IIS error 502.5

I solved it by adding "edit permission" to the application of the site, mapped to the physical directory and then selected the windows user that could have access to this root folder. (private network).

What are the true benefits of ExpandoObject?

Interop with other languages founded on the DLR is #1 reason I can think of. You can't pass them a Dictionary<string, object> as it's not an IDynamicMetaObjectProvider. Another added benefit is that it implements INotifyPropertyChanged which means in the databinding world of WPF it also has added benefits beyond what Dictionary<K,V> can provide you. vs location.hostname and cross-browser compatibility?

Just to add a note that Google Chrome browser has origin attribute for the location. which gives you the entire domain from protocol to the port number as shown in the below screenshot. chrome developers tool

How to scroll page in flutter

Wrap your widget tree inside a SingleChildScrollView

 body: SingleChildScrollView(
child: Stack(
    children: <Widget>[
      new Container(
        decoration: BoxDecoration(
            image: DecorationImage(...),
      new Column(children: [
        new Container(...),
        new Container(...... ),
        new Padding(
          child: SizedBox(
            child: RaisedButton(..),
 ); // Single child scroll view

Remember, SingleChildScrollView can only have one direct widget (Just like ScrollView in Android)

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

Java FileWriter how to write to next Line

I'm not sure if I understood correctly, but is this what you mean?

out.write("this is line 1");
out.write("this is line 2");

jQuery - checkbox enable/disable

$(document).ready(function() {_x000D_
  $('#InventoryMasterError').click(function(event) { //on click_x000D_
    if (this.checked) { // check select status_x000D_
      $('.checkerror').each(function() { //loop through each checkbox_x000D_
        $('#selecctall').attr('disabled', 'disabled');_x000D_
    } else {_x000D_
      $('.checkerror').each(function() { //loop through each checkbox_x000D_
        $('#selecctall').removeAttr('disabled', 'disabled');_x000D_
$(document).ready(function() {_x000D_
  $('#selecctall').click(function(event) { //on click_x000D_
    if (this.checked) { // check select status_x000D_
      $('.checkbox1').each(function() { //loop through each checkbox_x000D_
        $('#InventoryMasterError').attr('disabled', 'disabled');_x000D_
    } else {_x000D_
      $('.checkbox1').each(function() { //loop through each checkbox_x000D_
        $('#InventoryMasterError').removeAttr('disabled', 'disabled');_x000D_
<script src=""></script>_x000D_
<input type="checkbox" id="selecctall" name="selecctall" value="All" />_x000D_
<input type="checkbox" name="data[InventoryMaster][error]" label="" value="error" id="InventoryMasterError" />_x000D_
<input type="checkbox" name="checkid[]" class="checkbox1" value="1" id="InventoryMasterId" />_x000D_
<input type="checkbox" name="checkid[]" class="checkbox1" value="2" id="InventoryMasterId" />

How to get option text value using AngularJS?

The best way is to use the ng-options directive on the select element.


function Ctrl($scope) {
  // sort options
  $scope.products = [{
    value: 'prod_1',
    label: 'Product 1'
  }, {
    value: 'prod_2',
    label: 'Product 2'


<select ng-model="selected_product" 
        ng-options="product as product.label for product in products">           

This will bind the selected product object to the ng-model property - selected_product. After that you can use this:

<p>Ordered by: {{selected_product.label}}</p>


Why is my CSS style not being applied?

I had a similar problem which was caused by a simple mistake in CSS comments.

I had written a comment using the JavaScript // way instead of /* */ which made the subsequent css-class to break but all other CSS work as expected.

Angular 4.3 - HttpClient set params

Another option to do it is:

this.httpClient.get('path', {
    params: Object.entries(data).reduce(
    (params, [key, value]) => params.set(key, value), new HttpParams());

Laravel - Eloquent or Fluent random row

You can also use order_by method with fluent and eloquent like as:


This is a little bit weird usage, but works.

Edit: As @Alex said, this usage is cleaner and also works:


How do I grab an INI value within a shell script?

Here is my version, which parses sections and populates a global associative array g_iniProperties with it. Note that this works only with bash v4.2 and higher.

function parseIniFile() { #accepts the name of the file to parse as argument ($1)
    #declare syntax below (-gA) only works with bash 4.2 and higher
    unset g_iniProperties
    declare -gA g_iniProperties
    while read -r line
        if [[ $line = [*  ]] ; then
            if [[ $line = [* ]] ; then 
                currentSection=$(echo $line | sed -e 's/\r//g' | tr -d "[]")  
            if [[ $line = *=*  ]] ; then
                cleanLine=$(echo $line | sed -e 's/\r//g')
                key=$currentSection.$(echo $cleanLine | awk -F: '{ st = index($0,"=");print  substr($0,0,st-1)}')
                value=$(echo $cleanLine | awk -F: '{ st = index($0,"=");print  substr($0,st+1)}')
    done < $1

And here is a sample code using the function above:

parseIniFile "/path/to/myFile.ini"
for key in "${!g_iniProperties[@]}"; do
    echo "Found key/value $key = ${g_iniProperties[$key]}"

Loop over html table and get checked checkboxes (JQuery)

use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {

Checking something isEmpty in Javascript?


isEmpty_.isEmpty(object) Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.

How can I enable cURL for an installed Ubuntu LAMP stack?


sudo apt-get install php-curl

It worked on a fresh Ubuntu 16.04 (Xenial Xerus) LTS, with lamp-server and php7. I tried with php7-curl - it didn't work and also didn't work with php5-curl.

PostgreSQL, checking date relative to "today"

This should give you the current date minus 1 year:

select now() - interval '1 year';

Accessing MP3 metadata with Python

I would suggest mp3-tagger. Best thing about this is it is distributed under MIT License and supports all the required attributes.

- artist;
- album;
- song;
- track;
- comment;
- year;
- genre;
- band;
- composer;
- copyright;
- url;
- publisher.


from mp3_tagger import MP3File

# Create MP3File instance.
mp3 = MP3File('File_Name.mp3')

# Get all tags.
tags = mp3.get_tags()

It supports set, get, update and delete attributes of mp3 files.

slashes in url variables

You need to escape the slashes as %2F.

scp (secure copy) to ec2 instance without password

scp -i /path/to/your/.pemkey -r /copy/from/path user@server:/copy/to/path

pySerial write() won't take my string

It turns out that the string needed to be turned into a bytearray and to do this I editted the code to


This solved the problem

Oracle SQL: Update a table with data from another table

Update table set column = (select...)

never worked for me since set only expects 1 value - SQL Error: ORA-01427: single-row subquery returns more than one row.

here's the solution:

For i in (select id, name, desc from table1) 
Update table2 set name =, desc = i.desc where id =;

That's how exactly you run it on SQLDeveloper worksheet. They say it's slow but that's the only solution that worked for me on this case.

What does template <unsigned int N> mean?

A template class is like a macro, only a whole lot less evil.

Think of a template as a macro. The parameters to the template get substituted into a class (or function) definition, when you define a class (or function) using a template.

The difference is that the parameters have "types" and values passed are checked during compilation, like parameters to functions. The types valid are your regular C++ types, like int and char. When you instantiate a template class, you pass a value of the type you specified, and in a new copy of the template class definition this value gets substituted in wherever the parameter name was in the original definition. Just like a macro.

You can also use the "class" or "typename" types for parameters (they're really the same). With a parameter of one of these types, you may pass a type name instead of a value. Just like before, everywhere the parameter name was in the template class definition, as soon as you create a new instance, becomes whatever type you pass. This is the most common use for a template class; Everybody that knows anything about C++ templates knows how to do this.

Consider this template class example code:

#include <cstdio>
template <int I>
class foo
  void print()
    printf("%i", I);

int main()
  foo<26> f;
  return 0;

It's functionally the same as this macro-using code:

#include <cstdio>
#define MAKE_A_FOO(I) class foo_##I \
{ \
  void print() \
  { \
    printf("%i", I); \
  } \


int main()
  foo_26 f;
  return 0;

Of course, the template version is a billion times safer and more flexible.

Does it matter what extension is used for SQLite database files?

SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite extension, just so there isn't any ambiguity when I'm looking at my files later.

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

No Software or Plugin required!

(only usable if you don't need recursive deptch)

Use bookmarklet. Drag this link in bookmarks, then edit and paste this code:

(function(){ var arr=[], l=document.links; var ext=prompt("select extension for download (all links containing that, will be downloaded.", ".mp3"); for(var i=0; i<l.length; i++) { if(l[i].href.indexOf(ext) !== false){ l[i].setAttribute("download",l[i].text); l[i].click(); } } })();

and go on page (from where you want to download files), and click that bookmarklet.

How to switch position of two items in a Python list?

you can use for example:

>>> test_list = ['title', 'email', 'password2', 'password1', 'first_name',
                 'last_name', 'next', 'newsletter']
>>> reorder_func = lambda x: x.insert(x.index('password2'),  x.pop(x.index('password2')+1))
>>> reorder_func(test_list)
>>> test_list
... ['title', 'email', 'password1', 'password2', 'first_name', 'last_name', 'next', 'newsletter']

Sorting arrays in javascript by object key value

Here's the same as the current top answer, but in an ES6 one-liner:

myArray.sort((a, b) => a.distance - b.distance);

How to get the current TimeStamp?

Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch() to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.

Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.