Programs & Examples On #Optical drive

ImportError: No Module Named bs4 (BeautifulSoup)

pip3.7 install bs4

Try this. It works with python 3.7

Form/JavaScript not working on IE 11 with error DOM7011

This issue occurs if the server sends a "Cache-control:no-store" header or sends a "Cache-control:no-cache" header.

Dump all documents of Elasticsearch

The data itself is one or more lucene indices, since you can have multiple shards. What you also need to backup is the cluster state, which contains all sorts of information regarding the cluster, the available indices, their mappings, the shards they are composed of etc.

It's all within the data directory though, you can just copy it. Its structure is pretty intuitive. Right before copying it's better to disable automatic flush (in order to backup a consistent view of the index and avoiding writes on it while copying files), issue a manual flush, disable allocation as well. Remember to copy the directory from all nodes.

Also, next major version of elasticsearch is going to provide a new snapshot/restore api that will allow you to perform incremental snapshots and restore them too via api. Here is the related github issue:

What are best practices for multi-language database design?

I'm using next approach:


ProductID OrderID,...


ProductID Title Name LanguageID


LanguageID Name Culture,....

Convert hex string (char []) to int?

This is a function to directly convert hexadecimal containing char array to an integer which needs no extra library:

int hexadecimal2int(char *hdec) {
    int finalval = 0;
    while (*hdec) {
        int onebyte = *hdec++; 
        if (onebyte >= '0' && onebyte <= '9'){onebyte = onebyte - '0';}
        else if (onebyte >= 'a' && onebyte <='f') {onebyte = onebyte - 'a' + 10;}
        else if (onebyte >= 'A' && onebyte <='F') {onebyte = onebyte - 'A' + 10;}  
        finalval = (finalval << 4) | (onebyte & 0xF);
    finalval = finalval - 524288;
    return finalval;

jQuery text() and newlines

It's the year 2015. The correct answer to this question at this point is to use CSS white-space: pre-line or white-space: pre-wrap. Clean and elegant. The lowest version of IE that supports the pair is 8.

P.S. Until CSS3 become common you'd probably need to manually trim off initial and/or trailing white-spaces.

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

Please open terminal and fire the below command:

export LC_ALL="en_US.UTF-8"

How to use filter, map, and reduce in Python 3

As an addendum to the other answers, this sounds like a fine use-case for a context manager that will re-map the names of these functions to ones which return a list and introduce reduce in the global namespace.

A quick implementation might look like this:

from contextlib import contextmanager    

def noiters(*funcs):
    if not funcs: 
        funcs = [map, filter, zip] # etc
    from functools import reduce
    globals()[reduce.__name__] = reduce
    for func in funcs:
        globals()[func.__name__] = lambda *ar, func = func, **kwar: list(func(*ar, **kwar))
        del globals()[reduce.__name__]
        for func in funcs: globals()[func.__name__] = func

With a usage that looks like this:

with noiters(map):
    from operator import add
    print(reduce(add, range(1, 20)))
    print(map(int, ['1', '2']))

Which prints:

[1, 2]

Just my 2 cents :-)

Dynamic height for DIV

calculate the height of each link no do this

document.getElementById("products").style.height= height_of_each_link* no_of_link

Opening port 80 EC2 Amazon web services

  1. Check what security group you are using for your instance. See value of Security Groups column in row of your instance. It's important - I changed rules for default group, but my instance was under quickstart-1 group when I had similar issue.
  2. Go to Security Groups tab, go to Inbound tab, select HTTP in Create a new rule combo-box, leave in source field and click Add Rule, then Apply rule changes.

How to install bcmath module?

I just tried below package for php v5.6 and it worked for me.

yum install php56w-bcmath

Angular 2 Hover event

Simply do (mouseenter) attribute in Angular2+...

In your HTML do:

<div (mouseenter)="mouseHover($event)">Hover!</div> 

and in your component do:

import { Component, OnInit } from '@angular/core';

  selector: 'component',
  templateUrl: './component.html',
  styleUrls: ['./component.scss']

export class MyComponent implements OnInit {

  mouseHover(e) {
    console.log('hovered', e);

Stop jQuery .load response from being cached

Another approach to put the below line only when require to get data from server,Append the below line along with your ajax url.


ruby LoadError: cannot load such file

I created my own Gem, but I did it in a directory that is not in my load path:

$ pwd
$ gem build my_gem/my_gem.gemspec

Then I ran irb and tried to load the Gem:

> require 'my_gem'
LoadError: cannot load such file -- my_gem

I used the global variable $: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path $:. None of those directories included my ~/projects directory where I created the custom gem.

So one solution is to modify the load path itself:

$: << "/Users/myuser/projects/my_gem/lib"

Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:

> require 'my_gem'
 => true 

Now if you want to install the gem in RVM path, then you would need to run:

$ gem install my_gem

But it will need to be in a repository like

$ gem push my_gem-0.0.0.gem
Pushing gem to
Successfully registered gem my_gem

Runtime vs. Compile time

Imagine that you are a boss and you have an assistant and a maid, and you give them a list of tasks to do, the assistant (compile time) will grab this list and make a checkup to see if the tasks are understandable and that you didn't write in any awkward language or syntax, so he understands that you want to assign someone for a Job so he assign him for you and he understand that you want some coffee, so his role is over and the maid (run time)starts to run those tasks so she goes to make you some coffee but in sudden she doesn’t find any coffee to make so she stops making it or she acts differently and make you some tea (when the program acts differently because he found an error).

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

These work for general strings (in case you do not want to output to file/console, but store for later use or something).


MyStr += boost::lexical_cast<std::string>(MyInt);

String streams

std::stringstream Stream;
Stream << MyInt;
MyStr = Stream.str();

// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;

Rails 4 Authenticity Token

This is a security feature in Rails. Add this line of code in the form:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Documentation can be found here:

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Why doesn't indexOf work on an array IE8?

Please careful with $.inArray if you want to use it. I just found out that the $.inArray is only works with "Array", not with String. That's why this function will not working in IE8!

The jQuery API make confusion

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

--> They shouldn't say it "Similar". Since indexOf support "String" also!

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]


  1. Its not necessary to specify table name in Person.hbm.xml (........) when you are creating table with same as class name. Also applicable to fields.

  2. While creating "person" table in your respective database,make sure that whatever FILEDS names you specified in Person.hbm.xml must match with table COLUMNS names ELSE you wil get above error.

how to pass parameters to query in SQL (Excel)

It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)

The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.

When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.

When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.

I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.

Can you have multiline HTML5 placeholder text in a <textarea>?

According to MDN,

Carriage returns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint.

This means that if you just jump to a new line, it should be rendered correctly. I.e.

<textarea placeholder="The car horn plays La Cucaracha.
You can choose your own color as long as it's black.
The GPS has the voice of Darth Vader.

should render like this:

enter image description here

Python reading from a file and saving to utf-8

You can't do that using open. use codecs.

when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:

import codecs
file ='data.txt','w','utf-8')

Using LINQ to concatenate strings

return string.Join(", ", strings.ToArray());

In .Net 4, there's a new overload for string.Join that accepts IEnumerable<string>. The code would then look like:

return string.Join(", ", strings);

Foreach in a Foreach in MVC View

Try this:

It looks like you are looping for every product each time, now this is looping for each product that has the same category ID as the current category being looped

<div id="accordion1" style="text-align:justify">
@using (Html.BeginForm())
    foreach (var category in Model.Categories)

                @foreach (var product in Model.Product.Where(m=> m.CategoryID= category.CategoryID)
                        @if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
                            @Html.Raw(" - ")  
                            @Html.ActionLink("Edit", "Edit", new { id = product.ID })

How to install the Raspberry Pi cross compiler on my Linux host machine?

I couldn't get the compiler (x64 version) to use the sysroot until I added SET(CMAKE_SYSROOT $ENV{HOME}/raspberrypi/rootfs) to pi.cmake.

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

Try my way :

robocopy.exe "Desktop\Test folder 1" "Desktop\Test folder 2" /XD "C:\Users\Steve\Desktop\Test folder 2\XXX dont touch" /MIR

Had to put /XD before /MIR while including the full Destination Source directly after /XD.

In Maven how to exclude resources from the generated jar?

Do you mean to property files located in src/main/resources? Then you should exclude them using the maven-resource-plugin. See the following page for details:

Java JDBC connection status

Use Connection.isClosed() function.

The JavaDoc states:

Retrieves whether this Connection object has been closed. A connection is closed if the method close has been called on it or if certain fatal errors have occurred. This method is guaranteed to return true only when it is called after the method Connection.close has been called.

How to find cube root using Python?

You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

def is_perfect_cube(x):
    x = abs(x)
    return int(round(x ** (1. / 3))) ** 3 == x

print(is_perfect_cube(2146689000)) # no other currently posted solution
                                   # handles this correctly

This takes the cube root of x, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x.

The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).

How to measure time taken by a function to execute

var StopWatch = function (performance) {
    this.startTime = 0;
    this.stopTime = 0;
    this.running = false;
    this.performance = performance === false ? false : !!window.performance;

StopWatch.prototype.currentTime = function () {
    return this.performance ? : new Date().getTime();

StopWatch.prototype.start = function () {
    this.startTime = this.currentTime();
    this.running = true;

StopWatch.prototype.stop = function () {
    this.stopTime = this.currentTime();
    this.running = false;

StopWatch.prototype.getElapsedMilliseconds = function () {
    if (this.running) {
        this.stopTime = this.currentTime();

    return this.stopTime - this.startTime;

StopWatch.prototype.getElapsedSeconds = function () {
    return this.getElapsedMilliseconds() / 1000;

StopWatch.prototype.printElapsed = function (name) {
    var currentName = name || 'Elapsed:';

    console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');


var stopwatch = new StopWatch();

for (var index = 0; index < 100; index++) {
    stopwatch.printElapsed('Instance[' + index + ']');




Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s] is optional - just pass false into StopWatch constructor function.

Select specific row from mysql table

You can use LIMIT 2,1 instead of WHERE row_number() = 3.

As the documentation explains, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.

Keep in mind that it's an 0-based index. So, if you want the line number n, the first argument should be n-1. The second argument will always be 1, because you just want one row. For example, if you want the line number 56 of a table customer:

SELECT * FROM customer LIMIT 55,1

How do you write to a folder on an SD card in Android?

In order to download a file to Download or Music Folder In SDCard

File downlodDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);// or DIRECTORY_PICTURES

And dont forget to add these permission in manifest

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

Find the 2nd largest element in an array with minimum number of comparisons

I have gone through all the posts above but I am convinced that the implementation of the Tournament algorithm is the best approach. Let us consider the following algorithm posted by @Gumbo

largest := numbers[0];
secondLargest := null
for i=1 to numbers.length-1 do
    number := numbers[i];
    if number > largest then
        secondLargest := largest;
        largest := number;
        if number > secondLargest then
            secondLargest := number;

It is very good in case we are going to find the second largest number in an array. It has (2n-1) number of comparisons. But what if you want to calculate the third largest number or some kth largest number. The above algorithm doesn't work. You got to another procedure.

So, I believe tournament algorithm approach is the best and here is the link for that.

How I can print to stderr in C?

Some examples of formatted output to stdout and stderr:

printf("%s", "Hello world\n");              // "Hello world" on stdout (using printf)
fprintf(stdout, "%s", "Hello world\n");     // "Hello world" on stdout (using fprintf)
fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

I fixed this problem.The device system version is older then the sdk minSdkVersion? I just modified the minSdkVersion from android_L to 19 to target my nexus 4.4.4.

buildscript {
    repositories {
    dependencies {
        classpath ''
apply plugin: ''

repositories {

android {
    **compileSdkVersion 'android-L'** modified to 19
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.antwei.uiframework.ui"
        minSdkVersion 14
        targetSdkVersion 'L'
        versionCode 1
        versionName "1.0"
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    **compile ''** modified to compile ''

how to modified the value by ide. select file->Project Structure -> Facets -> android-gradle and then modified the compile Sdk Version from android_L to 19

sorry I don't have enough reputation to add pictures

client denied by server configuration

This has happened to me several times migrating from Apache 2.2.

What I have found is that there is an Order,Deny that I missed with VIM's Search feature somehow that is the default main Vhost, line 379. Hope this helps someone. I commented out the Order Deny,Allow and Deny from All and it worked!

Why doesn't the height of a container element increase if it contains floated elements?

The floated elements do not add to the height of the container element, and hence if you don't clear them, container height won't increase...

I'll show you visually:

enter image description here

enter image description here

enter image description here

More Explanation:

  <div style="float: left;"></div>
  <div style="width: 15px;"></div> <!-- This will shift 
                                        besides the top div. Why? Because of the top div 
                                        is floated left, making the 
                                        rest of the space blank -->

  <div style="clear: both;"></div> 
  <!-- Now in order to prevent the next div from floating beside the top ones, 
       we use `clear: both;`. This is like a wall, so now none of the div's 
       will be floated after this point. The container height will now also include the 
       height of these floated divs -->

You can also add overflow: hidden; on container elements, but I would suggest you use clear: both; instead.

Also if you might like to self-clear an element you can use

.self_clear:after {
  content: "";
  clear: both;
  display: table;

How Does CSS Float Work?

What is float exactly and what does it do?

  • The float property is misunderstood by most beginners. Well, what exactly does float do? Initially, the float property was introduced to flow text around images, which are floated left or right. Here's another explanation by @Madara Uchicha.

    So, is it wrong to use the float property for placing boxes side by side? The answer is no; there is no problem if you use the float property in order to set boxes side by side.

  • Floating an inline or block level element will make the element behave like an inline-block element.


  • If you float an element left or right, the width of the element will be limited to the content it holds, unless width is defined explicitly ...

  • You cannot float an element center. This is the biggest issue I've always seen with beginners, using float: center;, which is not a valid value for the float property. float is generally used to float/move content to the very left or to the very right. There are only four valid values for float property i.e left, right, none (default) and inherit.

  • Parent element collapses, when it contains floated child elements, in order to prevent this, we use clear: both; property, to clear the floated elements on both the sides, which will prevent the collapsing of the parent element. For more information, you can refer my another answer here.

  • (Important) Think of it where we have a stack of various elements. When we use float: left; or float: right; the element moves above the stack by one. Hence the elements in the normal document flow will hide behind the floated elements because it is on stack level above the normal floated elements. (Please don't relate this to z-index as that is completely different.)

Taking a case as an example to explain how CSS floats work, assuming we need a simple 2 column layout with a header, footer, and 2 columns, so here is what the blueprint looks like...

enter image description here

In the above example, we will be floating only the red boxes, either you can float both to the left, or you can float on to left, and another to right as well, depends on the layout, if it's 3 columns, you may float 2 columns to left where another one to the right so depends, though in this example, we have a simplified 2 column layout so will float one to left and the other to the right.

Markup and styles for creating the layout explained further down...

<div class="main_wrap">
    <div class="wrapper clear">
        <div class="floated_left">
            This<br />
            is<br />
            just<br />
            a<br />
            left<br />
            floated<br />
            column<br />
        <div class="floated_right">
            This<br />
            is<br />
            just<br />
            a<br />
            right<br />
            floated<br />
            column<br />

* {
    -moz-box-sizing: border-box;       /* Just for demo purpose */
    -webkkit-box-sizing: border-box;   /* Just for demo purpose */
    box-sizing: border-box;            /* Just for demo purpose */
    margin: 0;
    padding: 0;

.main_wrap {
    margin: 20px;
    border: 3px solid black;
    width: 520px;

header, footer {
    height: 50px;
    border: 3px solid silver;
    text-align: center;
    line-height: 50px;

.wrapper {
    border: 3px solid green;

.floated_left {
    float: left;
    width: 200px;
    border: 3px solid red;

.floated_right {
    float: right;
    width: 300px;
    border: 3px solid red;

.clear:after {
    clear: both;
    content: "";
    display: table;

Let's go step by step with the layout and see how float works..

First of all, we use the main wrapper element, you can just assume that it's your viewport, then we use header and assign a height of 50px so nothing fancy there. It's just a normal non floated block level element which will take up 100% horizontal space unless it's floated or we assign inline-block to it.

The first valid value for float is left so in our example, we use float: left; for .floated_left, so we intend to float a block to the left of our container element.

Column floated to the left

And yes, if you see, the parent element, which is .wrapper is collapsed, the one you see with a green border didn't expand, but it should right? Will come back to that in a while, for now, we have got a column floated to left.

Coming to the second column, lets it float this one to the right

Another column floated to the right

Here, we have a 300px wide column which we float to the right, which will sit beside the first column as it's floated to the left, and since it's floated to the left, it created empty gutter to the right, and since there was ample of space on the right, our right floated element sat perfectly beside the left one.

Still, the parent element is collapsed, well, let's fix that now. There are many ways to prevent the parent element from getting collapsed.

  • Add an empty block level element and use clear: both; before the parent element ends, which holds floated elements, now this one is a cheap solution to clear your floating elements which will do the job for you but, I would recommend not to use this.

Add, <div style="clear: both;"></div> before the .wrapper div ends, like

<div class="wrapper clear">
    <!-- Floated columns -->
    <div style="clear: both;"></div>


Well, that fixes very well, no collapsed parent anymore, but it adds unnecessary markup to the DOM, so some suggest, to use overflow: hidden; on the parent element holding floated child elements which work as intended.

Use overflow: hidden; on .wrapper

.wrapper {
    border: 3px solid green;
    overflow: hidden;


That saves us an element every time we need to clear float but as I tested various cases with this, it failed in one particular one, which uses box-shadow on the child elements.

Demo (Can't see the shadow on all 4 sides, overflow: hidden; causes this issue)

So what now? Save an element, no overflow: hidden; so go for a clear fix hack, use the below snippet in your CSS, and just as you use overflow: hidden; for the parent element, call the class below on the parent element to self-clear.

.clear:after {
    clear: both;
    content: "";
    display: table;

<div class="wrapper clear">
    <!-- Floated Elements -->


Here, shadow works as intended, also, it self-clears the parent element which prevents to collapse.

And lastly, we use footer after we clear the floated elements.


When is float: none; used anyways, as it is the default, so any use to declare float: none;?

Well, it depends, if you are going for a responsive design, you will use this value a lot of times, when you want your floated elements to render one below another at a certain resolution. For that float: none; property plays an important role there.

Few real-world examples of how float is useful.

  • The first example we already saw is to create one or more than one column layouts.
  • Using img floated inside p which will enable our content to flow around.

Demo (Without floating img)

Demo 2 (img floated to the left)

  • Using float for creating horizontal menu - Demo

Float second element as well, or use `margin`

Last but not the least, I want to explain this particular case where you float only single element to the left but you do not float the other, so what happens?

Suppose if we remove float: right; from our .floated_right class, the div will be rendered from extreme left as it isn't floated.


So in this case, either you can float the to the left as well


You can use margin-left which will be equal to the size of the left floated column i.e 200px wide.

How to convert Excel values into buckets?

May be not quite what you were looking for but how about using conditional formatting functionality of Excel

EDIT: As an alternate you could create a vba function that acts as a formula that will do the calulation for you. something like

Function getBucket(rng As Range) As String
    Dim strReturn As String

    Select Case rng.Value
        Case 0 to 10
            strReturn = "Small"
        Case 11 To 20
             strReturn = "Medium"
        Case 21 To 30
             strReturn = "Large"
        Case 31 To 40
             strReturn = "Huge"
        Case Else
             strReturn = "OMG!!!"
    End Select
    getBucket = strReturn
End Function

Crop image in android

Can you use default android Crop functionality?

Here is my code

private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties here
        cropIntent.putExtra("crop", true);
        // indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        // indicate output X and Y
        cropIntent.putExtra("outputX", 128);
        cropIntent.putExtra("outputY", 128);
        // retrieve data on return
        cropIntent.putExtra("return-data", true);
        // start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);;


final int PIC_CROP = 1;

at top.

In onActivity result method, writ following code:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PIC_CROP) {
        if (data != null) {
            // get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap
            Bitmap selectedBitmap = extras.getParcelable("data");


It is pretty easy for me to implement and also shows darken areas.

Check if an array item is set in JS

var assoc_pagine = new Array();

Don't use an Array for this. Arrays are for numerically-indexed lists. Just use a plain Object ({}).

What you are thinking of with the 'undefined' string is probably this:

if (typeof assoc_pagine[key]!=='undefined')

This is (more or less) the same as saying

if (assoc_pagine[key]!==undefined)

However, either way this is a bit ugly. You're dereferencing a key that may not exist (which would be an error in any more sensible language), and relying on JavaScript's weird hack of giving you the special undefined value for non-existent properties.

This also doesn't quite tell you if the property really wasn't there, or if it was there but explicitly set to the undefined value.

This is a more explicit, readable and IMO all-round better approach:

if (key in assoc_pagine)

How to set a default value for an existing column

cannot use alter column for that, use add instead


"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

I ran into a similar problem with the same error message using following code:

@Html.DisplayFor(model => model.EndDate.Value.ToShortDateString())

I found a good answer here

Turns out you can decorate the property in your model with a displayformat then apply a dataformatstring.

Be sure to import the following lib into your model:

using System.ComponentModel.DataAnnotations;

How to get text of an input text box during onKeyPress?

Handling the input event is a consistent solution: it is supported for textarea and input elements in all contemporary browsers and it fires exactly when you need it:

function edValueKeyPress() {
    var edValue = document.getElementById("edValue");
    var s = edValue.value;

    var lblValue = document.getElementById("lblValue");
    lblValue.innerText = "The text box contains: " + s;
<input id="edValue" type="text" onInput="edValueKeyPress()"><br>
<span id="lblValue">The text box contains: </span>

I'd rewrite this a bit, though:

function showCurrentValue(event)
    const value =;
    document.getElementById("label").innerText = value;
<input type="text" onInput="showCurrentValue(event)"><br>
The text box contains: <span id="label"></span>

Are there any Java method ordering conventions?

Not sure if there is universally accepted standard but my own preferences are;

  • constructors first
  • static methods next, if there is a main method, always before other static methods
  • non static methods next, usually in order of the significance of the method followed by any methods that it calls. This means that public methods that call other class methods appear towards the top and private methods that call no other methods usually end up towards the bottom
  • standard methods like toString, equals and hashcode next
  • getters and setters have a special place reserved right at the bottom of the class

How to loop an object in React?

you could also just have a return div like the one below and use the built in template literals of Javascript :

const tifs = {1: 'Joe', 2: 'Jane'};



Python, compute list difference

When having a look at TimeComplexity of In-operator, in worst case it works with O(n). Even for Sets.

So when comparing two arrays we'll have a TimeComplexity of O(n) in best case and O(n^2) in worst case.

An alternative (but unfortunately more complex) solution, which works with O(n) in best and worst case is this one:

# Compares the difference of list a and b
# uses a callback function to compare items
def diff(a, b, callback):
  a_missing_in_b = []
  ai = 0
  bi = 0

  a = sorted(a, callback)
  b = sorted(b, callback)

  while (ai < len(a)) and (bi < len(b)):

    cmp = callback(a[ai], b[bi])
    if cmp < 0:
      ai += 1
    elif cmp > 0:
      # Item b is missing in a
      bi += 1
      # a and b intersecting on this item
      ai += 1
      bi += 1

  # if a and b are not of same length, we need to add the remaining items
  for ai in xrange(ai, len(a)):

  return a_missing_in_b


>>> a=[1,2,3]
>>> b=[2,4,6]
>>> diff(a, b, cmp)
[1, 3]

Why should I use a container div in HTML?

The container div, and sometimes content div, are almost always used to allow for more sophisticated CSS styling. The body tag is special in some ways. Browsers don't treat it like a normal div; its position and dimensions are tied to the browser window.

But a container div is just a div and you can style it with margins and borders. You can give it a fixed width, and you can center it with margin-left: auto; margin-right: auto.

Plus, content, like a copyright notice for example, can go on the outside of the container div, but it can't go on the outside of the body, allowing for content on the outside of a border.

How to enable CORS in apache tomcat

Check this answer: Set CORS header in Tomcat

Note that you need Tomcat 7.0.41 or higher.

To know where the current instance of Tomcat is located try this:


You'll see the path in the console view.

Then look for /conf/web.xml on that folder, open it and add the lines of the above link.

Conda: Installing / upgrading directly from github

There's better support for this now through conda-env. You can, for example, now do:

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

It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml file.

If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml), then run the command: conda env update -f environment.yml.

It's more likely that you would want to create a new environment:

conda env create -f environment.yml (changed as supposed in the comments)

Callback function for JSONP with jQuery AJAX

This is what I do on mine

$(document).ready(function() {
  if ($('#userForm').valid()) {
    var formData = $("#userForm").serializeArray();
      url: '' + $('#Id').val() + '?callback=?',
      type: "GET",
      data: formData,
      dataType: "jsonp",
      jsonpCallback: "localJsonpCallback"

function localJsonpCallback(json) {
  if (!json.Error) {
  } else {

Validate Dynamically Added Input fields

In regards to @RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.

(function ($) {

    $.fn.initValidation = function () {


        return this;


This can be used like this:


Why does an onclick property set with setAttribute fail to work in IE?

function CheckBrowser(){
        navigator.userAgent.match(/Opera M/i)!=null||
            return 'OTHER';
            return 'IE';

function AddButt(i){
    var new_butt = document.createElement('input');
    new_butt.setAttribute('value','Delete Item');
    new_butt.setAttribute('id', 'answer_del_'+i);
        new_butt.setAttribute("onclick", function() { DelElemAnswer(i) });

Making a DateTime field in a database automatic?

Just right click on that column and select properties and write getdate()in Default value or image:

enter image description here

If you want do it in CodeFirst in EF you should add this attributes befor of your column definition:


this attributes can found in System.ComponentModel.Dataannotion.Schema.

In my opinion first one is better:))

What does 'git remote add upstream' help achieve?

Let's take an example: You want to contribute to django, so you fork its repository. In the while you work on your feature, there is much work done on the original repo by other people. So the code you forked is not the most up to date. setting a remote upstream and fetching it time to time makes sure your forked repo is in sync with the original repo.

Export and import table dump (.sql) using pgAdmin

If you have Git bash installed, you can do something like this:

/c/Program\ Files\ \(x86\)/PostgreSQL/9.3/bin/psql -U <pg_role_name> -d <pg_database_name> < <path_to_your>.sql

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

The problem is that you are calling ToString in a LINQ to Entities query. That means the parser is trying to convert the ToString call into its equivalent SQL (which isn't possible...hence the exception).

All you have to do is move the ToString call to a separate line:

var keyString = item.Key.ToString();

var pages = from p in context.entities
            where p.Serial == keyString
            select p;

If Else If In a Sql Server Function

Look at these lines:

If yes_ans > no_ans and yes_ans > na_ans

and similar. To what do "yes_ans" etc. refer? You're not using these in the context of a query; the "if exists" condition doesn't extend to the column names you're using inside.

Consider assigning those values to variables you can then use for your conditional flow below. Thus,

if exists (some record)
   set @var = column, @var2 = column2, ...

   if (@var1 > @var2)
      -- do something


The return type is also mismatched with the declaration. It would help a lot if you indented, used ANSI-standard punctuation (terminate statements with semicolons), and left out superfluous begin/end - you don't need these for single-statement lines executed as the result of a test.

Android - How to achieve setOnClickListener in Kotlin?

var tv = findViewById( as TextView

    tv.setOnClickListener {
       val i = Intent(this@MainActivity,

How to insert a new line in Linux shell script?

You could use the printf(1) command, e.g. like

printf "Hello times %d\nHere\n" $[2+3] 

The  printf command may accept arguments and needs a format control string similar (but not exactly the same) to the one for the standard C printf(3) function...

Quotation marks inside a string

String name = "\"john\"";

You have to escape the second pair of quotation marks using the \ character in front. It might be worth looking at this link, which explains in some detail.

Other scenario where you set variable:

String name2 = "\""+name+"\"";

Sequence in console:

> String name = "\"john\"";
> name
> String name2 = "\""+name+"\"";
> name2

Java: Add elements to arraylist with FOR loop where element name has increasing number

There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).

public class TheClass {

    private int theField= 42;

    public static void main(String[] args) throws Exception {

        TheClass c= new TheClass();


jQuery ajax request being block because Cross-Origin

Try to use JSONP in your Ajax call. It will bypass the Same Origin Policy.

Try example

    url: "",

    dataType: "jsonp",
    success: function( response ) {
        console.log( response ); // server response


How do I set a value in CKEditor with Javascript?

<textarea id="editor1" name="editor1">This is sample text</textarea>

<div id="trackingDiv" ></div>

<script type="text/javascript">
    CKEDITOR.replace( 'editor1' );


Let try this..

Update :

To set data :

Create instance First::

var editor = CKEDITOR.instances['editor1'];


editor.setData('your data');


editor.insertHtml('your html data');


editor.insertText('your text data');  

And Retrieve data from your editor::


If change the particular para HTML data in CKEditor.

var html = $(editor.editable.$);
$('#id_of_para',html).html('your html data');

These are the possible ways that I know in CKEditor

How to check if a column exists in Pandas

Just to suggest another way without using if statements, you can use the get() method for DataFrames. For performing the sum based on the question:

df['sum'] = df.get('A', df['B']) + df['C']

The DataFrame get method has similar behavior as python dictionaries.

How to disable Google asking permission to regularly check installed apps on my phone?

In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".

How to pass multiple parameters from ajax to mvc controller?

I think you may need to stringify the data using JSON.stringify.

 var data = JSON.stringify({ 
                 'StrContactDetails': Details,

        type: "POST",
        url: @url.Action("Dhp","SaveEmergencyContact"),
        data: data,
        success: function(){},
        contentType: 'application/json'

So the controller method would look like,

public ActionResult SaveEmergencyContact(string  StrContactDetails, bool IsPrimary)

How to copy a collection from one database to another in MongoDB

Using pymongo, you need to have both databases on same mongod, I did the following:

db = original database
db2 = database to be copied to

cursor = db["<collection to copy from>"].find()
for data in cursor:
    db2["<new collection>"].insert(data)

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

This was in response to your other question, that looks like it's been deleted....the point still stands.

Looks like a classic Unicode to ASCII issue. The trick would be to find where it's happening.

.NET works fine with Unicode, assuming it's told it's Unicode to begin with (or left at the default).

My guess is that your receiving app can't handle it. So, I'd probably use the ASCIIEncoder with an EncoderReplacementFallback with String.Empty:

using System.Text;

string inputString = GetInput();
var encoder = ASCIIEncoding.GetEncoder();
encoder.Fallback = new EncoderReplacementFallback(string.Empty);

byte[] bAsciiString = encoder.GetBytes(inputString);

// Do something with bytes...
// can write to a file as is
File.WriteAllBytes(FILE_NAME, bAsciiString);
// or turn back into a "clean" string
string cleanString = ASCIIEncoding.GetString(bAsciiString); 
// since the offending bytes have been removed, can use default encoding as well
Assert.AreEqual(cleanString, Default.GetString(bAsciiString));

Of course, in the old days, we'd just loop though and remove any chars greater than 127...well, those of us in the US at least. ;)

Delayed function calls

I though the perfect solution would be to have a timer handle the delayed action. FxCop doesn't like when you have an interval less then one second. I need to delay my actions until AFTER my DataGrid has completed sorting by column. I figured a one-shot timer (AutoReset = false) would be the solution, and it works perfectly. AND, FxCop will not let me suppress the warning!

Android: How to use webcam in emulator?

I suggest you to look at this highly rated blog post which manages to give a solution to the problem you're facing :

His code is based on the current Android APIs and should work in your case given that you are using a recent Android API.

Generate an integer that is not among four billion given ones

Perhaps I'm completely missing the point of this question, but you want to find an integer missing from a sorted file of integers?

Uhh... really? Let's think about what such a file would look like:

1 2 3 4 5 6 ... first missing number ... etc.

The solution to this problem seems trivial.

Android - drawable with rounded corners at the top only

Building upon busylee's answer, this is how you can make a drawable that only has one unrounded corner (top-left, in this example):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="">
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <!-- A numeric value is specified in "radius" for demonstrative purposes only,
                  it should be @dimen/val_name -->
            <corners android:radius="10dp" />
    <!-- To keep the TOP-LEFT corner UNROUNDED set both OPPOSITE offsets (bottom+right): -->
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />

Please note that the above drawable is not shown correctly in the Android Studio preview (2.0.0p7). To preview it anyway, create another view and use this as android:background="@drawable/...".

IIS Manager in Windows 10

Windows features, ISS Management Console

Under the windows feature list, make sure to check the IIS Management Console You also need to check additional check boxes as shown below:

Windows features, ISS, HTTP Features

Sizing elements to percentage of screen width/height

you can use MediaQuery with the current context of your widget and get width or height like this double width = MediaQuery.of(context).size.width double height = MediaQuery.of(context).size.height after that, you can multiply it with the percentage you want

How to update array value javascript?

Why not use an object1?

var dict = { "a": 1, "b": 2, "c": 3 };

Then you can update it like so

dict.a = 23;


dict["a"] = 23;

If you wan't to delete2 a particular key, it's as simple as:

delete dict.a;

1 See Objects vs arrays in Javascript for key/value pairs.
2 See the delete operator.

Center an element with "absolute" position and undefined width in CSS?

Sass/Compass version of a previous responsive solution:

#content {
  position: absolute;
  left: 50%;
  top: 50%;
  @include vendor(transform, translate(-50%, -50%));

What underlies this JavaScript idiom: var self = this?

The variable is captured by the inline functions defined in the method. this in the function will refer to another object. This way, you can make the function hold a reference to the this in the outer scope.

Resize svg when window is resized in d3.js

If you want to bind custom logic to resize event, nowadays you may start using ResizeObserver browser API for the bounding box of an SVGElement.
This will also handle the case when container is resized because of the nearby elements size change.
There is a polyfill for broader browser support.

This is how it may work in UI component:

function redrawGraph(container, { width, height }) {_x000D_
    .attr('height', height)_x000D_
    .attr('width', width)_x000D_
    .attr('height', height)_x000D_
    .attr('width', width);_x000D_
// Setup observer in constructor_x000D_
const resizeObserver = new ResizeObserver((entries, observer) => {_x000D_
  for (const entry of entries) {_x000D_
    // on resize logic specific to this component_x000D_
    redrawGraph(, entry.contentRect);_x000D_
// Observe the container_x000D_
const container = document.querySelector('.graph-container');_x000D_
.graph-container {_x000D_
  height: 75vh;_x000D_
  width: 75vw;_x000D_
.graph-container svg rect {_x000D_
  fill: gold;_x000D_
  stroke: steelblue;_x000D_
  stroke-width: 3px;_x000D_
<script src="[email protected]/dist/ResizeObserver.js"></script>_x000D_
<script src=""></script>_x000D_
<figure class="graph-container">_x000D_
  <svg width="100" height="100">_x000D_
    <rect x="0" y="0" width="100" height="100" />_x000D_

// unobserve in component destroy method

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

How do I make a batch file terminate upon encountering an error?

Check the errorlevel in an if statement, and then exit /b (exit the batch file only, not the entire cmd.exe process) for values other than 0.

same-executable-over-and-over.exe /with different "parameters"
if %errorlevel% neq 0 exit /b %errorlevel%

If you want the value of the errorlevel to propagate outside of your batch file

if %errorlevel% neq 0 exit /b %errorlevel%

but if this is inside a for it gets a bit tricky. You'll need something more like:

setlocal enabledelayedexpansion
for %%f in (C:\Windows\*) do (
    same-executable-over-and-over.exe /with different "parameters"
    if !errorlevel! neq 0 exit /b !errorlevel!

Edit: You have to check the error after each command. There's no global "on error goto" type of construct in cmd.exe/ batch. I've also updated my code per CodeMonkey, although I've never encountered a negative errorlevel in any of my batch-hacking on XP or Vista.

How can I use the HTML5 canvas element in IE?

You can try fxCanvas:

It implements almost all Canvas API within flash shim.

Get POST data in C#/ASP.NET

I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.

I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.

On the server, to turn the raw posted data back into a C# class, here's what I would do.

First, define a C# class which will contain the posted data.

Supposing my webpage is posting JSON data like this:

    "UserID" : 1,
    "FirstName" : "Mike",
    "LastName" : "Mike",
    "Address1" : "10 Really Street",
    "Address2" : "London"

Then I'd define a C# class like this...

public class JSONRequest
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }

(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)

Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...

    protected void Page_Load(object sender, EventArgs e)
        string jsonString = "";
        HttpContext.Current.Request.InputStream.Position = 0;
        using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
            jsonString = inputStream.ReadToEnd();
        JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);

And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.

Create list of single item repeated N times

As others have pointed out, using the * operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never used, you can use the anonymous underscore variable.

[e for _ in xrange(n)]

Find out who is locking a file on a network share

sounds like you have the same problem i tried to solve here. in my case, it's a Linux fileserver (running samba, of course), so i can log in and see what process is locking the file; unfortunately, i haven't found how to close it without killing the responsible session. AFAICT, the windows client 'thinks' it's closed; but didn't bother telling the fileserver.

Ifelse statement in R with multiple conditions

Very simple use of any

df <- <your structure>

df$Den <- apply(df,1,function(i) {ifelse(any( | any(i != 1), 0, 1)})

How to set a value for a selectize.js input?

First load select dropdown and then selectize it. It will work with normal $(select).val().

Convert base-2 binary number string to int

Another way to do this is by using the bitstring module:

>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint

Note that the unsigned integer is different from the signed integer:


The bitstring module isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.

Show data on mouseover of circle

There is an awesome library for doing that that I recently discovered. It's simple to use and the result is quite neat: d3-tip.

You can see an example here:

enter image description here

Basically, all you have to do is to download(index.js), include the script:

<script src="index.js"></script>

and then follow the instructions from here (same link as example)

But for your code, it would be something like:

define the method:

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Frequency:</strong> <span style='color:red'>" + d.frequency + "</span>";

create your svg (as you already do)

var svg = ...

call the method:;

add tip to your object:

   .on('mouseout', tip.hide)

Don't forget to add the CSS:

.d3-tip {
  line-height: 1;
  font-weight: bold;
  padding: 12px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  border-radius: 2px;

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  font-size: 10px;
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.8);
  content: "\25BC";
  position: absolute;
  text-align: center;

/* Style northward tooltips differently */
.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;

Java: Convert String to TimeStamp

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Util {
  public static Timestamp convertStringToTimestamp(String strDate) {
    try {
      DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
       // you can change format of date
      Date date = formatter.parse(strDate);
      Timestamp timeStampDate = new Timestamp(date.getTime());

      return timeStampDate;
    } catch (ParseException e) {
      System.out.println("Exception :" + e);
      return null;

Child with max-height: 100% overflows parent

.container {  
display: flex;
  background: blue; 
  padding: 10px; 
  max-height: 200px; 
  max-width: 200px; 

img { 
 object-fit: contain;
  max-height: 100%; 
  max-width: 100%; 
<div class="container">
  <img src="" />

Why does git perform fast-forward merges by default?

Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.

Warning: Non-fast-forwarding has potential side effects as well. Please review, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master.

alt text
(From, Vincent Driessen, post "A successful Git branching model")

Incorporating a finished feature on develop

Finished features may be merged into the develop branch to add them to the upcoming release:

$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.

Jakub Narebski also mentions the config merge.ff:

By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set to false, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the --no-ff option from the command line).
When set to 'only', only such fast-forward merges are allowed (equivalent to giving the --ff-only option from the command line).

The fast-forward is the default because:

  • short-lived branches are very easy to create and use in Git
  • short-lived branches often isolate many commits that can be reorganized freely within that branch
  • those commits are actually part of the main branch: once reorganized, the main branch is fast-forwarded to include them.

But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.

In this case, you can end up setting this kind of config file:

[branch "master"]
# This is the list of cmdline options that should be added to git-merge 
# when I merge commits into the master branch.

# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.

# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.

mergeoptions = --no-commit --no-ff

The OP adds in the comments:

I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?

Jefromi answers:

I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.

To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.

More generally, I add:

it really depends on your development workflow:

  • if it is linear, one branch makes sense.
  • If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.

See "When should you branch?"

Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".

Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.

Configure Flask dev server to be visible across the network

go to project path set SET FLASK_ENV=development

flask run -h [yourIP] -p 8080 you will following o/p on CMD:- * Serving Flask app "" (lazy loading) * Environment: development * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 199-519-700 * Running on http://[yourIP]:8080/ (Press CTRL+C to quit)

How to quickly test some javascript code?

If you want to edit some complex javascript I suggest you use JsFiddle. Alternatively, for smaller pieces of javascript you can just run it through your browser URL bar, here's an example:

javascript:alert("hello world");

And, as it was already suggested both Firebug and Chrome developer tools have Javascript console, in which you can type in your javascript to execute. So do Internet Explorer 8+, Opera, Safari and potentially other modern browsers.

Check if key exists in JSON object using jQuery

if(typeof theObject['key'] != 'undefined'){
     //key exists, do stuff


if(typeof theObject.key != 'undefined'){
    //object exists, do stuff

I'm writing here because no one seems to give the right answer..

I know it's old...

Somebody might question the same thing..

Using jQuery to compare two arrays of Javascript objects

Well, if you want to compare only the contents of arrays, there's a useful jQuery function $.inArray()

var arr = [11, "String #1", 14, "String #2"];
var arr_true = ["String #1", 14, "String #2", 11]; // contents are the same as arr
var arr_false = ["String #1", 14, "String #2", 16]; // contents differ

function test(arr_1, arr_2) {
    var equal = arr_1.length == arr_2.length; // if array sizes mismatches, then we assume, that they are not equal
    if (equal) {
        $.each(arr_1, function (foo, val) {
            if (!equal) return false;
            if ($.inArray(val, arr_2) == -1) {
                equal = false;
            } else {
                equal = true;
    return equal;

alert('Array contents are the same? ' + test(arr, arr_true)); //- returns true
alert('Array contents are the same? ' + test(arr, arr_false)); //- returns false

Open Facebook Page in Facebook App (if installed) on Android

This works on the latest version:

Go to ( for instance).

Copy your id Use this method:

public static Intent getOpenFacebookIntent(Context context) {
    try {
        context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
        return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/<id_here>"));
    } catch (Exception e) {
        return new Intent(Intent.ACTION_VIEW,Uri.parse("<user_name_here>"));

HTML text input allow only numeric input

When it comes to fool-proofing UX, one should always try to keep a reference point for the 'user's intelligence'.

While neglecting everything other than numbers, a dot and a hyphen would seem like the perfect choice, you should also consider letting them enter any content, and when they're done, purify the input; if not a valid number, show error. This method would make sure no matter what the user manages to do, the result will always be valid. If the user is naive enough not to understand the warnings and error messages, pressing a button and seeing that nothing happens (as in keycode comparison) will only confuse him/her more.

Also, for forms, validation and error message display are almost a necessity. So, the provisions might already be there. Here's the algorithm:

  1. On losing-focus or form-submission, do following.

    1.1. Read content from the input and apply parseFloat to result

    1.2. If the result is a Non-accessible-Number (NaN), reset the input field and pop-up an error message: "Please enter a valid number: eg. 235 or -654 or 321.526 or -6352.646584".

    1.3. Else, if String(result)!==(content from input), change value of the field to result and show warning message: "The value you entered have been modified. Input must be a valid number: eg. 235 or -654 or 321.526 or -6352.646584". For a field that cannot allow any unconfirmed value, then this condition may be added to step 1.2.

    1.4. Else, do nothing.

This method also gives you the added advantage of performing validations based on minimum value, maximum value, decimal places, etc if necessary. Just have to do these operations on the result after step 1.2.


  1. The input will allow the user to enter any value until the focus is lost or the form is submitted. But if the instructions on filling the field were clear enough, in 90% of the cases this might not come up.

  2. If step 1.3 is used to display a warning, it might be overlooked by the user and might result in unintentional input submission. Throwing an error or displaying the warning properly would solve this.

  3. Speed. This might be slower in microseconds than the regex method.

Advantages: Assuming the user have basic knowledge to read and understand,

  1. Highly customizable with options.

  2. Works cross browser and independent of language.

  3. Makes use of already available features in a form to display errors and warnings.

Convert a object into JSON in REST service by Spring MVC

Spring framework itself handles json conversion when controller is annotated properly.

For eg:

   @PutMapping(produces = {"application/json"})
        public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;

Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.

If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.


ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();

Using css transform property in jQuery

I started using the 'prefix-free' Script available at so I don't have to take care about the vendor prefixes. It neatly takes care of setting the correct vendor prefix behind the scenes for you. Plus a jQuery Plugin is available as well so one can still use jQuery's .css() method without code changes, so the suggested line in combination with prefix-free would be all you need:

$('.user-text').css('transform', 'scale(' + ui.value + ')');

Add & delete view from Layout

you can use addView or removeView


// Root Layout
LinearLayout linearLayout = new LinearLayout(context);

// TextView
TextView textView = new TextView(context);

// Add TextView in LinearLayout

// Remove TextView from LinearLayout


// Root Layout
val linearLayout = LinearLayout(context)
linearLayout.gravity = Gravity.CENTER
linearLayout.orientation = LinearLayout.VERTICAL

// TextView
val textView = TextView(context)
textView.text = "Sample"

// Add TextView in LinearLayout

// Remove TextView from LinearLayout

How to get complete month name from DateTime

You can do as mservidio suggested, or even better, keep track of your culture using this overload:

DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);

Oracle database: How to read a BLOB?

If the content is not too large, you can also use

SELECT CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) FROM <table>;


SELECT DUMP ( CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) ) FROM <table>;

This will show you the HEX values.

MySQL LIMIT on DELETE statement

Use row_count - your_desired_offset

So if we had 10 rows and want to offset 3

 10 - 3 = 7

Now the query delete from table where this = that order asc limit 7 keeps the last 3, and order desc to keep the first 3:

$row_count - $offset = $limit

Delete from table where entry = criteria order by ts asc limit $limit

How to extract the nth word and count word occurrences in a MySQL string?

The following is a proposed solution for the OP's specific problem (extracting the 2nd word of a string), but it should be noted that, as mc0e's answer states, actually extracting regex matches is not supported out-of-the-box in MySQL. If you really need this, then your choices are basically to 1) do it in post-processing on the client, or 2) install a MySQL extension to support it.

BenWells has it very almost correct. Working from his code, here's a slightly adjusted version:

  LOCATE(' ', sentence) + CHAR_LENGTH(' '),
  LOCATE(' ', sentence,
  ( LOCATE(' ', sentence) + 1 ) - ( LOCATE(' ', sentence) + CHAR_LENGTH(' ') )

As a working example, I used:

  LOCATE(' ', sentence) + CHAR_LENGTH(' '),
  LOCATE(' ', sentence,
  ( LOCATE(' ', sentence) + 1 ) - ( LOCATE(' ', sentence) + CHAR_LENGTH(' ') )
) as string
FROM (SELECT 'THIS IS A TEST' AS sentence) temp

This successfully extracts the word IS

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:


Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.

For a detailed reference on GCC's linker option, please read here.

PHP FPM - check if running

PHP-FPM is a service that spawns new PHP processes when needed, usually through a fast-cgi module like nginx. You can tell (with a margin of error) by just checking the init.d script e.g. "sudo /etc/init.d/php-fpm status"

What port or unix file socket is being used is up to the configuration, but often is just TCP port 9000. i.e.

The best way to tell if it is running correctly is to have nginx running, and setup a virtual host that will fast-cgi pass to PHP-FPM, and just check it with wget or a browser.

Is there a pretty print for PHP?

For simplicity, print_r() and var_dump() can't be beat. If you want something a little fancier or are dealing with large lists and/or deeply nested data, Krumo will make your life much easier - it provides you with a nicely formatted collapsing/expanding display.

Indirectly referenced from required .class file

I was getting this error:

The type cannot be resolved. It is indirectly referenced from required .class files

Doing the following fixed it for me:

Properties -> Java build path -> Libraries -> Server Library[wps.base.v61]unbound -> Websphere Portal v6.1 on WAS 7 -> Finish -> OK

Spring Data JPA findOne() change to Optional how to use this?

I always write a default method "findByIdOrError" in widely used CrudRepository repos/interfaces.

public interface RequestRepository extends CrudRepository<Request, Integer> {

    default Request findByIdOrError(Integer id) {
        return findById(id).orElseThrow(EntityNotFoundException::new);

Fastest method to replace all instances of a character in a string

I think the real answer is that it completely depends on what your inputs look like. I created a JsFiddle to try a bunch of these and a couple of my own against various inputs. No matter how I look at the results, I see no clear winner.

  • RegExp wasn't the fastest in any of the test cases, but it wasn't bad either.
  • Split/Join approach seems fastest for sparse replacements.
  • This one I wrote seems fastest for small inputs and dense replacements:

    function replaceAllOneCharAtATime(inSource, inToReplace, inReplaceWith) {
        var output="";
        var firstReplaceCompareCharacter = inToReplace.charAt(0);
        var sourceLength = inSource.length;
        var replaceLengthMinusOne = inToReplace.length - 1;
        for(var i = 0; i < sourceLength; i++){
            var currentCharacter = inSource.charAt(i);
            var compareIndex = i;
            var replaceIndex = 0;
            var sourceCompareCharacter = currentCharacter;
            var replaceCompareCharacter = firstReplaceCompareCharacter;
                if(sourceCompareCharacter != replaceCompareCharacter){
                output += currentCharacter;
            if(replaceIndex >= replaceLengthMinusOne) {
                output += inReplaceWith;
                //was a match
            compareIndex++; replaceIndex++;
            if(i >= sourceLength){
                // not a match
            sourceCompareCharacter = inSource.charAt(compareIndex)
                replaceCompareCharacter = inToReplace.charAt(replaceIndex);
            replaceCompareCharacter += currentCharacter;
        return output;

jQuery UI Dialog individual CSS styling

Try these:

#dialog_style1 .ui-dialog-titlebar { display:none; }
#dialog_style2 .ui-dialog-titlebar { color:#aaa; }

The best recommendation I can give for you is to load the page in Firefox, open the dialog and inspect it with Firebug, then try different selectors in the console, and see what works. You may need to use some of the other descendant selectors.

JPA CascadeType.ALL does not delete orphans

you can use @PrivateOwned to delete orphans e.g

@OneToMany(mappedBy = "masterData", cascade = {
        CascadeType.ALL })
private List<Data> dataList;

Make a number a percentage

The best solution, where en is the English locale:

fraction.toLocaleString("en", {style: "percent"})

How To Remove Outline Border From Input Button

It's greatly simple than you think. When the button is focussed, apply the outline property, like this:

button:focus {
    outline: 0 !important;

But when I use none value, it doesn't work for me.

How can I get nth element from a list?

Haskell's standard list data type forall t. [t] in implementation closely resembles a canonical C linked list, and shares its essentially properties. Linked lists are very different from arrays. Most notably, access by index is a O(n) linear-, instead of a O(1) constant-time operation.

If you require frequent random access, consider the Data.Array standard.

!! is an unsafe partially defined function, provoking a crash for out-of-range indices. Be aware that the standard library contains some such partial functions (head, last, etc.). For safety, use an option type Maybe, or the Safe module.

Example of a reasonably efficient, robust total (for indices = 0) indexing function:

data Maybe a = Nothing | Just a

lookup :: Int -> [a] -> Maybe a
lookup _ []       = Nothing
lookup 0 (x : _)  = Just x
lookup i (_ : xs) = lookup (i - 1) xs

Working with linked lists, often ordinals are convenient:

nth :: Int -> [a] -> Maybe a
nth _ []       = Nothing
nth 1 (x : _)  = Just x
nth n (_ : xs) = nth (n - 1) xs

How to get JavaScript caller function line number? How to get JavaScript caller source URL?

Line number is actually something static, so if you just want it for logging then it could be preprocessed with something like gulp. I've written a small gulp plugin that does exactly that:

var gulp = require('gulp');
var logLine = require('gulp-log-line');
gulp.task('log-line', function() {
    return gulp.src("file.js", {buffer : true})
    //Write here the loggers you use.


gulp.task('default', ['log-line'])

This will attach the file name and line to all logs from console.log, so console.log(something) will become console.log('filePath:fileNumber', something). The advantage is that now you can concat your files, transpile them... and you will still get the line

Is the buildSessionFactory() Configuration method deprecated in Hibernate

If you are using Hibernate 5.2 and above then you can use this:

  private static StandardServiceRegistry registry;
  private static SessionFactory sessionFactory;

  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
      try {
        // Creating a registry
        registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

        // Create the MetadataSources
        MetadataSources sources = new MetadataSources(registry);

        // Create the Metadata
        Metadata metadata = sources.getMetadataBuilder().build();

        // Create SessionFactory
        sessionFactory = metadata.getSessionFactoryBuilder().build();

      } catch (Exception e) {
        if (registry != null) {
    return sessionFactory;

  //To shut down
 public static void shutdown() {
    if (registry != null) {

How do I enable EF migrations for multiple contexts to separate databases?

I just bumped into the same problem and I used the following solution (all from Package Manager Console)

PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextA" -ContextTypeName MyProject.Models.ContextA
PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextB" -ContextTypeName MyProject.Models.ContextB

This will create 2 separate folders in the Migrations folder. Each will contain the generated Configuration.cs file. Unfortunately you still have to rename those Configuration.cs files otherwise there will be complaints about having two of them. I renamed my files to ConfigA.cs and ConfigB.cs

EDIT: (courtesy Kevin McPheat) Remember when renaming the Configuration.cs files, also rename the class names and constructors /EDIT

With this structure you can simply do

PM> Add-Migration -ConfigurationTypeName ConfigA
PM> Add-Migration -ConfigurationTypeName ConfigB

Which will create the code files for the migration inside the folder next to the config files (this is nice to keep those files together)

PM> Update-Database -ConfigurationTypeName ConfigA
PM> Update-Database -ConfigurationTypeName ConfigB

And last but not least those two commands will apply the correct migrations to their corrseponding databases.

EDIT 08 Feb, 2016: I have done a little testing with EF7 version 7.0.0-rc1-16348

I could not get the -o|--outputDir option to work. It kept on giving Microsoft.Dnx.Runtime.Common.Commandline.CommandParsingException: Unrecognized command or argument

However it looks like the first time an migration is added it is added into the Migrations folder, and a subsequent migration for another context is automatically put into a subdolder of migrations.

The original names ContextA seems to violate some naming conventions so I now use ContextAContext and ContextBContext. Using these names you could use the following commands: (note that my dnx still works from the package manager console and I do not like to open a separate CMD window to do migrations)

PM> dnx ef migrations add Initial -c "ContextAContext"
PM> dnx ef migrations add Initial -c "ContextBContext"

This will create a model snapshot and a initial migration in the Migrations folder for ContextAContext. It will create a folder named ContextB containing these files for ContextBContext

I manually added a ContextA folder and moved the migration files from ContextAContext into that folder. Then I renamed the namespace inside those files (snapshot file, initial migration and note that there is a third file under the initial migration file ... designer.cs). I had to add .ContextA to the namespace, and from there the framework handles it automatically again.

Using the following commands would create a new migration for each context

PM>  dnx ef migrations add Update1 -c "ContextAContext"
PM>  dnx ef migrations add Update1 -c "ContextBContext"

and the generated files are put in the correct folders.

How to make/get a multi size .ico file?

ImageMagick, the free and open source image manipulation toolkit, can easily do this:

Note: Since ImageMagick 7, the CLI has changed slightly, you need to add magick in front of any commands.

magick convert icon-16.png icon-32.png icon-64.png icon-128.png icon.ico

See also, that has the example:

magick convert image.png -bordercolor white -border 0 \
          \( -clone 0 -resize 16x16 \) \
          \( -clone 0 -resize 32x32 \) \
          \( -clone 0 -resize 48x48 \) \
          \( -clone 0 -resize 64x64 \) \
          -delete 0 -alpha off -colors 256 favicon.ico

There is also now the shorter:

magick convert image.png -define icon:auto-resize="256,128,96,64,48,32,16" favicon.ico

How to make an AlertDialog in Flutter?

Here is a shorter, but complete code.

If you need a dialog with only one button:

await showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('Message'),
        content: Text(
                'Your file is saved.'),
        actions: <Widget>[
          new FlatButton(
            onPressed: () {
              Navigator.of(context, rootNavigator: true)
                  .pop(); // dismisses only the dialog and returns nothing
            child: new Text('OK'),

If you need a dialog with Yes/No buttons:

onPressed: () async {
bool result = await showDialog(
  context: context,
  builder: (context) {
    return AlertDialog(
      title: Text('Confirmation'),
      content: Text('Do you want to save?'),
      actions: <Widget>[
        new FlatButton(
          onPressed: () {
            Navigator.of(context, rootNavigator: true)
                .pop(false); // dismisses only the dialog and returns false
          child: Text('No'),
          onPressed: () {
            Navigator.of(context, rootNavigator: true)
                .pop(true); // dismisses only the dialog and returns true
          child: Text('Yes'),

if (result) {
  if (missingvalue) {
    Scaffold.of(context).showSnackBar(new SnackBar(
      content: new Text('Missing Value'),
  } else {
    Navigator.of(context).pop(_myObject); // dismisses the entire widget
} else {
  Navigator.of(context).pop(_myObject); // dismisses the entire widget

How is using OnClickListener interface different via XML and Java code?

using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener then add the variable Button button1; then add this to your onCreate()

button1 = (Button) findViewById(;

when you implement OnClickListener you need to add the inherited method onClick() where you will handle your clicks

Regex matching in a Bash if statement

There are a couple of important things to know about bash's [[ ]] construction. The first:

Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.

The second thing:

An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.

Consequently, $v on either side of the =~ will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.

So if you write: [[ $x =~ [$0-9a-zA-Z] ]], the $0 inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0 ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]], then the right-hand side will be treated as an ordinary string, not a regex (and $0 will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]

Similarly, the expression between the [[ and ]] is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]. Other characters similarly need to be escaped, like #, which would start a comment if not quoted. Of course, you can put the pattern into a variable:

pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...

For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:

# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...

Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:

valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...

! negates the test, turning it into a "does not match" operator, and a [^...] regex character class means "any character other than ...".

The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ] into $valid, even if $valid were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ] in a character class, it needs to go at the beginning. - can go at the beginning or the end, so if you need both ] and -, you need to start with ] and end with -, leading to the regex "I know what I'm doing" emoticon: [][-])

IF... OR IF... in a windows batch file

Thanks for this post, it helped me a lot.

Dunno if it can help but I had the issue and thanks to you I found what I think is another way to solve it based on this boolean equivalence:

"A or B" is the same as "not(not A and not B)"


IF [%var%] == [1] OR IF [%var%] == [2] ECHO TRUE


IF not [%var%] == [1] IF not [%var%] == [2] ECHO FALSE

403 - Forbidden: Access is denied. ASP.Net MVC

In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :

  • IIS is pointing to an empty folder.
  • You do not have a default document set.

Change onclick action with a Javascript function

Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).

document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );

How to output loop.counter in python jinja template?

Inside of a for-loop block, you can access some special variables including loop.index --but no loop.counter. From the official docs:

Variable    Description
loop.index  The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex   The number of iterations from the end of the loop (1 indexed)
loop.revindex0  The number of iterations from the end of the loop (0 indexed)
loop.first  True if first iteration.
loop.last   True if last iteration.
loop.length The number of items in the sequence.
loop.cycle  A helper function to cycle between a list of sequences. See the explanation below.
loop.depth  Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem   The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem   The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val)  True if previously called with a different value (or not called at all).

What is the difference between Select and Project Operations

The difference between the project operator (p) in relational algebra and the SELECT keyword in SQL is that if the resulting table/set has more than one occurrences of the same tuple, then p will return only one of them, while SQL SELECT will return all.

Python 3: UnboundLocalError: local variable referenced before assignment

If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.

In your case, Var1 is considered as a local variable, and it's used before being set, thus the error.

To solve this problem, you can explicitly say it's a global by putting global Var1 in you function.

Var1 = 1
Var2 = 0
def function():
    global Var1
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    Var1 =- 1

AngularJS format JSON string output

You can use an optional parameter of JSON.stringify()

JSON.stringify(value[, replacer [, space]])


  • value The value to convert to a JSON string.
  • replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
  • space Causes the resulting string to be pretty-printed.

For example:

JSON.stringify({a:1,b:2,c:{d:3, e:4}},null,"    ")

will give you following result:

    "a": 1,
    "b": 2,
    "c": {
        "d": 3,
        "e": 4

How to update and order by using ms sql

I have to offer this as a better approach - you don't always have the luxury of an identity field:

SET [status]=10
  Select TOP (10) *
  FROM messages
  WHERE [status]=0
  ORDER BY [priority] DESC
) m

You can also make the sub-query as complicated as you want - joining multiple tables, etc...

Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages table. It can be used to update the top N rows from any table, even if that table has no unique key at all.

Android basics: running code in the UI thread

The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.

TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
    private String txt;
    public void run() {
    public void setText(String txt){
        this.txt = txt;


It can be used from anywhere like this:


Double decimal formatting in Java

First import NumberFormat. Then add this:

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

This will give you two decimal places and put a dollar sign if it's dealing with currency.

import java.text.NumberFormat;
public class Payroll 
     * @param args the command line arguments
    public static void main(String[] args) 
    int hoursWorked = 80;
    double hourlyPay = 15.52;

    double grossPay = hoursWorked * hourlyPay;
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

    System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));


Link vs compile vs controller

A directive allows you to extend the HTML vocabulary in a declarative fashion for building web components. The ng-app attribute is a directive, so is ng-controller and all of the ng- prefixed attributes. Directives can be attributes, tags or even class names, comments.

How directives are born (compilation and instantiation)

Compile: We’ll use the compile function to both manipulate the DOM before it’s rendered and return a link function (that will handle the linking for us). This also is the place to put any methods that need to be shared around with all of the instances of this directive.

link: We’ll use the link function to register all listeners on a specific DOM element (that’s cloned from the template) and set up our bindings to the page.

If set in the compile() function they would only have been set once (which is often what you want). If set in the link() function they would be set every time the HTML element is bound to data in the object.

<div ng-repeat="i in [0,1,2]">
        <div>Inner content</div>

app.directive("simple", function(){
   return {
     restrict: "EA",
     template:"<div>{{label}}<div ng-transclude></div></div>",        
     compile: function(element, attributes){  
     return {
             pre: function(scope, element, attributes, controller, transcludeFn){

             post: function(scope, element, attributes, controller, transcludeFn){

     controller: function($scope){


Compile function returns the pre and post link function. In the pre link function we have the instance template and also the scope from the controller, but yet the template is not bound to scope and still don't have transcluded content.

Post link function is where post link is the last function to execute. Now the transclusion is complete, the template is linked to a scope, and the view will update with data bound values after the next digest cycle. The link option is just a shortcut to setting up a post-link function.

controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.

You have to specify the name of the directive to be required – It should be bound to same element or its parent. The name can be prefixed with:

? – Will not raise any error if a mentioned directive does not exist.
^ – Will look for the directive on parent elements, if not available on the same element.

Use square bracket [‘directive1', ‘directive2', ‘directive3'] to require multiple directives controller.

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

app.controller('MainCtrl', function($scope, $element) {

app.directive('parentDirective', function() {
  return {
    restrict: 'E',
    template: '<child-directive></child-directive>',
    controller: function($scope, $element){
      this.variable = "Hi Vinothbabu"

app.directive('childDirective', function() {
  return {
    restrict:  'E',
    template: '<h1>I am child</h1>',
    replace: true,
    require: '^parentDirective',
    link: function($scope, $element, attr, parentDirectCtrl){
      //you now have access to parentDirectCtrl.variable

Bash or KornShell (ksh)?

I don't have experience with ksh, but I have used both bash and zsh. I prefer zsh over bash because of its support for very powerful file globbing, variable expansion modifiers, and faster tab completion.

Here's a quick intro:

How to access Session variables and set them in javascript?

i used my .php file to put required into sessions

$_SESSION['name'] = $phparray["name"]; $ajaxoutput['name'] =$phparray["name"];

in my .js file i used

sessionStorage.setItem("name", ajaxreturnedarray["name"]);

and i retrieved this using

var myName= sessionStorage.getItem("name");

in other .js files or in same .js files

if i keep it as it is , it will return same at all times even you loggedout. so while logging out i made

sessionStorage.setItem("name", "");

using this i emptied local variable. i used this process in single page website login/logout sessions. i hope this way will work for you because it worked for me. plz let me know your experiences.

What's the best/easiest GUI Library for Ruby?

Here is a good resource for you:

has links comparing basically all of them.

How do I get the current absolute URL in Ruby on Rails?

I needed the application URL but with the subdirectory. I used:

root_url(:only_path => false)

How to implement reCaptcha for ASP.NET MVC?

There are a few great examples:

This has also been covered before in this Stack Overflow question.

NuGet Google reCAPTCHA V2 for MVC 4 and 5

Convert string to decimal number with 2 decimal places in Java

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

System.out.println("liters of petrol before putting in editor : "+litersOfPetrol);

You print Float here, that has no format at all.

To print formatted float, just use

String formatted = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : " + formatted);

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

Import functions from another js file. Javascript

//In module.js add below code

export function multiply() {
    return 2 * 3;

// Consume the module in calc.js

import { multiply } from './modules.js';

const result = multiply();

console.log(`Result: ${result}`);

// Module.html

<!DOCTYPE html>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <script type="module" src="./calc.js"></script>

Its a design pattern same code can be found below, please use a live server to test it else you will get CORS error

What is the difference between "is None" and "== None"

class Foo:
    def __eq__(self,other):
        return True

# True

print(foo is None)
# False

How do I restart nginx only after the configuration test was successful on Ubuntu?

As of nginx 1.8.0, the correct solution is

sudo nginx -t && sudo service nginx reload

Note that due to a bug, configtest always returns a zero exit code even if the config file has an error.

Switch on Enum in Java

First, you can switch on an enum in Java. I'm guessing you intended to say you can’t, but you can. chars have a set range of values, so it's easy to compare. Strings can be anything.

A switch statement is usually implemented as a jump table (branch table) in the underlying compilation, which is only possible with a finite set of values. C# can switch on strings, but it causes a performance decrease because a jump table cannot be used.

Java 7 and later supports String switches with the same characteristics.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:

By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->

See also:

What exactly does stringstream do?

From C++ Primer:

The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.

I come across some cases where it is both convenient and concise to use stringstream.

case 1

It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.

Suppose a and b are complex numbers expressed in string format, we want to get the result of multiplication of a and b also in string format. The code is as follows:

string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;

int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of 
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;

out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';

// final result in string format
string result = out.str() 

case 2

It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:

string simplifyPath(string path) {
    string res, tmp;
    vector<string> stk;
    stringstream ss(path);
    while(getline(ss,tmp,'/')) {
        if (tmp == "" or tmp == ".") continue;
        if (tmp == ".." and !stk.empty()) stk.pop_back();
        else if (tmp != "..") stk.push_back(tmp);
    for(auto str : stk) res += "/"+str;
    return res.empty() ? "/" : res; 

Without the use of stringstream, it would be difficult to write such concise code.

What's the difference between window.location and document.location in JavaScript?

document.location was originally a read-only property, although Gecko browsers allow you to assign to it as well. For cross-browser safety, use window.location instead.

Read more:



Fatal error: Call to a member function bind_param() on boolean

Even when the query syntax is correct, prepare could return false, if there was a previous statement and it wasn't closed. Always close your previous statement with


If the syntax is correct, the following query will run well too.

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

I think this is what you need:


This will allow you to trigger the body click event from anywhere.

jQuery - passing value from one input to another

It's simpler if you modify your HTML a little bit:

<label for="first_name">First Name</label>
<input type="text" id="name" name="name" />

<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" />

<label for="firstname">Firstname</label>
<input type="text" id="firstname" name="firstname" disabled="disabled" />

then it's relatively simple

$(document).ready(function() { 
    $('#name').change(function() {

Leave out quotes when copying from cell

It's also possible to remove these double-quotes by placing your result on the "Clean" function.



The output will be pasted without the double-quotes on other programs such as Notepad++.

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

It's possible that the HTML5 Doctype is causing you problems with those older browsers. It could also be down to something funky related to the HTML5 shiv.

You could try switching to one of the XHTML doctypes and changing your markup accordingly, at least temporarily. This might allow you to narrow the problem down.

Is your design breaking when those IEs switch to quirks mode? If it's your CSS causing things to display strangely, it might be worth working on the CSS so the site looks the same even when the browsers switch modes.

zsh compinit: insecure directories

On macOS Sierra you need to run: sudo chown -R $(whoami):staff /usr/local

How can I create a product key for my C# application?

If you are asking about the keys that you can type in, like Windows product keys, then they are based on some checks. If you are talking about the keys that you have to copy paste, then they are based on a digitial signature (private key encryption).

A simple product key logic could be to start with saying that the product key consists of four 5-digit groups, like abcde-fghij-kljmo-pqrst, and then go on to specify internal relationships like f+k+p should equal a, meaning the first digits of the 2, 3 and 4 group should total to a. This means that 8xxxx-2xxxx-4xxxx-2xxxx is valid, so is 8xxxx-1xxxx-0xxxx-7xxxx. Of course, there would be other relationships as well, including complex relations like, if the second digit of the first group is odd, then the last digit of the last group should be odd too. This way there would be generators for product keys and verification of product keys would simply check if it matches all the rules.

Encryption are normally the string of information about the license encrypted using a private key (== digitally signed) and converted to Base64. The public key is distributed with the application. When the Base64 string arrives, it is verified (==decrypted) by the public key and if found valid, the product is activated.

Combine [NgStyle] With Condition (if..else)

<h2 [ngStyle]="serverStatus == 'Offline'? {'color': 'red'{'color':'green'}">Server with ID: {{serverId}} is {{getServerStatus()}} </h2>

or you can also use something like this:

<h2 [ngStyle]="{backgroundColor: getColor()}">Server with ID: {{serverId}} is {{getServerStatus()}}</h2>

and in the *.ts

getColor(){return this.serverStatus === 'Offline' ? 'red' : 'green';}

Float a div right, without impacting on design

If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:


If you want it to float at the right of a particular parent section, you can add position: relative to that section.

SQL Server Configuration Manager not found

Go to this location C:\Windows\System32 and find SQLServerManager . Worked for me. Configuration manager was there but somehow wasn't showing up in search results.

EF LINQ include multiple and nested entities

this is from my project

 var saleHeadBranch = await _context.SaleHeadBranch
 .Include(d => d.SaleDetailBranch)
 .ThenInclude(d => d.Item)
 .Where(d => d.BranchId == loginTkn.branchId)
 .FirstOrDefaultAsync(d => d.Id == id);

Why doesn't RecyclerView have onItemClickListener()?

it worked for me. Hope it will help. Most simplest way.

Inside View Holder

class GeneralViewHolder extends RecyclerView.ViewHolder {
    View cachedView = null;

    public GeneralViewHolder(View itemView) {
        cachedView = itemView;

Inside OnBindViewHolder()

public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final GeneralViewHolder generalViewHolder = (GeneralViewHolder) holder;
            generalViewHolder.cachedView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Toast.makeText(context, "item Clicked at "+position, Toast.LENGTH_SHORT).show();

And let me know, do you have any question about this solution ?

Setting max width for body using Bootstrap

Unfortunately none of the above solved the problem for me.

I didn't want to edit the bootstrap-responsive.css so I went the easy way:

  1. Create a css with priority over bootstrap-responsive.css
  2. Copy all the content of the @media (min-width: 768px) and (max-width: 979px) (line 461 with latest bootstrap version 2.3.1 as of today)
  3. Paste it in your high priority css
  4. In your css, put @media (min-width: 979px) in the place where it said @media (min-width: 768px) and (max-width: 979px) before. This sets the from 768 to 979 style to everything above 768.

That's it. It's not optimal, you will have duplicated css, but it works 100% perfect!

Remove git mapping in Visual Studio 2015

Tools -> Options -> Source Control -> Current Source Control Plug-in: None

Getting mouse position in c#

   internal static class CursorPosition {
  public struct PointInter {
     public int X;
     public int Y;
     public static explicit operator Point(PointInter point) => new Point(point.X, point.Y);       

  public static extern bool GetCursorPos(out PointInter lpPoint);

  // For your convenience
  public static Point GetCursorPosition() {
     PointInter lpPoint;
     GetCursorPos(out lpPoint);
     return (Point) lpPoint;


How to get HttpClient to pass credentials along with the request?

What you are trying to do is get NTLM to forward the identity on to the next server, which it cannot do - it can only do impersonation which only gives you access to local resources. It won't let you cross a machine boundary. Kerberos authentication supports delegation (what you need) by using tickets, and the ticket can be forwarded on when all servers and applications in the chain are correctly configured and Kerberos is set up correctly on the domain. So, in short you need to switch from using NTLM to Kerberos.

For more on Windows Authentication options available to you and how they work start at:

Escape double quotes in Java

Escaping the double quotes with backslashes is the only way to do this in Java.

Some IDEs around such as IntelliJ IDEA do this escaping automatically when pasting such a String into a String literal (i.e. between the double quotes surrounding a java String literal)

One other option would be to put the String into some kind of text file that you would then read at runtime

Set background colour of cell to RGB value of data in cell

Setting the Color property alone will guarantee an exact match. Excel 2003 can only handle 56 colors at once. The good news is that you can assign any rgb value at all to those 56 slots (which are called ColorIndexs). When you set a cell's color using the Color property this causes Excel to use the nearest "ColorIndex". Example: Setting a cell to RGB 10,20,50 (or 3281930) will actually cause it to be set to color index 56 which is 51,51,51 (or 3355443).

If you want to be assured you got an exact match, you need to change a ColorIndex to the RGB value you want and then change the Cell's ColorIndex to said value. However you should be aware that by changing the value of a color index you change the color of all cells already using that color within the workbook. To give an example, Red is ColorIndex 3. So any cell you made Red you actually made ColorIndex 3. And if you redefine ColorIndex 3 to be say, purple, then your cell will indeed be made purple, but all other red cells in the workbook will also be changed to purple.

There are several strategies to deal with this. One way is to choose an index not yet in use, or just one that you think will not be likely to be used. Another way is to change the RGB value of the nearest ColorIndex so your change will be subtle. The code I have posted below takes this approach. Taking advantage of the knowledge that the nearest ColorIndex is assigned, it assigns the RGB value directly to the cell (thereby yielding the nearest color) and then assigns the RGB value to that index.

Sub Example()
    Dim lngColor As Long
    lngColor = RGB(10, 20, 50)
    With Range("A1").Interior
        .Color = lngColor
        ActiveWorkbook.Colors(.ColorIndex) = lngColor
    End With
End Sub

Make absolute positioned div expand parent div height

You answered the question by yourself: "I know that absolute positioned elements are removed from the flow, thus ignored by other elements." So you can't set the parents height according to an absolutely positioned element.

You either use fixed heights or you need to involve JS.

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

The res.header('Access-Control-Allow-Origin', '*'); wouldn't work with Autorization header. Just enable pre-flight request, using cors library:

var express = require('express')
var cors = require('cors')
var app = express()
app.options('*', cors())

keypress, ctrl+c (or some combo like that)

Try the Jquery Hotkeys plugin instead - it'll do everything you require.

jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination.

This plugin is based off of the plugin by Tzury Bar Yochay: jQuery.hotkeys

The syntax is as follows:

$(expression).bind(types, keys, handler); $(expression).unbind(types, handler);

$(document).bind('keydown', 'ctrl+a', fn);

// e.g. replace '$' sign with 'EUR'
// $('').bind('keyup', '$', function(){   
//      this.value = this.value.replace('$', 'EUR'); });

How to handle the new window in Selenium WebDriver using Java?

It seems like you are not actually switching to any new window. You are supposed get the window handle of your original window, save that, then get the window handle of the new window and switch to that. Once you are done with the new window you need to close it, then switch back to the original window handle. See my sample below:


String parentHandle = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[@id='someXpath']")).click(); // click some link that opens a new window

for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)

//code to do something on new window

driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window

How to convert list to string

By using ''.join

list1 = ['1', '2', '3']
str1 = ''.join(list1)

Or if the list is of integers, convert the elements before joining them.

list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)

Reload parent window from child window

this will work


"Submit is not a function" error in JavaScript

If you have no opportunity to change name="submit" you can also submit form this way:

function submitForm(form) {
    const submitFormFunction = Object.getPrototypeOf(form).submit;;

Ignore self-signed ssl cert using Jersey Client

For Jersey 2.*:

Client client = ClientBuilder.newBuilder()
                .hostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;


Trying to embed newline in a variable in bash

var="a b c"
for i in $var
   p=`echo -e "$p"'\n'$i`
echo "$p"

The solution was simply to protect the inserted newline with a "" during current iteration when variable substitution happens.

Check if all elements in a list are identical

For what it's worth, this came up on the python-ideas mailing list recently. It turns out that there is an itertools recipe for doing this already:1

def all_equal(iterable):
    "Returns True if all the elements are equal to each other"
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

Supposedly it performs very nicely and has a few nice properties.

  1. Short-circuits: It will stop consuming items from the iterable as soon as it finds the first non-equal item.
  2. Doesn't require items to be hashable.
  3. It is lazy and only requires O(1) additional memory to do the check.

1In other words, I can't take the credit for coming up with the solution -- nor can I take credit for even finding it.

Generate random integers between 0 and 9

The secrets module is new in Python 3.6. This is better than the random module for cryptography or security uses.

To randomly print an integer in the inclusive range 0-9:

from secrets import randbelow

For details, see PEP 506.

Simplest way to do grouped barplot

I wrote a function wrapper called bar() for barplot() to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do

bar(dv = Species, 
    factors = c(Category, Reason), 
    dataframe = Reasonstats, 
    errbar = FALSE, 
    ylim=c(0, 140))  #I increased the upper y-limit to accommodate the legend. 

The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE

enter image description here

MySQL convert date string to Unix timestamp

For current date just use UNIX_TIMESTAMP() in your MySQL query.

Understanding the Gemfile.lock file

Bundler is a Gem manager which provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed.

Gemfile and Gemfile.lock are primary products given by Bundler gem (Bundler itself is a gem).

Gemfile contains your project dependency on gem(s), that you manually mention with version(s) specified, but those gem(s) inturn depends on other gem(s) which is resolved by bundler automatically.

Gemfile.lock contain complete snapshot of all the gem(s) in Gemfile along with there associated dependency.

When you first call bundle install, it will create this Gemfile.lock and uses this file in all subsequent calls to bundle install, which ensures that you have all the dependencies installed and will skip dependency installation.

Same happens when you share your code with different machines

You share your Gemfile.lock along with Gemfile, when you run bundle install on other machine it will refer to your Gemfile.lock and skip dependency resolution step, instead it will install all of the same dependent gem(s) that you used on the original machine, which maintains consistency across multiple machines

Why do we need to maintain consistency along multiple machines ?

  • Running different versions on different machines could lead to broken code

  • Suppose, your app used the version 1.5.3 and it works 14 months ago
    without any problems, and you try to install on different machine
    without Gemfile.lock now you get the version 1.5.8. Maybe it's broken with the latest version of some gem(s) and your application will
    fail. Maintaining consistency is of utmost importance (preferred

It is also possible to update gem(s) in Gemfile.lock by using bundle update.

This is based on the concept of conservative updating

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())

         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         success: function (result) {
         async: true,
         processData: false

How to keep a git branch in sync with master

Whenever you want to get the changes from master into your work branch, do a git rebase <remote>/master. If there are any conflicts. resolve them.

When your work branch is ready, rebase again and then do git push <remote> HEAD:master. This will update the master branch on remote (central repo).

How to display UTF-8 characters in phpMyAdmin?

Easier solution for wamp is: go to phpMyAdmin, click localhost, select latin1_bin for Server connection collation, then start to create database and table

Merge two Excel tables Based on matching data in Columns

Put the table in the second image on Sheet2, columns D to F.

In Sheet1, cell D2 use the formula


copy across and down.

Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

enter image description here

How to browse for a file in java swing library?

In WebStart and the new 6u10 PlugIn you can use the FileOpenService, even without security permissions. For obvious reasons, you only get the file contents, not the file path.

How to stop a goroutine

Generally, you could create a channel and receive a stop signal in the goroutine.

There two way to create channel in this example.

  1. channel

  2. context. In the example I will demo context.WithCancel

The first demo, use channel:

package main

import "fmt"
import "time"

func do_stuff() int {
    return 1

func main() {

    ch := make(chan int, 100)
    done := make(chan struct{})
    go func() {
        for {
            select {
            case ch <- do_stuff():
            case <-done:
            time.Sleep(100 * time.Millisecond)

    go func() {
        time.Sleep(3 * time.Second)
        done <- struct{}{}

    for i := range ch {
        fmt.Println("receive value: ", i)


The second demo, use context:

package main

import (

func main() {
    forever := make(chan struct{})
    ctx, cancel := context.WithCancel(context.Background())

    go func(ctx context.Context) {
        for {
            select {
            case <-ctx.Done():  // if cancel() execute
                forever <- struct{}{}
                fmt.Println("for loop")

            time.Sleep(500 * time.Millisecond)

    go func() {
        time.Sleep(3 * time.Second)


Implicit function declarations in C

C is a very low-level language, so it permits you to create almost any legal object (.o) file that you can conceive of. You should think of C as basically dressed-up assembly language.

In particular, C does not require functions to be declared before they are used. If you call a function without declaring it, the use of the function becomes it's (implicit) declaration. In a simple test I just ran, this is only a warning in the case of built-in library functions like printf (at least in GCC), but for random functions, it will compile just fine.

Of course, when you try to link, and it can't find foo, then you will get an error.

In the case of library functions like printf, some compilers contain built-in declarations for them so they can do some basic type checking, so when the implicit declaration (from the use) doesn't match the built-in declaration, you'll get a warning.

Using GPU from a docker container?

Updated for cuda-8.0 on ubuntu 16.04


FROM ubuntu:16.04
MAINTAINER Jonathan Kosgei <[email protected]>

# A docker container with the Nvidia kernel module and CUDA drivers installed


RUN apt-get update && apt-get install -q -y \
  wget \
  module-init-tools \

RUN cd /opt && \
  wget $CUDA_RUN && \
  chmod +x cuda_8.0.44_linux-run && \
  mkdir nvidia_installers && \
  ./cuda_8.0.44_linux-run -extract=`pwd`/nvidia_installers && \
  cd nvidia_installers && \
  ./ -s -N --no-kernel-module

RUN cd /opt/nvidia_installers && \
  ./ -noprompt

# Ensure the CUDA libs and binaries are in the correct environment variables
ENV LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-8.0/lib64
ENV PATH=$PATH:/usr/local/cuda-8.0/bin

RUN cd /opt/nvidia_installers &&\
    ./ -noprompt -cudaprefix=/usr/local/cuda-8.0 &&\
    cd /usr/local/cuda/samples/1_Utilities/deviceQuery &&\ 

WORKDIR /usr/local/cuda/samples/1_Utilities/deviceQuery
  1. Run your container

sudo docker run -ti --device /dev/nvidia0:/dev/nvidia0 --device /dev/nvidiactl:/dev/nvidiactl --device /dev/nvidia-uvm:/dev/nvidia-uvm <built-image> ./deviceQuery

You should see output similar to:

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 8.0, CUDA Runtime Version = 8.0, NumDevs = 1, Device0 = GRID K520 Result = PASS

Visual Studio Community 2015 expiration date

Visual Studio Community 2015 is free. But I got the 30 day trial expired message. After some googling figured out that I have to sign in with a Microsoft account. So I signed up with my Hotmail account and after that I was able to continue using the VS community 2015.

How to set the style -webkit-transform dynamically using JavaScript?

Try using = "rotate(60deg)"

How do I print colored output to the terminal in Python?

Compared to the methods listed here, I prefer the method that comes with the system. Here, I provide a better method without third-party libraries.

class colors: # You may need to change color settings
    RED = '\033[31m'
    ENDC = '\033[m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'

print(colors.RED + "something you want to print in red color" + colors.ENDC)
print(colors.GREEN + "something you want to print in green color" + colors.ENDC)
print("something you want to print in system default color")

More color code , ref to : Printing Colored Text in Python

Enjoy yourself!

Send POST request using NSURLSession

Swift 2.0 solution is here:

 let urlStr = “http://url_to_manage_post_requests” 
 let url = NSURL(string: urlStr) 
 let request: NSMutableURLRequest =
 NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST"
 request.setValue(“application/json” forHTTPHeaderField:”Content-Type”)
 request.timeoutInterval = 60.0 
 //additional headers
 request.setValue(“deviceIDValue”, forHTTPHeaderField:”DeviceId”)

 let bodyStr = “string or data to add to body of request” 
 let bodyData = bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) 
 request.HTTPBody = bodyData

 let session = NSURLSession.sharedSession()

 let task = session.dataTaskWithRequest(request){
             (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

             if let httpResponse = response as? NSHTTPURLResponse {
                print("responseCode \(httpResponse.statusCode)")

            if error != nil {

                 // You can handle error response here
             }else {
                  //Converting response to collection formate (array or dictionary)
                     let jsonResult: AnyObject = (try NSJSONSerialization.JSONObjectWithData(data!, options:

                     //success code
                     //failure code


Two decimal places using printf( )

What you want is %.2f, not 2%f.

Also, you might want to replace your %d with a %f ;)

#include <cstdio>
int main()
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;

This will output:

When this number: 94.945600 is assigned to 2 dp, it will be: 94.95

See here for a full description of the printf formatting options: printf

using jquery $.ajax to call a PHP function

I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).

You basically send a JSON string in a specific format to the server, e.g.

{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}

which includes the function to call and the parameters of that function.

Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.

This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.

What is the difference between Document style and RPC style communication?

I think what you are asking is the difference between RPC Literal, Document Literal and Document Wrapped SOAP web services.

Note that Document web services are delineated into literal and wrapped as well and they are different - one of the primary difference is that the latter is BP 1.1 compliant and the former is not.

Also, in Document Literal the operation to be invoked is not specified in terms of its name whereas in Wrapped, it is. This, I think, is a significant difference in terms of easily figuring out the operation name that the request is for.

In terms of RPC literal versus Document Wrapped, the Document Wrapped request can be easily vetted / validated against the schema in the WSDL - one big advantage.

I would suggest using Document Wrapped as the web service type of choice due to its advantages.

SOAP on HTTP is the SOAP protocol bound to HTTP as the carrier. SOAP could be over SMTP or XXX as well. SOAP provides a way of interaction between entities (client and servers, for example) and both entities can marshal operation arguments / return values as per the semantics of the protocol.

If you were using XML over HTTP (and you can), it is simply understood to be XML payload on HTTP request / response. You would need to provide the framework to marshal / unmarshal, error handling and so on.

A detailed tutorial with examples of WSDL and code with emphasis on Java: SOAP and JAX-WS, RPC versus Document Web Services

Delete column from SQLite table

PRAGMA foreign_keys=off;


ALTER TABLE table1 RENAME TO _table1_old;

( column1 datatype [ NULL | NOT NULL ],
  column2 datatype [ NULL | NOT NULL ],

INSERT INTO table1 (column1, column2, ... column_n)
  SELECT column1, column2, ... column_n
  FROM _table1_old;


PRAGMA foreign_keys=on;

For more info:

When to use 'npm start' and when to use 'ng serve'?

npm start will run whatever you have defined for the start command of the scripts object in your package.json file.

So if it looks like this:

"scripts": {
  "start": "ng serve"

Then npm start will run ng serve.