Programs & Examples On #Captcha

Captcha is a type of challenge-response test used in computing as an attempt to ensure that the response is given by a human being and not generated by a computer.

How do I show multiple recaptchas on a single page?

A good option is to generate a recaptcha input for each form on the fly (I've done it with two but you could probably do three or more forms). I'm using jQuery, jQuery validation, and jQuery form plugin to post the form via AJAX, along with the Recaptcha AJAX API -

When the user submits one of the forms:

  1. intercept the submission - I used jQuery Form Plugin's beforeSubmit property
  2. destroy any existing recaptcha inputs on the page - I used jQuery's $.empty() method and Recaptcha.destroy()
  3. call Recaptcha.create() to create a recaptcha field for the specific form
  4. return false.

Then, they can fill out the recaptcha and re-submit the form. If they decide to submit a different form instead, well, your code checks for existing recaptchas so you'll only have one recaptcha on the page at a time.

ReCaptcha API v2 Styling

If someone is still interested, there is a simple javascript library (no jQuery dependency), named custom recaptcha. It lets you customize the button with css and implement some js events (ready/checked). The idea is to make the default recaptcha "invisible" and put a button over it. Just change the id of the recaptcha and that's it.

    <script src=""></script>
    <style type="text/css">
        #captcha {
            float: left;
            margin: 2%;

            background-color: rgba(72, 61, 139, 0.5); /* darkslateblue with 50% opacity */
            border-radius: 2px;

            font-size: 1em;
            color: #C0FFEE;

        #captcha.success {
            background-color: rgba(50, 205, 50, 0.5); /* limegreen with 50% opacity */
            color: limegreen;
    <div id="captcha" data-sitekey="your_site_key" data-label="Click here" data-label-spacing="15"></div>

See for more information.

How does Google reCAPTCHA v2 work behind the scenes?

A new paper has been released with several tests against reCAPTCHA:

Some highlights:

  • By keeping a cookie active for +9 days (by browsing sites with Google resources), you can then pass reCAPTCHA by only clicking the checkbox;
  • There are no restrictions based on requests per IP;
  • The browser's user agent must be real, and Google run tests against your environment to ensure it matches the user agent;
  • Google tests if the browser can render a Canvas;
  • Screen resolution and mouse events don't affect the results;

Google has already fixed the cookie vulnerability and is probably restricting some behaviors based on IPs.

Another interesting finding is that Google runs a VM in JavaScript that obfuscates much of reCAPTCHA code and behavior. This VM is known as botguard and is used to protect other services besides reCAPTCHA:


A recent paper (from August) was published on WOOT 2017 achieving 85% accuracy in solving noCAPTCHA reCAPTCHA audio challenges:


Google is introducing reCAPTCHA v3, which looks like a "human score prediction engine" that is calibrated per website. It can be installed into different pages of a website (working like a Google Analytics script) to help reCAPTCHA and the website owner to understand the behaviour of humans vs. bots before filling a reCAPTCHA.

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

In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db

The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!

Totally depends on your usage scenario I suppose.

How to get current memory usage in android?

public static boolean isAppInLowMemory(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();

    return memoryInfo.lowMemory;

Starting iPhone app development in Linux?

The answer to this really depends on whether or not you want to develop apps that are then distributed through the iPhone store. If you don't, and don't mind developing for the "jailbroken" iPhone crowd - then it's possible to develop from Linux.

Check this chap's page for a comprehensive (if a little complex) guide on what to do :

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

I was missing System.Data.Entity dll reference and problem was solved

How to Set Focus on Input Field using JQuery

Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus() creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).

Inspired by , I added autofocus attribute to the input field and voila!

function addfield() {
    n=$('table tr').length;
    $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');

How to print a dictionary line by line in Python?

This will work if you know the tree only has two levels:

for k1 in cars:
    d = cars[k1]
    for k2 in d
        print(k2, ':', d[k2])

How to remove a branch locally?

As far I can understand the original problem, you added commits to local master by mistake and did not push that changes yet. Now you want to cancel your changes and hope to delete your local changes and to create a new master branch from the remote one.

You can just reset your changes and reload master from remote server:

git reset --hard origin/master

make: Nothing to be done for `all'

I think you missed a tab in 9th line. The line following all:hello must be a blank tab. Make sure that you have a blank tab in 9th line. It will make the interpreter understand that you want to use default recipe for makefile.

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

Which font is used in Visual Studio Code Editor and how to change fonts?

Go to Preferences > User Settings. (Alternatively, Ctrl + , / Cmd + , on macOS)

Then you can type inside the JSON object any settings you want to override. User settings are per user. You can also configure workspace settings, which are for the project that you are currently working on.

Here's an example:

// Controls the font family.
"editor.fontFamily": "Consolas",

// Controls the font size.
"editor.fontSize": 13

Useful links:

How to reset AUTO_INCREMENT in MySQL?

Best way is remove the field with AI and add it again with AI, works for all tables

How to serialize an object to XML without getting xmlns="..."?

If you want to remove the namespace you may also want to remove the version, to save you searching I've added that functionality so the below code will do both.

I've also wrapped it in a generic method as I'm creating very large xml files which are too large to serialize in memory so I've broken my output file down and serialize it in smaller "chunks":

    public static string XmlSerialize<T>(T entity) where T : class
        // removes version
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;

        XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
        using (StringWriter sw = new StringWriter())
        using (XmlWriter writer = XmlWriter.Create(sw, settings))
            // removes namespace
            var xmlns = new XmlSerializerNamespaces();
            xmlns.Add(string.Empty, string.Empty);

            xsSubmit.Serialize(writer, entity, xmlns);
            return sw.ToString(); // Your XML

Angular.js ng-repeat filter by property having one of multiple values (OR of values)


<div ng-repeat="product in products | filter: colorFilter">

In Angular:

$scope.colorFilter = function (item) { 
  if (item.color === 'red' || item.color === 'blue') {
  return item;

how to iterate through dictionary in a dictionary in django template?

Lets say your data is -

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

You can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.


    {% for key, values in data.items %}
        {% for v in values[0] %}
        {% endfor %}
    {% endfor %}

Am pretty sure you can extend this logic to your specific dict.

To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.

return render_to_response('some_page.html', {'data': sorted(data.items())})

In template file:

{% for key, value in data %}
        <td> Key: {{ key }} </td> 
        <td> Value: {{ value }} </td>
{% endfor %}

Get the Last Inserted Id Using Laravel Eloquent

For get last inserted id in database You can use

$data = new YourModelName;
$data->name = 'Some Value';
$data->email = '[email protected]';
$lastInsertedId = $data->id;

here $lastInsertedId will gives you last inserted auto increment id.

using favicon with css

You can't set a favicon from CSS - if you want to do this explicitly you have to do it in the markup as you described.

Most browsers will, however, look for a favicon.ico file on the root of the web site - so if you access most browsers will look for automatically.

Send multipart/form-data files with angular using $http

Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.

Angular 5 Solution:

import {HttpClient} from '@angular/common/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = {} as any; // Set any options you like
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(, file)

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);

  // Send it.
  return, formData, options)
    .catch((e) => {
      // handle me

Angular 4 Solution:

// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(, file)

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);

  // Send it.
  return, formData, options)
    .catch((e) => {
      // handle me

Convert sqlalchemy row object to python dict

Python 3.6.8+

The builtin str() method automatically converts datetime.datetime objects to iso-8806-1.

print(json.dumps([dict(row.items()) for row in rows], default=str, indent="  "))

NOTE: The default func will only be applied to a value if there's an error so int and float values won't be converted... unless there's an error :).

error: pathspec 'test-branch' did not match any file(s) known to git

This error can also appear if your git branch is not correct even though case sensitive wise. In my case I was getting this error as actual branch name was "CORE-something" but I was taking pull like "core-something".

Associative arrays in Shell scripts

several years ago I wrote script library for bash which supported associative arrays among other features (logging, configuration files, extended support for command line argument, generate help, unit testing, etc). The library contains a wrapper for associative arrays and automatically switches to appropriate model (internal for bash4 and emulate for previous versions). It was called shell-framework and hosted at but today the resource is closed. If someone still needs it I can share it with you.

Add data dynamically to an Array

Like this?:

$array[] = 'newItem';

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

@papigee should work on Windows 10 just fine. I'm using the integrated VSCode terminal with git bash and this always works for me.

winpty docker exec -it <container-id> //bin//sh

Is it possible to put CSS @media rules inline?

You can use image-set()

<div style="
  background-image: url(icon1x.png);
  background-image: -webkit-image-set(  
    url(icon1x.png) 1x,  
    url(icon2x.png) 2x);  
  background-image: image-set(  
    url(icon1x.png) 1x,  
    url(icon2x.png) 2x);">

How can I run a PHP script in the background after a form is submitted?

Use Amphp to execute jobs in parallel & asynchronously.

Install the library

composer require amphp/parallel-functions

Code sample


require "vendor/autoload.php";

use Amp\Promise;
use Amp\ParallelFunctions;

echo 'started</br>';

$promises[1] = ParallelFunctions\parallel(function (){
    // Send Email

$promises[2] = ParallelFunctions\parallel(function (){
    // Send SMS


echo 'finished';

Fo your use case, You can do something like below


use function Amp\ParallelFunctions\parallelMap;
use function Amp\Promise\wait;

$responses = wait(parallelMap([
    '[email protected]',
    '[email protected]',
    '[email protected]',
], function ($to) {
    return send_mail($to);

How to create a 100% screen width div inside a container in bootstrap?

2019's answer as this is still actively seen today

You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.

original hack from 2015 that still works in some situations

You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.

If you cannot pull it out of the div for some reason, you should change the position style with this css:

.full-width-div {
    position: absolute;
    width: 100%;
    left: 0;

Instead of absolute, you could also use fixed, but then it will not move as you scroll.

Python nonlocal statement

Quote from the Python 3 Reference:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.

As said in the reference, in case of several nested functions only variable in the nearest enclosing function is modified:

def outer():
    def inner():
        def innermost():
            nonlocal x
            x = 3

        x = 2
        if x == 3: print('Inner x has been modified')

    x = 1
    if x == 3: print('Outer x has been modified')

x = 0
if x == 3: print('Global x has been modified')

# Inner x has been modified

The "nearest" variable can be several levels away:

def outer():
    def inner():
        def innermost():
            nonlocal x
            x = 3


    x = 1
    if x == 3: print('Outer x has been modified')

x = 0
if x == 3: print('Global x has been modified')

# Outer x has been modified

But it cannot be a global variable:

def outer():
    def inner():
        def innermost():
            nonlocal x
            x = 3



x = 0
if x == 3: print('Global x has been modified')

# SyntaxError: no binding for nonlocal 'x' found

LINQ Group By and select collection

you may also like this

var Grp = Model.GroupBy(item => item.Order.Customer)
      .Select(group => new 
             Customer = Model.First().Customer, 
             CustomerId= group.Key,  
             Orders= group.ToList() 

Chosen Jquery Plugin - getting selected values

if you want to get text of a selected option (chosen get display selected value)

 $("#select-id").chosen().find("option:selected" ).text();

Group array items using object

You can extend array functionality with the next:

Array.prototype.groupBy = function(prop) {
  var result = this.reduce(function (groups, item) {
      const val = item[prop];
      groups[val] = groups[val] || [];
      return groups;
  }, {});
  return Object.keys(result).map(function(key) {
      return result[key];

Usage example:

/* re-usable function */_x000D_
Array.prototype.groupBy = function(prop) {_x000D_
  var result = this.reduce(function (groups, item) {_x000D_
      const val = item[prop];_x000D_
      groups[val] = groups[val] || [];_x000D_
      return groups;_x000D_
  }, {});_x000D_
  return Object.keys(result).map(function(key) {_x000D_
      return result[key];_x000D_
var myArray = [_x000D_
  {group: "one", color: "red"},_x000D_
  {group: "two", color: "blue"},_x000D_
  {group: "one", color: "green"},_x000D_
  {group: "one", color: "black"}_x000D_

Credits: @Wahinya Brian

Print a div content using Jquery

First include the header

<script src="" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> 

<script type="text/JavaScript" src=""></script>

As you are using a print function with a selector which is a part of print.js so you need to call them before you use it...


will do it

$("#btn").click(function () {


$("#btn").on('click',function () {

//Learn more:

How do you print in Sublime Text 2

Still no print no native print function, but outside the installing the suggested package, you can go the autohotkey way, as the that app can actually help you run macros for other stuff as well. So you can do something like create a macro that with one click does:

  1. Select all the text
  2. Copies all the text
  3. Opens your other edit of choice
  4. pastes text
  5. Prints text

No the most glamorous of options but could also work if the receiving app has can accept code-formatting.

Could not find folder 'tools' inside SDK

In my case i was using Ubuntu. Where the was two directories one was /android-sdks and /android-sdk-linux. I used the second one it works for me :)

Add CSS to <head> with JavaScript?

Here's a simple way.

 * Add css to the document
 * @param {string} css
function addCssToDocument(css){
  var style = document.createElement('style')
  style.innerText = css

what is the use of fflush(stdin) in c programming

It's not in standard C, so the behavior is undefined.

Some implementation uses it to clear stdin buffer.

From C11 The fflush function, fflush works only with output/update stream, not input stream.

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

C++ correct way to return pointer to array from function

A variable referencing an array is basically a pointer to its first element, so yes, you can legitimately return a pointer to an array, because thery're essentially the same thing. Check this out yourself:

#include <assert.h>

int main() {
  int a[] = {1, 2, 3, 4, 5}; 

  int* pArr = a;
  int* pFirstElem = &(a[0]);

  assert(a == pArr);
  assert(a == pFirstElem);

  return 0;

This also means that passing an array to a function should be done via pointer (and not via int in[5]), and possibly along with the length of the array:

int* test(int* in, int len) {
    int* out = in;
    return out;

That said, you're right that using pointers (without fully understanding them) is pretty dangerous. For example, referencing an array that was allocated on the stack and went out of scope yields undefined behavior:

#include <iostream>

using namespace std;

int main() {
  int* pArr = 0;
    int a[] = {1, 2, 3, 4, 5};
    pArr = a; // or test(a) if you wish
  // a[] went out of scope here, but pArr holds a pointer to it

  // all bets are off, this can output "1", output 1st chapter
  // of "Romeo and Juliet", crash the program or destroy the
  // universe
  cout << pArr[0] << endl; // WRONG!

  return 0;

So if you don't feel competent enough, just use std::vector.

[answer to the updated question]

The correct way to write your test function is either this:

void test(int* a, int* b, int* c, int len) {
  for (int i = 0; i < len; ++i) c[i] = a[i] + b[i];
int main() {
   int a[5] = {...}, b[5] = {...}, c[5] = {};
   test(a, b, c, 5);
   // c now holds the result

Or this (using std::vector):

#include <vector>

vector<int> test(const vector<int>& a, const vector<int>& b) {
  vector<int> result(a.size());
  for (int i = 0; i < a.size(); ++i) {
    result[i] = a[i] + b[i];
  return result; // copy will be elided

How to print the data in byte array as characters?

Try this one : new String(byte[])

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You're talking about template literals.

They allow for both multiline strings and string interpolation.

Multiline strings:

// foo_x000D_
// bar

String interpolation:

var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar

The result of a query cannot be enumerated more than once

Try explicitly enumerating the results by calling ToList().


foreach (var item in query)


foreach (var item in query.ToList())

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;

ArrayList<String> recordings = new ArrayList<String>();

this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.

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

Just simply use isset($_POST['radio']) so that whenever i click any of the radio button, the one that is clicked is set to the post.

 <form method="post" action="sample.php">
 select sex: 
 <input type="radio" name="radio" value="male">
 <input type="radio" name="radio" value="female">

 <input type="submit" value="submit">


if (isset($_POST['radio'])){

    $Sex = $_POST['radio'];

python pandas remove duplicate columns

First step:- Read first row i.e all columns the remove all duplicate columns.

Second step:- Finally read only that columns.

cols = pd.read_csv("file.csv", header=None, nrows=1).iloc[0].drop_duplicates()
df = pd.read_csv("file.csv", usecols=cols)

How to replace a whole line with sed?

You can also use sed's change line to accomplish this:

sed -i "/aaa=/c\aaa=xxx" your_file_here

This will go through and find any lines that pass the aaa= test, which means that the line contains the letters aaa=. Then it replaces the entire line with aaa=xxx. You can add a ^ at the beginning of the test to make sure you only get the lines that start with aaa= but that's up to you.

Search in all files in a project in Sublime Text 3

You can search a directory using Find ? Find in files. This also includes all opened tabs.

The keyboard shortcut is Ctrl?+F on non-Mac (regular) keyboards, and ??+F on a Mac.

You'll be presented with three boxes: Find, Where and Replace. It's a regular Find/Find-replace search where Where specifies a file or directory to search. I for example often use a file name or . for searching the current directory. There are also a few special constructs that can be used within the Where field:

<project>,<current file>,<open files>,<open folders>,-*.doc,*.txt

Note that these are not placeholders, you type these verbatim. Most of them are self-explanatory (e.g. -*.doc excludes files with a .doc extension).

Pressing the ... to the right will present you with all available options.

After searching you'll be presented with a Find results page with all of your matching results. To jump to specific lines and files from it you simply double-click on a line.

Insert NULL value into INT column

2 ways to do it

insert tbl (other, col1, intcol) values ('abc', 123, NULL)

or just omit it from the column list

insert tbl (other, col1) values ('abc', 123)

PHP multiline string with PHP

You cannot run PHP code within a string like that. It just doesn't work. As well, when you're "out" of PHP code (?>), any text outside of the PHP blocks is considered output anyway, so there's no need for the echo statement.

If you do need to do multiline output from with a chunk of PHP code, consider using a HEREDOC:


$var = 'Howdy';

echo <<<EOL
This is output
And this is a new line
blah blah blah and this following $var will actually say Howdy as well

and now the output ends

Maven Unable to locate the Javac Compiler in:

None of the current answers helped me here. We were getting something like:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:
    #.#.#:compile (default-compile) on project Streaming_Test: Compilation failure
[ERROR] Unable to locate the Javac Compiler in:
[ERROR] /opt/java/J7.0/../lib/tools.jar

This happens because the Java installation has determined that it is a JRE installation. It's expecting there to be JDK stuff above the JRE subdirectory, hence the ../lib in the path. Our tools.jar is in $JAVA_HOME/lib/tools.jar not in $JAVA_HOME/../lib/tools.jar.

Unfortunately, we do not have an option to install a JDK on our OS (don't ask) so that wasn't an option. I fixed the problem by adding the following to the maven pom.xml:

      <fork>true</fork>  <!-- not sure if this is also needed -->
      <!--        ^^^^^^^^^^^^^^^^^^^^^^ -->

By pointing the executable to the right place this at least got past our compilation failures.

How to force composer to reinstall a library?

As user @aaracrr pointed out in a comment on another answer probably the best answer is to re-require the package with the same version constraint.


composer require vendor/package

or specifying a version constraint

composer require vendor/package:^1.0.0

How to set Apache Spark Executor memory

The answer submitted by Grega helped me to solve my issue. I am running Spark locally from a python script inside a Docker container. Initially I was getting a Java out-of-memory error when processing some data in Spark. However, I was able to assign more memory by adding the following line to my script:

conf.set("spark.driver.memory", "4g") 

Here is a full example of the python script which I use to start Spark:

import os
import sys
import glob

spark_home = '<DIRECTORY WHERE SPARK FILES EXIST>/spark-2.0.0-bin-hadoop2.7/'

if 'SPARK_HOME' not in os.environ:
    os.environ['SPARK_HOME'] = spark_home 

SPARK_HOME = os.environ['SPARK_HOME']

for lib in glob.glob(os.path.join(SPARK_HOME, "python", "lib", "*.zip")):

from pyspark import SparkContext
from pyspark import SparkConf
from pyspark.sql import SQLContext

conf.set("spark.executor.memory", "4g")
conf.set("spark.driver.memory", "4g")
conf.set("spark.cores.max", "2")

sc = SparkContext.getOrCreate(conf)

spark = SQLContext(sc)

Use of var keyword in C#

Don't use that, makes your code unreadable.

ALWAYS use as strict typing as possible, crutches only makes your life hell.

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as


If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as


UICollectionView Self Sizing Cells with Auto Layout

I did a dynamic cell height of collection view. Here is git hub repo.

And, dig out why preferredLayoutAttributesFittingAttributes is called more than once. Actually, it will be called at least 3 times.

The console log picture : enter image description here

1st preferredLayoutAttributesFittingAttributes:

(lldb) po layoutAttributes
<UICollectionViewLayoutAttributes: 0x7fa405c290e0> index path: (<NSIndexPath:    0xc000000000000016> 
{length = 2, path = 0 - 0}); frame = (15 12; 384 57.5); 

(lldb) po self.collectionView
<UICollectionView: 0x7fa40606c800; frame = (0 57.6667; 384 0);

The layoutAttributes.frame.size.height is current status 57.5.

2nd preferredLayoutAttributesFittingAttributes:

(lldb) po layoutAttributes
<UICollectionViewLayoutAttributes: 0x7fa405c16370> index path: (<NSIndexPath: 0xc000000000000016> 
{length = 2, path = 0 - 0}); frame = (15 12; 384 534.5); 

(lldb) po self.collectionView
<UICollectionView: 0x7fa40606c800; frame = (0 57.6667; 384 0);

The cell frame height changed to 534.5 as our expected. But, the collection view still zero height.

3rd preferredLayoutAttributesFittingAttributes:

(lldb) po layoutAttributes
<UICollectionViewLayoutAttributes: 0x7fa403d516a0> index path: (<NSIndexPath: 0xc000000000000016> 
{length = 2, path = 0 - 0}); frame = (15 12; 384 534.5); 

(lldb) po self.collectionView
<UICollectionView: 0x7fa40606c800; frame = (0 57.6667; 384 477);

You can see the collection view height was changed from 0 to 477.

The behavior is similar to handle scroll:

1. Before self-sizing cell

2. Validated self-sizing cell again after other cells recalculated.

3. Did changed self-sizing cell

At beginning, I thought this method only call once. So I coded as the following:

CGRect frame = layoutAttributes.frame;
frame.size.height = frame.size.height + self.collectionView.contentSize.height;
UICollectionViewLayoutAttributes* newAttributes = [layoutAttributes copy];
newAttributes.frame = frame;
return newAttributes;

This line:

frame.size.height = frame.size.height + self.collectionView.contentSize.height;

will cause system call infinite loop and App crash.

Any size changed, it will validate all cells' preferredLayoutAttributesFittingAttributes again and again until every cells' positions (i.e frames) are no more change.

When to use static keyword before global variables?

global static variables are initialized at compile-time unlike automatic

What is the best Java library to use for HTTP POST, GET etc.?

I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient

I would also recommend to take a look at HtmlUnit. HtmlUnit is a "GUI-Less browser for Java programs".

How do I exit a while loop in Java?

Take a look at the Java™ Tutorials by Oracle.

But basically, as dacwe said, use break.

If you can it is often clearer to avoid using break and put the check as a condition of the while loop, or using something like a do while loop. This isn't always possible though.

how to display a javascript var in html body

<script type="text/javascript">
var number = 123;
var string = "abcd";

function docWrite(variable) {

<h1>the value for number is: <script>docWrite(number)</script></h1>

<h2>the text is: <script>docWrite(string)</script> </h2>

You can shorten document.write but can't avoid <script> tag

Extract / Identify Tables from PDF python

You should definitely have a look at this answer of mine:

and also have a look at all the links included therein.

Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.

What is the best regular expression to check if a string is a valid URL?

Mathias Bynens has a great article on the best comparison of a lot of regular expressions: In search of the perfect URL validation regex

The best one posted is a little long, but it matches just about anything you can throw at it.

JavaScript version


PHP version


React: why child component doesn't update when prop changes

In my case I was updating a loading state that was passed down to a component. Within the Button the props.loading was coming through as expected (switching from false to true) but the ternary that showed a spinner wasn't updating.

I tried adding a key, adding a state that updated with useEffect() etc but none of the other answers worked.

What worked for me was changing this:


To this:

setTimeout(() => { handleOtherCPUHeavyCode() }, 1)

I assume it's because the process in handleOtherCPUHeavyCode is pretty heavy and intensive so the app freezes for a second or so. Adding the 1ms timeout allows the loading boolean to update and then the heavy code function can do it's work.

What does %>% function mean in R?

%...% operators

%>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

"%,%" <- function(x, y) paste0(x, ", ", y)

# test run

"Hello" %,% "World"
## [1] "Hello, World"

The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See

igraph This package defines %--% , %->% and %<-% to select edges.

lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .


magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See

magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%, %<>% and %$% and for even more details.

dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% and can be used as an alternative to it. See

The pipeR package also has defined a number of other such operators too. See:

postlogic The postlogic package defined %if% and %unless% operators.

wrapr The R package, wrapr, defines a dot pipe %.>% that is an explicit version of %>% in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%. See

Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in The idea is that instead of writing:

1:8 %>% sum %>% sqrt
## [1] 6

one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.) . We follow that with a semicolon.

1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6

Update Added info on expm package and simplified example at top. Added postlogic package.

Why is Ant giving me a Unsupported major.minor version error

In my case, the project was a Maven, I had JDK 1.8.0, Eclipse : Kepler, and I installed the M2Eclipse plugin from Eclipse Marketplace.

Changing compiler level didn't help.

Finally I used latest version of eclipse (Luna), compiler level 1.7, same M2Eclipse plugin and problem was solved.

Comments in Android Layout xml

Comments INSIDE tags possible

It's possible to create custom attributes that can be used for commenting/documentation purposes.

In the example below, a documentation:info attribute is defined, with an example comment value:

    documentation:info="This is an example comment" >

        documentation:purpose="Instructions label"
        android:text="Click here to begin."
        documentation:info="Another example comment"
        documentation:translation_notes="This control should use the fewest characters possible, as space is limited"


Note that in this case, is just a definition for the new custom XML namespace (of documentation), and is thus just a unique URI string - it can be anything as long as it's unique. The documentation to the right of the xmlns: can also be anything - this works the same way that the android: XML namespace is defined and used.

Using this format, any number of attributes can be created, such as documentation:info, documentation:translation_notes etc., along with a description value, the format being the same as any XML attribute.

In summary:

  • Add a xmls:my_new_namespace attribute to the root (top-level) XML element in the XML layout file. Set its value to a unique string
  • Under any child XML element within the file, use the new namespace, and any word following to define comment tags that are ignored when compiled, e.g. <TextView my_new_namespace:my_new_doc_property="description" />

how to use sqltransaction in c#

First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like

sqlCommand.Transaction = transaction;

And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like

sqlCommand.CommandText = "select * from table1";
sqlCommand.CommandText = "select * from table2";

Returning http status code from Web Api controller

Another option:

return new NotModified();

public class NotModified : IHttpActionResult
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        var response = new HttpResponseMessage(HttpStatusCode.NotModified);
        return Task.FromResult(response);

Equivalent to 'app.config' for a library (DLL)

use from configurations must be very very easy like this :

var config = new MiniConfig("setting.conf");

config.AddOrUpdate("port", "1580");

if (config.TryGet("port", out int port)) // if config exist

for more details see MiniConfig

Change the color of a checked menu item in a navigation drawer

One need to set NavigateItem checked true whenever item in NavigateView is clicked

//listen for navigation events
NavigationView navigationView = (NavigationView)findViewById(;
// select the correct nav menu item

Add NavigationItemSelectedListener on NavigationView

  public boolean onNavigationItemSelected(final MenuItem menuItem) {
    // update highlighted item in the navigation menu
    mNavItemId = menuItem.getItemId();

    // allow some time after closing the drawer before performing real navigation
    // so the user can see what is happening
    mDrawerActionHandler.postDelayed(new Runnable() {
      public void run() {
    return true;

Oracle PL/SQL : remove "space characters" from a string

Shorter version of:

REGEXP_REPLACE( my_value, '[[:space:]]', '' )

Would be:

REGEXP_REPLACE( my_value, '\s')

Neither of the above statements will remove "null" characters.

To remove "nulls" encase the statement with a replace

Like so:

REPLACE(REGEXP_REPLACE( my_value, '\s'), CHR(0))

Best way to iterate through a Perl array

1 is substantially different from 2 and 3, since it leaves the array in tact, whereas the other two leave it empty.

I'd say #3 is pretty wacky and probably less efficient, so forget that.

Which leaves you with #1 and #2, and they do not do the same thing, so one cannot be "better" than the other. If the array is large and you don't need to keep it, generally scope will deal with it (but see NOTE), so generally, #1 is still the clearest and simplest method. Shifting each element off will not speed anything up. Even if there is a need to free the array from the reference, I'd just go:

undef @Array;

when done.

  • NOTE: The subroutine containing the scope of the array actually keeps the array and re-uses the space next time. Generally, that should be fine (see comments).

How to make a page redirect using JavaScript?

You can achieve this using the location object.

location.href = "http://someurl"; 

VBA: Selecting range by variables

I ran into something similar - I wanted to create a range based on some variables. Using the Worksheet.Cells did not work directly since I think the cell's values were passed to Range.

This did work though:

Range(Cells(1, 1).Address(), Cells(lastRow, lastColumn).Address()).Select

That took care of converting the cell's numerical location to what Range expects, which is the A1 format.

Visual Studio Code includePath

This answer maybe late but I just happened to fix the issue. Here is my c_cpp_properties.json file:

"configurations": [
        "name": "Linux",
        "includePath": [
        "defines": [],
        "compilerPath": "/usr/bin/gcc",
        "cStandard": "c11",
        "cppStandard": "c++14",
        "intelliSenseMode": "clang-x64"
"version": 4


Assert a function/method was not called using Mock

This should work for your case;

assert not my_var.called, 'method should not have been called'


>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have been'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: a was called and should not have been

PowerShell: Create Local User Account

As of PowerShell 5.1 there cmdlet New-LocalUser which could create local user account.

Example of usage:

Create a user account

New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword

or Create a user account that has a password

$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."

or Create a user account that is connected to a Microsoft account

New-LocalUser -Name "MicrosoftAccount\usr [email protected]" -Description "Description of this account." 

Importing Maven project into Eclipse

Since Eclipse Neon which contains Eclipse Maven Integration (m2e) 1.7, the preferred way is one of the following ways:

  • File > Projects from File System... - This works for Eclipse projects (containing the file .project) as well as for non-Eclipse projects that only contain the file pom.xml.
  • If importing from a Git repository, in the Git Repositories view right-click the repository node, one folder or multiple selected folders in the Working Tree and choose Import Projects.... This opens the same dialog, but you don't have to select the directory.

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

You can use the overflow property

style="overflow: scroll ;max-height: 250px; width: 50%;"

Saving an image in OpenCV

On OSX, saving video frames and still images only worked for me when I gave a full path to cvSaveImage:


Could you explain STA and MTA?

I find the existing explanations too gobbledygook. Here's my explanation in plain English:

STA: If a thread creates a COM object that's set to STA (when calling CoCreateXXX you can pass a flag that sets the COM object to STA mode), then only this thread can access this COM object (that's what STA means - Single Threaded Apartment), other thread trying to call methods on this COM object is under the hood silently turned into delivering messages to the thread that creates(owns) the COM object. This is very much like the fact that only the thread that created a UI control can access it directly. And this mechanism is meant to prevent complicated lock/unlock operations.

MTA: If a thread creates a COM object that's set to MTA, then pretty much every thread can directly call methods on it.

That's pretty much the gist of it. Although technically there're some details I didn't mention, such as in the 'STA' paragraph, the creator thread must itself be STA. But this is pretty much all you have to know to understand STA/MTA/NA.

How to change the docker image installation directory?

On Fedora 26 and probably many other versions, you may encounter an error after moving your base folder location as described above. This is particularly true if you are moving it to somewhere under /home. This is because SeLinux kicks in and prevents the docker container from running many of its programs from under this location.

The short solution is to remove the --enable-selinux option when you add the -g parameter.

Business logic in MVC

The term business logic is in my opinion not a precise definition. Evans talks in his book, Domain Driven Design, about two types of business logic:

  • Domain logic.
  • Application logic.

This separation is in my opinion a lot clearer. And with the realization that there are different types of business rules also comes the realization that they don't all necessarily go the same place.

Domain logic is logic that corresponds to the actual domain. So if you are creating an accounting application, then domain rules would be rules regarding accounts, postings, taxation, etc. In an agile software planning tool, the rules would be stuff like calculating release dates based on velocity and story points in the backlog, etc.

For both these types of application, CSV import/export could be relevant, but the rules of CSV import/export has nothing to do with the actual domain. This kind of logic is application logic.

Domain logic most certainly goes into the model layer. The model would also correspond to the domain layer in DDD.

Application logic however does not necessarily have to be placed in the model layer. That could be placed in the controllers directly, or you could create a separate application layer hosting those rules. What is most logical in this case would depend on the actual application.

How do I create a new branch?

Right click and open SVN Repo-browser:

Enter image description here

Right click on Trunk (working copy) and choose Copy to...:

Enter image description here

Input the respective branch's name/path:

Enter image description here

Click OK, type the respective log message, and click OK.

How do I divide in the Linux console?

Better way is to use "bc", an arbitrary precision calculator.

variable=$(echo "OPTIONS; OPERATIONS" | bc)


my_var=$(echo "scale=5; $temp_var/100 + $temp_var2" | bc)

where "scale=5" is accuracy.

man bc 

comes with several usage examples.

Sort Pandas Dataframe by Date

The data containing the date column can be read by using the below code:

data = pd.csv(file_path,parse_dates=[date_column])

Once the data is read by using the above line of code, the column containing the information about the date can be accessed using pd.date_time() like:

pd.date_time(data[date_column], format = '%d/%m/%y')

to change the format of date as per the requirement.

Switch firefox to use a different DNS than what is in the file

I use this to override system's DNS with localserver
in about:config
change this value:

  • network.dns.forceResolve
  • network.dns.ipv4OnlyDomains
  • network.dns.localDomains
  • with IP address of local DNS server (for exsample
    Sorry for my english

    Is it possible to style html5 audio tag?

    If you want to style the browsers standard music player in the CSS:

    audio {
        enter code here;

    Convert string to variable name in JavaScript

    You can access the window object as an associative array and set it that way

    window["onlyVideo"] = "TEST";

    How can I add the new "Floating Action Button" between two widgets/layouts

    Best practice:

    • Add compile '' to gradle file
    • Use CoordinatorLayout as root view.
    • Add layout_anchorto the FAB and set it to the top view
    • Add layout_anchorGravity to the FAB and set it to: bottom|right|end

    enter image description here


    Select SQL Server database size

    This query generates size for both log and data in MB as well as GB

    SELECT X.database_name,
           X.log_size_mb / 1024 AS log_size_gb,
           X.row_size_mb / 1024 AS row_size_gb,
           X.total_size_mb / 1024 AS total_size_gb
      FROM (SELECT database_name = DB_NAME(database_id),
                      log_size_mb = CAST(SUM(CASE
                                                  WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8, 2)),
                      row_size_mb = CAST(SUM(CASE
                                                  WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8, 2)),
                      total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8, 2))
                FROM sys.master_files WITH (NOWAIT)
                WHERE database_id = DB_ID() -- current db by default
                GROUP BY database_id) AS X

    Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities


    O(2N) denotes an algorithm whose growth doubles with each additon to the input data set. The growth curve of an O(2N) function is exponential - starting off very shallow, then rising meteorically. An example of an O(2N) function is the recursive calculation of Fibonacci numbers:

    int Fibonacci (int number)
    if (number <= 1) return number;
    return Fibonacci(number - 2) + Fibonacci(number - 1);

    How to select between brackets (or quotes or ...) in Vim?

    This method of selection is built-in and well covered in the Vim help. It covers XML tags and more.

    See :help text-objects.

    WPF Application that only has a tray icon

    I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

    If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

    • Rich ToolTips rather than text
    • WPF context menus and popups
    • Command support and routed events
    • Flexible data binding
    • Rich balloon messages rather than the default messages provides by the OS

    Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

    Create array of all integers between two numbers, inclusive, in Javascript/jQuery

    Solving in underscore

    data = [];
    _.times( highEnd, function( n ){ data.push( lowEnd ++ ) } );

    Find a file by name in Visual Studio Code

    I believe the action name is "workbench.action.quickOpen".

    How to get a list column names and datatypes of a table in PostgreSQL?

    A version that supports finding the column names and types of a table in a specific schema, and uses JOINs without any subqueries

        pg_attribute.attname AS column_name,
        pg_catalog.format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS data_type
        pg_catalog.pg_class ON pg_class.oid = pg_attribute.attrelid
        pg_catalog.pg_namespace ON pg_namespace.oid = pg_class.relnamespace
        pg_attribute.attnum > 0
        AND NOT pg_attribute.attisdropped
        AND pg_namespace.nspname = 'my_schema'
        AND pg_class.relname = 'my_table'
        attnum ASC;

    How do I print bytes as hexadecimal?

    This is a modified version of the Nibble to Hex method

    void hexArrayToStr(unsigned char* info, unsigned int infoLength, char **buffer) {
        const char* pszNibbleToHex = {"0123456789ABCDEF"};
        int nNibble, i;
        if (infoLength > 0) {
            if (info != NULL) {
                *buffer = (char *) malloc((infoLength * 2) + 1);
                buffer[0][(infoLength * 2)] = 0;
                for (i = 0; i < infoLength; i++) {
                    nNibble = info[i] >> 4;
                    buffer[0][2 * i] = pszNibbleToHex[nNibble];
                    nNibble = info[i] & 0x0F;
                    buffer[0][2 * i + 1] = pszNibbleToHex[nNibble];
            } else {
                *buffer = NULL;
        } else {
            *buffer = NULL;

    How do I remove/delete a virtualenv?

    if you are windows user, then it's in C:\Users\your_user_name\Envs. You can delete it from there.

    Also try in command prompt rmvirtualenv environment name.

    I tried with command prompt so it said deleted but it was still existed. So i manually delete it.

    WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

    If you have <deployment retail="true"/> in your .NET Framework's machine.config, you won't see detailed error messages. Make sure that setting is false, or not present.

    How to change icon on Google map marker

    var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(23.016427,72.571156),
                    map: map,
                    icon: 'images/map_marker_icon.png',
                    title: 'Hi..!'

    apply local path on icon only

    Is it possible to import modules from all files in a directory, using a wildcard?

    You can use require as well:

    const moduleHolder = []
    function loadModules(path) {
      let stat = fs.lstatSync(path)
      if (stat.isDirectory()) {
        // we have a directory: do a tree walk
        const files = fs.readdirSync(path)
        let f,
          l = files.length
        for (var i = 0; i < l; i++) {
          f = pathModule.join(path, files[i])
      } else {
        // we have a file: load it
        var controller = require(path)

    Then use your moduleHolder with dynamically loaded controllers:

      for (const controller of moduleHolder) {
        controller(app, db)

    Django: List field in model?

    I think it will help you.

    from django.db import models
    import ast
    class ListField(models.TextField):
        __metaclass__ = models.SubfieldBase
        description = "Stores a python list"
        def __init__(self, *args, **kwargs):
            super(ListField, self).__init__(*args, **kwargs)
        def to_python(self, value):
            if not value:
                value = []
            if isinstance(value, list):
                return value
            return ast.literal_eval(value)
        def get_prep_value(self, value):
            if value is None:
                return value
            return unicode(value)
        def value_to_string(self, obj):
            value = self._get_val_from_obj(obj)
            return self.get_db_prep_value(value)
    class ListModel(models.Model):
        test_list = ListField()

    Example :

    >>> ListModel.objects.create(test_list= [[1,2,3], [2,3,4,4]])
    >>> ListModel.objects.get(id=1)
    >>> o = ListModel.objects.get(id=1)
    >>> o.test_list
    [[1, 2, 3], [2, 3, 4, 4]]

    Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

    I am not sure I understand what you want, but based on what I understood

    the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"

    you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)

    p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
    p <- p + facet_wrap(~variable, scales = "free_x")

    worked for me, see the picture

    enter image description here

    I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code

    setBackground vs setBackgroundDrawable (Android)

    Use ViewCompat.setBackground(view, background);

    Javascript: How to generate formatted easy-to-read JSON straight from an object?

    JSON.stringify takes more optional arguments.


     JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
     JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab


    How can I beautify JSON programmatically?

    Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

    Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

    This problem also arises when you have mockito-all on your class path, which is already deprecated.

    If possible just include mockito-core.

    Maven config for mixing junit, mockito and hamcrest:


    The default for KeyValuePair

    To avoid the boxing of KeyValuePair.Equals(object) you can use a ValueTuple.

    if ((getResult.Key, getResult.Value) == default)

    Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

    Another potential cause is that docker will not follow symbolic links by default (i.e don't use ln -s).

    rmagick gem install "Can't find Magick-config"

    For those who don't want to do the build-from-source approach of the (otherwise excellent installer script by John Maddox, the following worked for me when installing on CentOS 6.2. (Adjust your package manager as necessary).

    yum install -y {libwmf,lcms,ghostscript,ImageMagick}{,-devel}
    gem install rmagick

    Again, this is mainly of interest if you use your distro's package manager and would really prefer to keep it sane.

    file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

    If your PHP version is 5, try installing cURL by typing the following command in the terminal:

    sudo apt-get install php5-curl

    How to choose an AWS profile when using boto3 to connect to CloudFront

    I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.

    So there are three different ways to do this:

    Option A) Create a new session with the profile

        dev = boto3.session.Session(profile_name='dev')

    Option B) Change the profile of the default session in code


    Option C) Change the profile of the default session with an environment variable

        $ AWS_PROFILE=dev ipython
        >>> import boto3
        >>> s3dev = boto3.resource('s3')

    what is the unsigned datatype?

    In C and C++

    unsigned = unsigned int (Integer type)
    signed   = signed int (Integer type)

    An unsigned integer containing n bits can have a value between 0 and (2^n-1) , which is 2^n different values.

    An unsigned integer is either positive or zero.

    Signed integers are stored in a computer using 2's complement.

    What is the difference between "::" "." and "->" in c++

    In C++ you can access fields or methods, using different operators, depending on it's type:

    • ClassName::FieldName : class public static field and methods
    • ClassInstance.FieldName : accessing a public field (or method) through class reference
    • ClassPointer->FieldName : accessing a public field (or method) dereferencing a class pointer

    Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.

    class AClass{
    static int static_field;
    int instance_field;
    static void static_method();
    void method();

    then you access this way:

    AClass instance;
    AClass *pointer = new AClass();
    instance.instance_field; //access instance_field through a reference to AClass
    pointer->instance_field; //access instance_field through a pointer to AClass

    Updating .class file in jar

    Editing properties/ file inside jar:

    "zip -u /var/opt/my-jar-with-dependencies.jar properties/". Basically "zip -u <source> <dest>", where dest is relative to the jar extract folder.

    Convert a object into JSON in REST service by Spring MVC

    You can always add the @Produces("application/json") above your web method or specify produces="application/json" to return json. Then on top of the Student class you can add @XmlRootElement from javax.xml.bind.annotation package.

    Please note, it might not be a good idea to directly return model classes. Just a suggestion.


    Django Reverse with arguments '()' and keyword arguments '{}' not found

    This problems gave me great headache when i tried to use reverse for generating activation link and send it via email of course. So i think from it will be same. The correct way to do this is following:

    from django.test import Client
    from django.core.urlresolvers import reverse
    #app name - name of the app where the url is defined
    client= Client()
    response = client.get(reverse('app_name:edit_project', project_id=4)) 

    Custom ImageView with drop shadow

    I manage to apply gradient border using this code..

    public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        int newW = w - (leftRightThk * 2);
        int newH = h - (bottomThk + padTop);
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        Bitmap bmp = Bitmap.createBitmap(w, h, conf);
        Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Canvas c = new Canvas(bmp);
        // Left
        int leftMargin = (leftRightThk + 7)/2;
        Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
        c.drawRect(0, padTop, leftMargin, newH, paint); 
        // Right
        Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
        c.drawRect(newW, padTop, w, newH, paint);
        // Bottom
        Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
        c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
        c.drawBitmap(sbmp, leftRightThk, 0, null);
        return bmp;

    hope this helps !

    How to determine the version of android SDK installed in computer?

    Type in android list target into your command line to see what android API you are using.

    Animate element to auto height with jQuery

    var h = document.getElementById('First').scrollHeight;
    $('#First').animate({ height : h+'px' },300);

    clientHeight/clientWidth returning different values on different browsers

    Element.clientWidth & Element.clientHeight return the height/width of that element's content in addition any applicable padding.

    The jQuery implementation of these are: $(target).outerWidth() & $(target).outerHeight()

    .clientWidth & .clientHeight are included in the CSSOM View Module specification which is currently in the working draft stage. While modern browsers have a consistent implementation of this specification, to insure consistent performance across legacy platforms, the jQuery implementation should still be used.

    Additional information:

    • https://developer.mozilla[dot]org/en-US/docs/Web/API/Element.clientWidth
    • https://developer.mozilla[dot]org/en-US/docs/Web/API/Element.clientHeight

    How to call a PHP file from HTML or Javascript

    How to make a button call PHP?

    I don't care if the page reloads or displays the results immediately;


    Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.

    I just want to have a button on my website make a PHP file run.

    That can be done with a form with a single button:

    <form action="">
      <input type="submit" value="my button"/>

    That's it.

    Pretty much. Also note that there are cases where ajax is really the way to go.

    That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.

    Why I cannot call PHP directly from JavaScript?

    If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

    Because the PHP code is not in the HTML just fine. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.

    You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.

    If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.

    How to call another PHP file?

    Use a form to do the call. You can have it to direct the user to a particlar file:

    <form action="myphpfile.php">
      <input type="submit" value="click on me!">

    The user will end up in the page myphpfile.php. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).

    I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

    You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden" and use POST):

    <form action="" method="POST">
      <input type="text" value="default value, you can edit it" name="myfield">
      <input type="submit" value = "post">

    What do I need to know about it to call a PHP file that will create a text file on a button press?

    see: How to write into a file in PHP.

    How do you recieve the data from the POST in the server?

    I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:

        if ($_SERVER['REQUEST_METHOD'] === 'POST')
            //Ok we got a POST, probably from a FORM, read from $_POST.
            var_dump($_PSOT); //Use this to see what info we got!
           //You could assume you got a GET
           var_dump($_GET); //Use this to see what info we got!
     <!DOCTYPE html>
     <html lang="en">
         <meta char-set="utf-8">
         <title>Page title</title>
         <form action="" method="POST">
           <input type="text" value="default value, you can edit it" name="myfield">
           <input type="submit" value = "post">

    Note: you can remove var_dump, it is just for debugging purposes.

    How do I...

    I know the next stage, you will be asking how to:

    1. how to pass variables form a PHP file to another?
    2. how to remember the user / make a login?
    3. how to avoid that anoying message the appears when you reload the page?

    There is a single answer for that: Sessions.

    I'll give a more extensive template for Post-Redirect-Get

        if ($_SERVER['REQUEST_METHOD'] === 'POST')
            //Do stuff...
            //Write results to session
            $_SESSION['stuff'] = $something;
            //You can store stuff such as the user ID, so you can remeember him.
            header('Location: ', true, 303);
            //The redirection will cause the browser to request with GET
            //The results of the operation are in the session variable
            //It has empty location because we are redirecting to the same page
            //Otherwise use `header('Location: anotherpage.php', true, 303);`
            //You could assume you got a GET
            var_dump($_GET); //Use this to see what info we got!
            //Get stuff from session
            if (array_key_exists('stuff', $_SESSION))
               $something = $_SESSION['stuff'];
               //we got stuff
               //later use present the results of the operation to the user.
            //clear stuff from session:
            //set headers
            header('Content-Type: text/html; charset=utf-8');
            //This header is telling the browser what are we sending.
            //And it says we are sending HTML in UTF-8 encoding
    <!DOCTYPE html>
    <html lang="en">
        <meta char-set="utf-8">
        <title>Page title</title>
        <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
        <form action="" method="POST">
          <input type="text" value="default value, you can edit it" name="myfield">
          <input type="submit" value = "post">

    Please look at for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.

    Also, use UTF-8 because UTF-8!


    I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.

    If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.

    Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.

    Ok... but how do I Use Ajax anyway?

    Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.

    So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.

        if ($_SERVER['REQUEST_METHOD'] === 'POST')
            header('Location: ', true, 303);
            header('Content-Type: text/html; charset=utf-8');
    <!DOCTYPE html>
    <html lang="en">
        <meta char-set="utf-8">
        <title>Page title</title>
            function ajaxmagic()
                $.post(                             //call the server
                    "test.php",                     //At this url
                        field: "value",
                        name: "John"
                    }                               //And send this data to it
                ).done(                             //And when it's done
                        $('#fromAjax').html(data);  //Update here with the response
        <input type="button" value = "use ajax", onclick="ajaxmagic()">
        <span id="fromAjax"></span>

    The above code will send a POST request to the page test.php.

    Note: You can mix sessions with ajax and stuff if you want.

    How do I...

    1. How do I connect to the database?
    2. How do I prevent SQL injection?
    3. Why shouldn't I use Mysql_* functions?

    ... for these or any other, please make another questions. That's too much for this one.

    How to show soft-keyboard when edittext is focused

    For Kotlin:

    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    fun showKeyboard() {
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
    fun hideKeyboard() {
            imm.hideSoftInputFromWindow(phoneNoInputTxt.windowToken, 0);

    Then just call what you want!

    Is it possible to set a number to NaN or infinity?

    Cast from string using float():

    >>> float('NaN')
    >>> float('Inf')
    >>> -float('Inf')
    >>> float('Inf') == float('Inf')
    >>> float('Inf') == 1

    Where is Maven Installed on Ubuntu

    I would like to add that .m2 folder a lot of people say it is in your home folder. It is right. But if use maven from ready to go IDE like Spring STS then your .m2 folder is placed in root folder

    To access root folder you need to switch to super user account

    sudo su

    Go to root folder

    cd root/

    You will find it by

    cd -all

    Why does .json() return a promise?

    This difference is due to the behavior of Promises more than fetch() specifically.

    When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.

    The 2nd snippet could also have been written as:

    iterator.then(response =>
        response.json().then(post => document.write(post.title))

    In both this form and yours, the value of post is provided by the Promise returned from response.json().

    When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:

    iterator.then(response =>
          data: response.json(),
          status: response.status
        .then(post => document.write(

    post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.

    Associating enums with strings in C#

    How about using a static class with constants?

    static class GroupTypes
      public const string TheGroup = "OEM";
      public const string TheOtherGroup = "CMB";
    void DoSomething(string groupType)
      if(groupType == GroupTypes.TheGroup)
        // Be nice
      else if (groupType == GroupTypes.TheOtherGroup)
        // Continue to be nice
        // unexpected, throw exception?

    Angular 2 @ViewChild annotation returns undefined

    In my case, I knew the child component would always be present, but wanted to alter the state prior to the child initializing to save work.

    I choose to test for the child until it appeared and make changes immediately, which saved me a change cycle on the child component.

    export class GroupResultsReportComponent implements OnInit {
        @ViewChild(ChildComponent) childComp: ChildComponent;
        ngOnInit(): void {
            this.WhenReady(() => this.childComp, () => { this.childComp.showBar = true; });
         * Executes the work, once the test returns truthy
         * @param test a function that will return truthy once the work function is able to execute 
         * @param work a function that will execute after the test function returns truthy
        private WhenReady(test: Function, work: Function) {
            if (test()) work();
            else setTimeout(this.WhenReady.bind(window, test, work));

    Alertnatively, you could add a max number of attempts or add a few ms delay to the setTimeout. setTimeout effectively throws the function to the bottom of the list of pending operations.

    array_push() with key value pair

    So what about having:


    oracle - what statements need to be committed?

    And a key point - although TRUNCATE TABLE seems like a DELETE with no WHERE clause, TRUNCATE is not DML, it is DDL. DELETE requires a COMMIT, but TRUNCATE does not.

    HTTP status code for update and delete?

    RFC 2616 describes which status codes to use.

    And no, it's not always 200.

    How to get div height to auto-adjust to background size?

    There is no way to auto adjust for background image size using CSS.

    You can hack around it by measuring the background image on the server and then applying those attributes to the div, as others have mentioned.

    You could also hack up some javascript to resize the div based on the image size (once the image has been downloaded) - this is basically the same thing.

    If you need your div to auto-fit the image, I might ask why don't you just put an <img> tag inside your div?

    WPF Check box: Check changed handling

    I know this is an old question, but how about just binding to Command if using MVVM?


    <CheckBox Content="Case Sensitive" Command="{Binding bSearchCaseSensitive}"/>

    For me it triggers on both Check and Uncheck.

    Jenkins - how to build a specific branch

    enter image description here

    There will be an option in configure under Build Triggers

    Check the GitHub Branches

    A hook will be created and then you can build any branch you like from Jenkins when you select github Branches enter image description here

    Hope it helps :)

    How do I move to end of line in Vim?

    The easiest option would be to key in $. If you are working with blocks of text, you might appreciate the command { and } in order to move a paragraph back and forward, respectively.

    How to select a range of the second row to the last row

    Sub SelectAllCellsInSheet(SheetName As String)
        lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
        Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
        Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
    End Sub

    To use with ActiveSheet:

    Call SelectAllCellsInSheet(ActiveSheet.Name)

    How to delete a certain row from mysql table with same column values?

    Best way to design table is add one temporary row as auto increment and keep as primary key. So we can avoid such above issues.

    Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

    This worked for me. may help some one. Turn off firewall. on RHEL 7

    systemctl stop  firewalld

    How to generate random float number in C

    If you want to generate a random float in a range, try a next solution.

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    random_float(const float min, const float max)
        if (max == min) return min;
        else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;
        // return 0 if min > max
        return 0;
    main (const int argc, const char *argv[])
        char line[] = "-------------------------------------------";
        float data[10][2] = {
            {-10, 10},
            {-5., 5},
            {-1, 1},
            {-0.25, -0.15},
            {1.5, 1.52},
            {-1700, 8000},
            {-0.1, 0.1},
            {-1, 0},
            {-1, -2},
            {1.2, 1.1}
        puts("     From    |    Result    |      To");
        int i;
        for (i = 0; i < 10; ++i) {
            printf("%12f | %12f | %12f\n", data[i][0], random_float(data[i][0], data[i][1]), data[i][1]);
        return 0;

    A result (values is fickle)

         From    |    Result    |      To
      -10.000000 |     2.330828 |    10.000000
       -5.000000 |    -4.945523 |     5.000000
       -1.000000 |     0.004242 |     1.000000
       -0.250000 |    -0.203197 |    -0.150000
        1.500000 |     1.513431 |     1.520000
    -1700.000000 |  3292.941895 |  8000.000000
       -0.100000 |    -0.021541 |     0.100000
       -1.000000 |    -0.148299 |     0.000000
       -1.000000 |     0.000000 |    -2.000000
        1.200000 |     0.000000 |     1.100000

    Binding Combobox Using Dictionary as the Datasource

    userListComboBox.DataSource = userCache.ToList();
    userListComboBox.DisplayMember = "Key";

    How can I align two divs horizontally?

    <style type="text/css">
    <div id="floatingDivs">
        <span>source list</span>
        <select size="10">
            <option />
            <option />
            <option />
    <div id="floatingDivs">
        <span>destination list</span>
        <select size="10">
            <option />
            <option />
            <option />

    Putting a simple if-then-else statement on one line

    That's more specifically a ternary operator expression than an if-then, here's the python syntax

    value_when_true if condition else value_when_false

    Better Example: (thanks Mr. Burns)

    'Yes' if fruit == 'Apple' else 'No'

    Now with assignment and contrast with if syntax

    fruit = 'Apple'
    isApple = True if fruit == 'Apple' else False


    fruit = 'Apple'
    isApple = False
    if fruit == 'Apple' : isApple = True

    Starting of Tomcat failed from Netbeans

    For NetBeans to be able to interact with tomcat, it needs the user as setup in netbeans to be properly configured in the tomcat-users.xml file. NetBeans can do so automatically.

    That is, within the tomcat-users.xml, which you can find in ${CATALINA_HOME}/conf, or ${CATALINA_BASE}/conf,

    1. make sure that the user (as chosen in netbeans) is added the script-manager role

    Example, change

    <user password="tomcat" roles="manager,admin" username="tomcat"/>


    <user password="tomcat" roles="manager-script,manager,admin" username="tomcat"/>
    1. make sure that the manager-script role is declared


    <role rolename="manager-script"/>

    Actually the netbeans online-help incorrectly states:

    Username - Specifies the user name that the IDE uses to log into the server's manager application. The user must be associated with the manager role. The first time the IDE started the Tomcat Web Server, such as through the Start/Stop menu action or by executing a web component from the IDE, the IDE adds an admin user with a randomly-generated password to the tomcat-base-path/conf/tomcat-users.xml file. (Right-click the Tomcat Web server instance node in the Services window and select Properties. In the Properties dialog box, the Base Directory property points to the base-dir directory.) The admin user entry in the tomcat-users.xml file looks similar to the following: <user username="idea" password="woiehh" roles="manager"/>

    The role should be manager-script, and not manager.

    For a more complete tomcat-users.xml file:

    <?xml version='1.0' encoding='utf-8'?>
      <role rolename="manager-script"/>
      <role rolename="manager-gui"/>
      <user password="tomcat" roles="manager-script" username="tomcat"/>
      <user password="pass" roles="manager-gui" username="me"/>

    There is another nice posting on why am I getting the deployment error?

    UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

    The problem according to your traceback is the print statement on line 136 of Unfortunately you didn't see fit to post that part of your code, but I'm going to guess it is just there for debugging. If you change it to:

    print repr(ch)

    then you should at least see what you are trying to print.

    What are all the possible values for HTTP "Content-Type" header?

    As is defined in RFC 1341:

    In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows:

    Content-Type := type "/" subtype *[";" parameter]

    type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token

    x-token := < The two characters "X-" followed, with no intervening white space, by any token >

    subtype := token

    parameter := attribute "=" value

    attribute := token

    value := token / quoted-string

    token := 1*

    tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "\" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values

    And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source).

    As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).

    Also note the comment above:

    If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.

    You'll notice that a lot of HTTP requests/responses include an X- header of some sort which are self defined, keep this in mind when validating the types.

    How do I change Bootstrap 3 column order on mobile layout?

    Updated 2018

    For the original question based on Bootstrap 3, the solution was to use push-pull.

    In Bootstrap 4 it's now possible to change the order, even when the columns are full-width stacked vertically, thanks to Bootstrap 4 flexbox. OFC, the push pull method will still work, but now there are other ways to change column order in Bootstrap 4, making it possible to re-order full-width columns.

    Method 1 - Use flex-column-reverse for xs screens:

    <div class="row flex-column-reverse flex-md-row">
        <div class="col-md-3">
        <div class="col-md-9">

    Method 2 - Use order-first for xs screens:

    <div class="row">
        <div class="col-md-3">
        <div class="col-md-9 order-first order-md-last">

    Bootstrap 4(alpha 6):
    Bootstrap 4.1:

    Original 3.x Answer

    For the original question based on Bootstrap 3, the solution was to use push-pull for the larger widths, and then the columns will show is their natural order on smaller (xs) widths. (A-B reverse to B-A).

    <div class="container">
        <div class="row">
            <div class="col-md-9 col-md-push-3">
            <div class="col-md-3 col-md-pull-9">

    Bootstrap 3:

    @emre stated, "You cannot change the order of columns in smaller screens but you can do that in large screens". However, this should be clarified to state: "You cannot change the order of full-width "stacked" columns.." in Bootstrap 3.

    How to check whether a string is a valid HTTP URL?

    This method works fine both in http and https. Just one line :)

    if (Uri.IsWellFormedUriString("", UriKind.Absolute))

    MSDN: IsWellFormedUriString

    Obtaining only the filename when using OpenFileDialog property "FileName"

    Use: Path.GetFileName Method

    var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

    Zip lists in Python

    For the completeness's sake.

    When zipped lists' lengths are not equal. The result list's length will become the shortest one without any error occurred

    >>> a = [1]
    >>> b = ["2", 3]
    >>> zip(a,b)
    [(1, '2')]

    isPrime Function for Python Language

    I have a new solution which I think might be faster than any of the mentioned Function in Python

    It's based on the idea that: N/D = R for any arbitrary number N, the least possible number to divide N (if not prime) is D=2 and the corresponding result R is (N/2) (highest).

    As D goes bigger the result R gets smaller ex: divide by D = 3 results R = (N/3) so when we are checking if N is divisible by D we are also checking if it's divisible by R

    so as D goes bigger and R goes smaller till (D == R == square root(N))

    then we only need to check numbers from 2 to sqrt(N) another tip to save time, we only need to check the odd numbers as it the number is divisible by any even number it will also be divisible by 2.

    so the sequence will be 3,5,7,9,......,sqrt(N).

    import math
    def IsPrime (n): 
        if (n <= 1 or n % 2 == 0):return False
        if n == 2:return True
        for i in range(3,int(math.sqrt(n))+1,2):
            if (n % i) == 0:
                return False
        return True

    Stacked Bar Plot in R

    I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:

    data<- rbind(c(480, 780, 431, 295, 670, 360,  190),
                 c(720, 350, 377, 255, 340, 615,  345),
                 c(460, 480, 179, 560,  60, 735, 1260),
                 c(220, 240, 876, 789, 820, 100,   75))
    a <- cbind(data[, 1], 1, c(1:4))
    b <- cbind(data[, 2], 2, c(1:4))
    c <- cbind(data[, 3], 3, c(1:4))
    d <- cbind(data[, 4], 4, c(1:4))
    e <- cbind(data[, 5], 5, c(1:4))
    f <- cbind(data[, 6], 6, c(1:4))
    g <- cbind(data[, 7], 7, c(1:4))
    data           <-, b, c, d, e, f, g))
    colnames(data) <-c("Time", "Type", "Group")
    data$Type      <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))
    ggplot(data = data, aes(x = Type, y = Time, fill = Group)) + 
           geom_bar(stat = "identity") +
           opts(legend.position = "none")

    enter image description here

    How to access to a child method from the parent in vue.js

    To communicate a child component with another child component I've made a method in parent which calls a method in a child with:


    And from the another child I've called the root method:


    It worked for me.

    Convert Time DataType into AM PM Format:

        select right(convert(varchar(20),getdate(),100),7)

    Python Inverse of a Matrix

    Numpy will be suitable for most people, but you can also do matrices in Sympy

    Try running these commands at

    M = Matrix([[1, 3], [-2, 3]])

    For fun, try M**(1/2)

    Use python requests to download CSV

    Python3 Supported Code

        with closing(requests.get(PHISHTANK_URL, stream=True})) as r:
            reader = csv.reader(codecs.iterdecode(r.iter_lines(), 'utf-8'), delimiter=',', quotechar='"')
            for record in reader:
               print (record)

    Save results to csv file with Python

    This is how I do it

     import csv
        file = open('???.csv', 'r')
        read = csv.reader(file)
        for column in read:
                file = open('???.csv', 'r')
                read = csv.reader(file)
                file = open('????.csv', 'a', newline='')
                write = csv.writer(file, delimiter = ",")
                write.writerow((, ))

    how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

    Why you can't just use mysqlsh?

    PS C:\Users\artur\Desktop> mysqlsh --user root
    MySQL Shell 8.0.17
    Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
    Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
    Other names may be trademarks of their respective owners.
    Type '\help' or '\?' for help; '\quit' to exit.
    Creating a session to 'root@localhost'
    Fetching schema names for autocompletion... Press ^C to stop.
    Your MySQL connection id is 13 (X protocol)
    Server version: 8.0.17 MySQL Community Server - GPL
    No default schema selected; type \use <schema> to set one.
     MySQL  localhost:33060+ ssl  JS >

    mysqlsh on windows terminal (pic)

    Converting Long to Date in Java returns 1970

    Try this:

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(1220227200 * 1000);

    The split() method in Java does not work on a dot (.)

    It works fine. Did you read the documentation? The string is converted to a regular expression.

    . is the special character matching all input characters.

    As with any regular expression special character, you escape with a \. You need an additional \ for the Java string escape.

    How to `wget` a list of URLs in a text file?

    If you also want to preserve the original file name, try with:

    wget --content-disposition --trust-server-names -i list_of_urls.txt

    ArrayList - How to modify a member of an object?

    Assuming Customer has a setter for email - myList.get(3).setEmail("[email protected]")

    Convert Month Number to Month Name Function in SQL


    What are the differences between NP, NP-Complete and NP-Hard?

    NP-complete problems are those problems that are both NP-Hard and in the complexity class NP. Therefore, to show that any given problem is NP-complete, you need to show that the problem is both in NP and that it is NP-hard.

    Problems that are in the NP complexity class can be solved non-deterministically in polynomial time and a possible solution (i.e., a certificate) for a problem in NP can be verified for correctness in polynomial time.

    An example of a non-deterministic solution to the k-clique problem would be something like:

    1) randomly select k nodes from a graph

    2) verify that these k nodes form a clique.

    The above strategy is polynomial in the size of the input graph and therefore the k-clique problem is in NP.

    Note that all problems deterministically solvable in polynomial time are also in NP.

    Showing that a problem is NP-hard typically involves a reduction from some other NP-hard problem to your problem using a polynomial time mapping:

    Change remote repository credentials (authentication) on Intellij IDEA 14

    IN Android Studio 2.3

    1. Open Setting (CTRL+ALT+S)
    2. Select Other Settings (at the end)
    3. select Bitbucket

    Here you can change your new Password or User

    Disable cache for some images

    A common and simple solution to this problem that feels like a hack but is fairly portable is to add a randomly generated query string to each request for the dynamic image.

    So, for example -

    <img src="image.png" />

    Would become

    <img src="image.png?dummy=8484744" />


    <img src="image.png?dummy=371662" />

    From the point of view of the web-server the same file is accessed, but from the point of view of the browser no caching can be performed.

    The random number generation can happen either on the server when serving the page (just make sure the page itself isn't cached...), or on the client (using JavaScript).

    You will need to verify whether your web-server can cope with this trick.

    Finding the next available id in MySQL

    The problem with many solutions is they only find the next "GAP", while ignoring if "1" is available, or if there aren't any rows they'll return NULL as the next "GAP".

    The following will not only find the next available gap, it'll also take into account if the first available number is 1:

    -- return 1 if it's available or if there are no rows yet
    ELSE -- find next gap
        (SELECT MIN(t.MyID)+1
        FROM MyTable t (updlock)
    END AS NextID
    FROM MyTable

    OOP vs Functional Programming vs Procedural

    I think that they are often not "versus", but you can combine them. I also think that oftentimes, the words you mention are just buzzwords. There are few people who actually know what "object-oriented" means, even if they are the fiercest evangelists of it.

    Just get column names from hive table

    use desc tablename from Hive CLI or beeline to get all the column names. If you want the column names in a file then run the below command from the shell.

    $ hive -e 'desc dbname.tablename;' > ~/columnnames.txt

    where dbname is the name of the Hive database where your table is residing You can find the file columnnames.txt in your root directory.

    $cd ~

    How to get current time and date in Android

    To ge the current time you can use System.currentTimeMillis() which is standard in Java. Then you can use it to create a date

    Date currentDate = new Date(System.currentTimeMillis());

    And as mentioned by others to create a time

    Time currentTime = new Time();

    How to correctly save instance state of Fragments in back stack?

    On the latest support library none of the solutions discussed here are necessary anymore. You can play with your Activity's fragments as you like using the FragmentTransaction. Just make sure that your fragments can be identified either with an id or tag.

    The fragments will be restored automatically as long as you don't try to recreate them on every call to onCreate(). Instead, you should check if savedInstanceState is not null and find the old references to the created fragments in this case.

    Here is an example:

    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            myFragment = MyFragment.newInstance();
                    .add(, myFragment, MY_FRAGMENT_TAG)
        } else {
            myFragment = (MyFragment) getSupportFragmentManager()

    Note however that there is currently a bug when restoring the hidden state of a fragment. If you are hiding fragments in your activity, you will need to restore this state manually in this case.

    iPhone App Development on Ubuntu

    Perhaps the best way would be to implement your app as a web app. I think you can also make web apps that run direct on the phone, without internet access or a remote server.

    Web app, sounds lame? But a lot can be done with DHTML / HTML5 / JavaScript. It's a rare app that requires more power and couldn't be done as a web app. And you get pretty good cross platform with Web / JavaScript - the browsers vary a bit but a good web dev can write one web app that works pretty much everywhere.

    Of course if you're writing a high-performance 3D game, the browser might not deliver what you need! maybe in a few years... Apparently some Google hackers ported Quake 2 to HTML5 already!

    Unsigned keyword in C++

    Integer Types:

    short            -> signed short
    signed short
    unsigned short
    int              -> signed int
    signed int
    unsigned int
    signed           -> signed int
    unsigned         -> unsigned int
    long             -> signed long
    signed long
    unsigned long

    Be careful of char:

    char  (is signed or unsigned depending on the implmentation)
    signed char
    unsigned char

    Resource from src/main/resources not found after building with maven

    Resources from src/main/resources will be put onto the root of the classpath, so you'll need to get the resource as:

    new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/config.txt")));

    You can verify by looking at the JAR/WAR file produced by maven as you'll find config.txt in the root of your archive.

    How to install all required PHP extensions for Laravel?

    Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

    You can run the following command in Ubuntu to make sure the extensions are installed.

    sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

    PHP version specific installation (if PHP 7.4 installed)

    sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

    You may need other PHP extensions for your composer packages. Find from links below.

    PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

    PHP extensions for Ubuntu 18.04 LTS (Bionic)

    PHP extensions for Ubuntu 16.04 LTS (Xenial)

    What is the difference between min SDK version/target SDK version vs. compile SDK version?

    The min sdk version is the minimum version of the Android operating system required to run your application.

    The target sdk version is the version of Android that your app was created to run on.

    The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.

    Usually the compile sdk version and the target sdk version are the same.

    How to download/checkout a project from Google Code in Windows?

    If you have a github account and don't want to download software, you can export to github, then download a zip from github.

    High CPU Utilization in java application - why?

    You may be victim of a garbage collection problem.

    When your application requires memory and it's getting low on what it's configured to use the garbage collector will run often which consume a lot of CPU cycles. If it can't collect anything your memory will stay low so it will be run again and again. When you redeploy your application the memory is cleared and the garbage collection won't happen more than required so the CPU utilization stays low until it's full again.

    You should check that there is no possible memory leak in your application and that it's well configured for memory (check the -Xmx parameter, see What does Java option -Xmx stand for?)

    Also, what are you using as web framework? JSF relies a lot on sessions and consumes a lot of memory, consider being stateless at most!

    How to call code behind server method from a client side JavaScript function?

    In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:

    aspx code:

        <asp:Button runat="server" id="btnResponse1" Text="" 
        style="display: none; width:100%; height:100%"
        OnClick="btnResponses_Clicked" />
        <div class="circlebuttontext" id="calendarButtonText">Calendar</div>

    C# code behind:

    protected void btnResponses_Clicked(object sender, EventArgs e)
        if(sender == btnResponse1)
            //Your code behind logic for that button goes here

    Import module from subfolder

    Say your project is structured this way:

    |   +---.gitignore
    |   |   +---subscripts
    |   |   |
    |   |   |

    Inside, you can import scripts one and two by:

    from subscripts import script_one as One
    from subscripts import script_two as Two

    Now, still inside, you'll be able to call their methods with:


    Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

    I choose use javascript:void(0), because use this could prevent right click to open the content menu. But javascript:; is shorter and does the same thing.

    SSIS Connection Manager Not Storing SQL Password

    Check the text contents of the connection manager file itself, the password field might be configured in the Project.params file, in which case entering the password into the connection manager window will cause it to not save.

    Why doesn't list have safe "get" method like dictionary?

    So I did some more research into this and it turns out there isn't anything specific for this. I got excited when I found list.index(value), it returns the index of a specified item, but there isn't anything for getting the value at a specific index. So if you don't want to use the safe_list_get solution which I think is pretty good. Here are some 1 liner if statements that can get the job done for you depending on the scenario:

    >>> x = [1, 2, 3]
    >>> el = x[4] if len(x) > 4 else 'No'
    >>> el

    You can also use None instead of 'No', which makes more sense.:

    >>> x = [1, 2, 3]
    >>> i = 2
    >>> el_i = x[i] if len(x) == i+1 else None

    Also if you want to just get the first or last item in the list, this works

    end_el = x[-1] if x else None

    You can also make these into functions but I still liked the IndexError exception solution. I experimented with a dummied down version of the safe_list_get solution and made it a bit simpler (no default):

    def list_get(l, i):
            return l[i]
        except IndexError:
            return None

    Haven't benchmarked to see what is fastest.

    Select value if condition in SQL Server

    Try Case

             WHEN stock.quantity <20 THEN 'Buy urgent'
             ELSE 'There is enough'
    FROM stock

    How do I configure git to ignore some files locally?

    If your repo doesn't already have a .gitignore file, then a simple solution is to create a .gitignore file, and in it add .gitignore to the list of files to be ignored.

    display HTML page after loading complete

    you can also go for this.... this will only show the HTML section once javascript has loaded.

    <!-- Adds the hidden style and removes it when javascript has loaded -->
    <style type="text/css">
        .hideAll  {
    <script type="text/javascript">
        $(window).load(function () {
    <div id="tabs" class="hideAll">

    Converting a date in MySQL from string field

    Yes, there's str_to_date

    mysql> select str_to_date("03/02/2009","%d/%m/%Y");
    | str_to_date("03/02/2009","%d/%m/%Y") |
    | 2009-02-03                           |
    1 row in set (0.00 sec)

    how to get the ipaddress of a virtual box running on local machine

    Login to virtual machine use below command to check ip address. (anyone will work)

    1. ifconfig
    2. ip addr show

    If you used NAT for your virtual machine settings(your machine ip will be, then you have to use port forwarding to connect to machine. IP address will be

    If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

    What does the function then() mean in JavaScript?

    I suspect doSome returns this, which is myObj, which also has a then method. Standard method chaining...

    if doSome is not returning this, being the object on which doSome was executed, rest assured it is returning some object with a then method...

    as @patrick points out, there is no then() for standard js

    Copy all values in a column to a new column in a pandas dataframe

    You can simply assign the B to the new column , Like -

    df['D'] = df['B']

    Example/Demo -

    In [1]: import pandas as pd
    In [2]: df = pd.DataFrame([['a.1','b.1','c.1'],['a.2','b.2','c.2'],['a.3','b.3','c.3']],columns=['A','B','C'])
    In [3]: df
         A    B    C
    0  a.1  b.1  c.1
    1  a.2  b.2  c.2
    2  a.3  b.3  c.3
    In [4]: df['D'] = df['B']                  #<---What you want.
    In [5]: df
         A    B    C    D
    0  a.1  b.1  c.1  b.1
    1  a.2  b.2  c.2  b.2
    2  a.3  b.3  c.3  b.3
    In [6]: df.loc[0,'D'] = 'd.1'
    In [7]: df
         A    B    C    D
    0  a.1  b.1  c.1  d.1
    1  a.2  b.2  c.2  b.2
    2  a.3  b.3  c.3  b.3

    How to create a DOM node as an object?

    Try this:

    var div = $('<div></div>').addClass('bar').text('bla');
    var li = $('<li></li>').attr('id', '1234');

    Obviously, it doesn't make sense to append a li to the body directly. Basically, the trick is to construct the DOM elementr tree with $('your html here'). I suggest to use CSS modifiers (.text(), .addClass() etc) as opposed to making jquery parse raw HTML, it will make it much easier to change things later.

    How to fully clean bin and obj folders within Visual Studio?

    I store my finished VS projects by saving only source code.

    I delete BIN, DEBUG, RELEASE, OBJ, ARM and .vs folders from all projects.

    This reduces the size of the project considerably. The project

    must be rebuilt when pulled out of storage.

    How to output loop.counter in python jinja template?

    if you are using django use forloop.counter instead of loop.counter

    {% for user in userlist %}
          {{ user }} {{forloop.counter}}
          {% if forloop.counter == 1 %}
              This is the First user
          {% endif %}
    {% endfor %}

    Invalid argument supplied for foreach()

    $values = get_values();
    foreach ((array) $values as $value){

    Problem is always null and Casting is in fact the cleaning solution.

    How to deal with SettingWithCopyWarning in Pandas

    For me this issue occured in a following >simplified< example. And I was also able to solve it (hopefully with a correct solution):

    old code with warning:

    def update_old_dataframe(old_dataframe, new_dataframe):
        for new_index, new_row in new_dataframe.iterrorws():
            old_dataframe.loc[new_index] = update_row(old_dataframe.loc[new_index], new_row)
    def update_row(old_row, new_row):
        for field in [list_of_columns]:
            # line with warning because of chain indexing old_dataframe[new_index][field]
            old_row[field] = new_row[field]  
        return old_row

    This printed the warning for the line old_row[field] = new_row[field]

    Since the rows in update_row method are actually type Series, I replaced the line with:[field] =[field]

    i.e. method for accessing/lookups for a Series. Eventhough both works just fine and the result is same, this way I don't have to disable the warnings (=keep them for other chain indexing issues somewhere else).

    I hope this may help someone.

    Reload browser window after POST without prompting user to resend POST data

    This worked for me.

    window.location = window.location.pathname;

    Tested on

    • Chrome 44.0.2403
    • IE edge
    • Firefox 39.0

    How to change the background color of Action Bar's Option Menu in Android 4.2?

    If you read this, it's probably because all the previous answers didn't work for your Holo Dark based theme.

    Holo Dark uses an additional wrapper for the PopupMenus, so after doing what Jonik suggested you have to add the following style to your 'xml' file:

    <style name="PopupWrapper" parent="@android:style/Theme.Holo">
        <item name="android:popupMenuStyle">@style/YourPopupMenu</item>

    Then reference it in your theme block:

    <style name="" parent="@android:style/Theme.Holo">
        <item name="android:actionBarWidgetTheme">@style/PopupWrapper</item>

    That's it!

    Is there a simple JavaScript slider?

    Here is another light JavaScript Slider that seems to fit your needs.

    Displaying files (e.g. images) stored in Google Drive on a website

    Per this blog post, a currently working solution is:

    <img src=”[imageIdGoesHere]" />

    Test here

    This is verified to work as of Aug 8, 2020. No shared folder or login is required. But a publicly shared file is.

    JavaScript: How to pass object by value?

    If you are using lodash or npm, use lodash's merge function to deep copy all of the object's properties to a new empty object like so:

    var objectCopy = lodash.merge({}, originalObject);

    How to use BeginInvoke C#

    Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

    () => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

    Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

    BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

    Uncaught ReferenceError: function is not defined with onclick

    I think you put the function in the $(document).ready....... The functions are always provided out the $(document).ready.......

    Bash script error [: !=: unary operator expected

    Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

    In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

    case $1 in
      '-v') if [ "$1" = -v ]; then
             echo "`ps -ef | grep -v '\['`"
             echo "`ps -ef | grep '\[' | grep root`"
         *) echo "usage: $0 [-v]"
            exit 1;; #It is good practice to throw a code, hence allowing $? check

    If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

    usage ()
      echo "usage: $0 [-v]"
      exit 1
    unset arg_match
    for arg in $*
      case $arg in
        '-v') if [ "$arg" = -v ]; then
               echo "`ps -ef | grep -v '\['`"
               echo "`ps -ef | grep '\[' | grep root`"
              arg_match=1;; # this is set, but could increment.
           *) ;;
    if [ ! $arg_match ]

    But, allow multiple occurrences of an argument is convenient to use in situations such as:

    $ adduser -u:sam -s -f -u:bob -trace -verbose

    We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

    $ adduser -u sam -s -f -u bob -trace -verbose