Programs & Examples On #Search engine bots

CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

Border-radius is now officially supported. So, in all of the above examples you may drop the "-moz-" prefix.

Another trick is to use the same color for the top and bottom rows as is your border. With all 3 colors the same, it blends in and looks like a perfectly rounded table even though it isn't physically.

HTTP 1.0 vs 1.1

A key compatibility issue is support for persistent connections. I recently worked on a server that "supported" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.

Filtering Pandas DataFrames on dates

If you have already converted the string to a date format using pd.to_datetime you can just use:

df = df[(df['Date']> "2018-01-01") & (df['Date']< "2019-07-01")]

How to delete an SVN project from SVN repository

"Obliberating" contents from a svn repository, i.e. wiping this contents from the disc, can be done as described in this article

It requires access to the server side svn repository, thus you must have some admin privileges.

It works by (a) dumping the repository content into a file, (b) excluding some contents and (c) wiping and re-creating the plain repository again and eventually by (d) loading the filtered repository contents:

svnadmin dump "path/to/svnrepo" > svnrepo.txt                    // (a)
svndumpfilter exclude "my/folder" < svnrepo.txt > filtered.txt   // (b)
rm -rf "path/to/svnrepo" && svnadmin create "path/to/svnrepo"    // (c)
svnadmin load "path/to/svnrepo" < filtered.txt                   // (d)

The repository counter is unchanged by this operations. However, your repository is now "missing" all those revision numbers used to create that contents you removed in step (b).

Subversion 1.7.5 appears to handle this "missing" revisions pretty well. Using "svn ls -r $missing" for example, reports the very same as "svn ls -r $(( missing - 1))".

Contrary to this, my (pretty old) VIEWVC reports "no contents" when querying a "missing" revision.

Dead simple example of using Multiprocessing Queue, Pool and Locking

Here is my personal goto for this topic:

Gist here, (pull requests welcome!):

import multiprocessing
import sys


# Used to prevent multiple threads from mixing thier output
GLOBALLOCK = multiprocessing.Lock()

def func_worker(args):
    """This function will be called by each thread.
    This function can not be a class method.
    # Expand list of args into named args.
    str1, str2 = args
    del args

    # Work
    # ...

    # Serial-only Portion

def main(argp=None):
    """Multiprocessing Spawn Example
    # Create the number of threads you want
    pool = multiprocessing.Pool(THREADS)

    # Define two jobs, each with two args.
    func_args = [
        ('Hello', 'World',), 
        ('Goodbye', 'World',), 

        # Spawn up to 9999999 jobs, I think this is the maximum possible.
        # I do not know what happens if you exceed this.
        pool.map_async(func_worker, func_args).get(9999999)
    except KeyboardInterrupt:
        # Allow ^C to interrupt from any thread.
        sys.stdout.write('User Interupt\n')

if __name__ == '__main__':

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

One easy trick that can help with most deadlocks is sorting the operations in a specific order.

You get a deadlock when two transactions are trying to lock two locks at opposite orders, ie:

  • connection 1: locks key(1), locks key(2);
  • connection 2: locks key(2), locks key(1);

If both run at the same time, connection 1 will lock key(1), connection 2 will lock key(2) and each connection will wait for the other to release the key -> deadlock.

Now, if you changed your queries such that the connections would lock the keys at the same order, ie:

  • connection 1: locks key(1), locks key(2);
  • connection 2: locks key(1), locks key(2);

it will be impossible to get a deadlock.

So this is what I suggest:

  1. Make sure you have no other queries that lock access more than one key at a time except for the delete statement. if you do (and I suspect you do), order their WHERE in (k1,k2, in ascending order.

  2. Fix your delete statement to work in ascending order:


DELETE FROM onlineusers 
WHERE datetime <= now() - INTERVAL 900 SECOND


DELETE FROM onlineusers 
    SELECT id FROM onlineusers
    WHERE datetime <= now() - INTERVAL 900 SECOND 
    ORDER BY id
) u;

Another thing to keep in mind is that mysql documentation suggest that in case of a deadlock the client should retry automatically. you can add this logic to your client code. (Say, 3 retries on this particular error before giving up).

Iterate through dictionary values?

If all your values are unique, you can make a reverse dictionary:

PIXO_reverse = {v: k for k, v in PIX0.items()}


>>> PIXO_reverse

{'320x240': 'QVGA', '640x480': 'VGA', '800x600': 'SVGA'}

Now you can use the same logic as before.

If statements for Checkboxes

I'm making an assumption that you mean not checked. I don't have a C# compiler handy but:

if (checkbox1.Checked && !checkbox2.Checked)

else if (!checkbox1.Checked && checkbox2.Checked)


How do I get my solution in Visual Studio back online in TFS?

Neither of the above solutions worked for me on Visual Studio Community 2017 v15.7.1. Somehow, there was no "Go Online" option in the context menu. I tried registry edit as suggested here, but that only displayed me error that it could not find the binding. What worked for me is rebinding solution to the server from Change Source Control menu.

Go to File->Source Control->Advanced->Change Source Control and make sure that your solution is binded to your source control. If not (like mine) then click on bind button, it will automatically search online TFS server and rebind your solution to it.

MVC Calling a view from a different controller

To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.

public class CommentsController : Controller
    public ActionResult Index()
        return View("../Articles/Index", model );


public class ArticlesController : Controller
    public ActionResult Index()
        return View();

Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

Can you recommend a free light-weight MySQL GUI for Linux?

RazorSQL vote here too. It is not free, but it's not expensive ($70 for a perpetual license and 1 year of free upgrades).

If you use it for work, it will pay for itself quickly. I was jumping between MySQL GUI tools, SQL Server and Informix DBAccess, some of them through VMs because I use a Mac for development. Having a single tool to connect to any database out there is pretty nice. It is also highly customizable, and very reliable.

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

In my case, I use nginx as reverse-proxy for an API Gateway URL. I got same error.

I resolved the issue when I added the following two lines to the Nginx config:

proxy_set_header Host "";
proxy_ssl_server_name on;

Source is here: Setting up proxy_pass on nginx to make API calls to API Gateway

"Error: Main method not found in class MyClass, please define the main method as..."

I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a

java.lang.NoSuchMethodError: No virtual method

How can I determine if a variable is 'undefined' or 'null'?

var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
if (typeof y === "undefined") {
    alert ("not even declared.")

You can only use second one: as it will check for both definition and declaration

Get pixel's RGB using PIL

Yes, this way:

im ='image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))

print(r, g, b)
(65, 100, 137)

The reason you were getting a single value before with pix[1, 1] is because GIF pixels refer to one of the 256 values in the GIF color palette.

See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert() function.

By the way, your code would work just fine for .jpg images.

Can you display HTML5 <video> as a full screen background?

Just a comment on this - I've used HTML5 video for a full-screen background and it works a treat - but make sure to use either Height:100% and width:auto or the other way around - to ensure you keep aspect ratio.

As for Ipads -you can (apparently) do this, by having a hidden and then forcing the click event to fire, and having the function of the click event kick off the Load/Play().

P.s - this shouldn't require any plugins and can be done with minimal JS - If you're targeting any mobile device (I would assume you might be..) staying away from any such framework is the way forward.

PHP regular expressions: No ending delimiter '^' found in

Your regex pattern needs to be in delimiters:


HSL to RGB color conversion

Shortest but precise - JS

Use this JS code (more: rgb2hsl, hsv2rgb rgb2hsv and hsl2hsv) - php here

// input: h in [0,360] and s,v in [0,1] - output: r,g,b in [0,1]
function hsl2rgb(h,s,l) 
  let a=s*Math.min(l,1-l);
  let f= (n,k=(n+h/30)%12) => l - a*Math.max(Math.min(k-3,9-k,1),-1);                 
  return [f(0),f(8),f(4)];

// oneliner version
let hsl2rgb = (h,s,l, a=s*Math.min(l,1-l), f= (n,k=(n+h/30)%12) => l - a*Math.max(Math.min(k-3,9-k,1),-1)) => [f(0),f(8),f(4)];

// r,g,b are in [0-1], result e.g. #0812fa.
let rgb2hex = (r,g,b) => "#" + [r,g,b].map(x=>Math.round(x*255).toString(16).padStart(2,0) ).join('');

console.log(`hsl: (30,0.2,0.3) --> rgb: (${hsl2rgb(30,0.2,0.3)}) --> hex: ${rgb2hex(...hsl2rgb(30,0.2,0.3))}`);

// ---------------
// UX
// ---------------

rgb= [0,0,0];
hs= [0,0,0];

let $ = x => document.querySelector(x);

function changeRGB(i,e) {
  hs = rgb2hsl(...rgb);

function changeHS(i,e) {
  rgb= hsl2rgb(...hs);

function refresh() {
  rr =>x*255|0).join(', ')
  hh = rgb2hex(...rgb);
  tr = `RGB: ${rr}`
  th = `HSL: ${,i)=>i? (x*100).toFixed(2)+'%':x|0).join(', ')}`
  thh= `HEX: ${hh}`
  $('.infoHS').innerHTML =`${th}\n${thh}`;  

function rgb2hsl(r,g,b) {
  let a=Math.max(r,g,b), n=a-Math.min(r,g,b), f=(1-Math.abs(a+a-n-1)); 
  let h= n && ((a==r) ? (g-b)/n : ((a==g) ? 2+(b-r)/n : 4+(r-g)/n)); 
  return [60*(h<0?h+6:h), f ? n/f : 0, (a+a-n)/2];

.box {
  width: 50px;
  height: 50px;
  margin: 20px;

body {
    display: flex;
<input id="r" type="range" min="0" max="255" oninput="changeRGB(0,event)">R<br>
<input id="g" type="range" min="0" max="255" oninput="changeRGB(1,event)">G<br>
<input id="b" type="range" min="0" max="255" oninput="changeRGB(2,event)">B<br>
<pre class="infoRGB"></pre>

<div class="box hsl"></div>


<input id="h" type="range" min="0" max="360" oninput="changeHS(0,event)">H<br>
<input id="s" type="range" min="0" max="255" oninput="changeHS(1,event)">S<br>
<input id="l" type="range" min="0" max="255" oninput="changeHS(2,event)">L<br>
<pre class="infoHS"></pre><br>

Here is formula which I discover and precisely describe in wiki + error analysis,

enter image description here

How to fix missing dependency warning when using useEffect React Hook?

just disable eslint for the next line;

useEffect(() => {
// eslint-disable-next-line
}, []);

in this way you are using it just like a component did mount (called once)



const fetchBusinesses = useCallback(() => {
 // your logic in here
 }, [someDeps])

useEffect(() => {
// no need to skip eslint warning
}, [fetchBusinesses]); 

fetchBusinesses will be called everytime someDeps will change

Can I make a <button> not submit a form?

The button element has a default type of submit.

You can make it do nothing by setting a type of button:

<button type="button">Cancel changes</button>

Dynamically Add Images React Webpack

here is the code

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './image.css';
    import Dropdown from 'react-dropdown';
    import axios from 'axios';

    let obj = {};

    class App extends Component {
        this.state = {
          selectedFiles: []
        this.fileUploadHandler = this.fileUploadHandler.bind(this);

        let selectedFiles_ = this.state.selectedFiles;
        this.setState({selectedFiles: selectedFiles_});

      render() {
        let Images = => {
          <div className = "image_parent">

              <img src={require(image.src)}

        return (
            <div className="image-upload images_main">

            <input type="file" onClick={this.fileUploadHandler}/>


    export default App;

How to set the focus for a particular field in a Bootstrap modal, once it appears

I had the same problem with the bootstrap 3 and solved like this:

$('#myModal').on('', function (e) {


PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
    echo 'Less than';



 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
    echo 'Less than';


What is the difference between %g and %f in C?

As Unwind points out f and g provide different default outputs.

Roughly speaking if you care more about the details of what comes after the decimal point I would do with f and if you want to scale for large numbers go with g. From some dusty memories f is very nice with small values if your printing tables of numbers as everything stays lined up but something like g is needed if you stand a change of your numbers getting large and your layout matters. e is more useful when your numbers tend to be very small or very large but never near ten.

An alternative is to specify the output format so that you get the same number of characters representing your number every time.

Sorry for the woolly answer but it is a subjective out put thing that only gets hard answers if the number of characters generated is important or the precision of the represented value.

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Please note on iPad Safari, NoviceCoding's solution won't work if you have -webkit-overflow-scrolling: touch; somewhere in your CSS. The solution is either removing all the occurrences of -webkit-overflow-scrolling: touch; or putting -webkit-overflow-scrolling: auto; with NoviceCoding's solution.

How to get these two divs side-by-side?

User float:left property in child div class

check for div structure in detail :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

I added @Component annotation from import org.springframework.stereotype.Component and the problem was solved.

Subtract 1 day with PHP

How to add 1 year to a date and then subtract 1 day from it in c#


Laravel - Return json along with http status code

There are multiple ways

return \Response::json(['hello' => $value], STATUS_CODE);

return response()->json(['hello' => $value], STATUS_CODE);

where STATUS_CODE is your HTTP status code you want to send. Both are identical.

if you are using Eloquent model, then simple return will also be auto converted in JSON by default like,

return User::all();

Backup a single table with its data from a database in sql server 2008

You can use the "Generate script for database objects" feature on SSMS.

  1. Right click on the target database
  2. Select Tasks > Generate Scripts
  3. Choose desired table or specific object
  4. Hit the Advanced button
  5. Under General, choose value on the Types of data to script. You can select Data only, Schema only, and Schema and data. Schema and data includes both table creation and actual data on the generated script.
  6. Click Next until wizard is done

This one solved my challenge.
Hope this will help you as well.

How to parse JSON with VBA without external libraries?

Call me simple but I just declared a Variant and split the responsetext from my REST GET on the quote comma quote between each item, then got the value I wanted by looking for the last quote with InStrRev. I'm sure that's not as elegant as some of the other suggestions but it works for me.

         varLines = Split(.responsetext, """,""")
        strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)

How to avoid annoying error "declared and not used"

I ran into this issue when I wanted to temporarily disable the sending of an email while working on another part of the code.

Commenting the use of the service triggered a lot of cascade errors, so instead of commenting I used a condition

if false {
    // Technically, svc still be used so no yelling
    _, err = svc.SendRawEmail(input) 

How to Split Image Into Multiple Pieces in Python

Splitting image to tiles of MxN pixels (assuming im is numpy.ndarray):

tiles = [im[x:x+M,y:y+N] for x in range(0,im.shape[0],M) for y in range(0,im.shape[1],N)]

In the case you want to split the image to four pieces:

M = im.shape[0]//2
N = im.shape[1]//2

tiles[0] holds the upper left tile

How do I return an int from EditText? (Android)

For now, use an EditText. Use android:inputType="number" to force it to be numeric. Convert the resulting string into an integer (e.g., Integer.parseInt(myEditText.getText().toString())).

In the future, you might consider a NumberPicker widget, once that becomes available (slated to be in Honeycomb).

Get device information (such as product, model) from adb command

Why don't you try to grep the return of your command ? Something like :

adb devices -l | grep 123abc12

It should return only the line you want to.

Call a stored procedure with parameter in c#

You have to add parameters since it is needed for the SP to execute

using (SqlConnection con = new SqlConnection(dc.Con))
    using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@FirstName", txtfirstname.Text);
        cmd.Parameters.AddWithValue("@LastName", txtlastname.Text);

How do I find the date a video (.AVI .MP4) was actually recorded?

There doesn't seem to be a well defined standard for video metadata (compared to photos and audio files, which have EXIF and ID3/etc. respectively)

Some tags exists like e.g. Title, Composer etc. You can see those if you select a movie file in Windows 7 (perhaps earlier versions also) explorer or right click and view properties. I have not found a tag for recording date unfortunately - the closest thing available is Year (integer) :-(

Programatically, you can read and write most of these tags in .NET using Taglib Sharp from the mono project. Source and binaries are available on the banshee FTP server. It has a pretty impressive list of formats it supports (but still, make sure you catch exceptions when trying to read or write tags - it will throw whenever it finds a file it cannot understand, something which happened to me several times for my modest collection of home recordings.)

To read tags:

using (var f = TagLib.File.Create(@"c:\Path\To\MyVideo.mp4"))
    if (f.Tag != null)
        string title = f.Tag.Title;
        Size resolution = new Size(f.Properties.VideoWidth, f.Properties.VideoHeight);
        int year = f.Tag.Year;
        // etc.

And similarly, to write metadata back to the file:

using (var f = TagLib.File.Create(@"c:\Path\To\MyVideo.mp4"))
    f.Tag.Title = "My Awesome Movie";
    f.Tag.Year = (uint)2011;

first-child and last-child with IE8

If you want to carry on using CSS3 selectors but need to support older browsers I would suggest using a polyfill such as Selectivizr.js

Android Saving created bitmap to directory on sd card

You can also try this.

File file = new File(strDirectoy,imgname);
OutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

The SUBTOTAL function can be used if you want to get the count respecting any filters you use on the page.

=SUBTOTAL(103, A1:A200)

will help you get count of non-empty rows, respecting filters.

103 - is similar to COUNTA, but ignores empty rows and also respects filters.

Reference : SUBTOTAL function

How can I find out if I have Xcode commandline tools installed?

if you want to know the install version of Xcode as well as Swift language current version:

Use below simple command by using Terminal:

1. To get install Xcode Version

 xcodebuild -version

2. To get install Swift language Version

swift --version

Executing another application from Java

You can execute a batch instruction, or any other application using

  • cmd is the command or te application path.

Also yo can wait for executing and getting the return code (to check if its executed correctly) with this code:

  Process p = Runtime.getRuntime().exec(cmd);
  int exitVal = p.exitValue();

You have a full explanation of different types of calls here

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

First Heroku deploy failed `error code=H10`

In my own case, i got this error because i refuse to add a Procfile to my node js app and my "main": "app.js" was initially pointing to another js file as main. so doing these chnages get it fixed for me

how to print json data in console.log

{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}

console.dir() will do what you need. It will give you a hierarchical structure of the data.


like so

> Object
  > input_data: Object
      price-row_122: " 35.1 "
      quantity-row_122: "1"
    success: true

I don't think you need console.log(JSON.stringify(data)).

To get the data you can do this without stringify:

console.log(data.success); // true
console.log(data.input_data['quantity-row_122']) // "1"
console.log(data.input_data['price-row_122']) // " 35.1 "


The value from input_data Object will be typeof "1": String, but you can convert to number(Int or Float) using ParseInt or ParseFloat, like so:

 typeof parseFloat(data.input_data['price-row_122'], 10) // "number"
 parseFloat(data.input_data['price-row_122'], 10) // 35.1

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

How to append strings using sprintf?

For safety (buffer overflow) I recommend to use snprintf()

const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);

int length = 0;
length += snprintf(Buffer+length, MAX_BUF-length, "Hello World");
length += snprintf(Buffer+length, MAX_BUF-length, "Good Morning");
length += snprintf(Buffer+length, MAX_BUF-length, "Good Afternoon");

How do I create a file and write to it?


try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
    writer.write("text to write");
catch (IOException ex) {
    // Handle me

Using try() will close stream automatically. This version is short, fast (buffered) and enables choosing encoding.

This feature was introduced in Java 7.

Listing files in a specific "folder" of a AWS S3 bucket

As other have already said, everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.

If you don't need objects which end with a '/' you can safely delete them e.g. via REST api or AWS Java SDK (I assume you have write access). You will not lose "nested files" (there no files, so you will not lose objects whose names are prefixed with the key you delete)

AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(new ProfileCredentialsProvider()).withRegion("region").build();
amazonS3.deleteObject(new DeleteObjectRequest("my-bucket", "users/<user-id>/contacts/<contact-id>/"));

Please note that I'm using ProfileCredentialsProvider so that my requests are not anonymous. Otherwise, you will not be able to delete an object. I have my AWS keep key stored in ~/.aws/credentials file.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Error message: “No toolchains found in the NDK toolchains folder for ABI with prefix: llvm” .

After fresh web installation of Android Studio with NDK, I imported an Android code sample that used NDK from GitHub and tried to compile it.

As a result had an Error:

No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Solution: for some reasons standard installation process on macOS had failed to install a complete set:

~/Library/Android/sdk/ndk-bundle had missed folder toolchains with all tools,

(it should be like this: ~/Library/Android/sdk/ndk-bundle/toolchains)

The solution was to download NDK separately, open it, copy folder toolchain and paste it to the folder:


After that it worked well for me.

Named tuple and default values for optional keyword arguments

A slightly extended example to initialize all missing arguments with None:

from collections import namedtuple

class Node(namedtuple('Node', ['value', 'left', 'right'])):
    __slots__ = ()
    def __new__(cls, *args, **kwargs):
        # initialize missing kwargs with None
        all_kwargs = {key: kwargs.get(key) for key in cls._fields}
        return super(Node, cls).__new__(cls, *args, **all_kwargs)

What is the difference between precision and scale?

If value is 9999.988 and Precision 4, scale 2 then it means 9999(it represents precision).99(scale is 2 so .988 is rounded to .99)

If value is 9999.9887 and precision is 4, scale is 2 then it means 9999.99

In PowerShell, how can I test if a variable holds a numeric value?

PS> Add-Type -Assembly Microsoft.VisualBasic
PS> [Microsoft.VisualBasic.Information]::IsNumeric(1.5)

Converting an int to std::string

You can use this function to convert int to std::string after including <sstream>:

#include <sstream>

string IntToString (int a)
    stringstream temp;
    return temp.str();

How to create a floating action button (FAB) in android, using AppCompat v21?

Here is one aditional free Floating Action Button library for Android It has many customizations and requires SDK version 9 and higher

enter image description here

Full Demo Video

Determine the process pid listening on a certain port

Short version which you can pass to kill command:

lsof -i:80 -t

Volatile boolean vs AtomicBoolean

Remember the IDIOM -

READ - MODIFY- WRITE this you can't achieve with volatile

What is the difference between "mvn deploy" to a local repo and "mvn install"?

From the Maven docs, sounds like it's just a difference in which repository you install the package into:

  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Maybe there is some confusion in that "install" to the CI server installs it to it's local repository, which then you as a user are sharing?

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

Check if you do not have declared the method getAll() in the model. That causes the controller to think that you are calling a non-static method.

Use ffmpeg to add text subtitles

ffmpeg supports the mov_text subtitle encoder which is about the only one supported in an MP4 container and playable by iTunes, Quicktime, iOS etc.

Your line would read:

ffmpeg -i input.mp4 -i -map 0:0 -map 0:1 -map 1:0 -c:s mov_text output.mp4

Android SQLite Example

Using Helper class you can access SQLite Database and can perform the various operations on it by overriding the onCreate() and onUpgrade() methods.

Make Frequency Histogram for Factor Variables

It seems like you want barplot(prop.table(table(animals))):

enter image description here

However, this is not a histogram.

Strip / trim all strings of a dataframe

You can use the apply function of the Series object:

>>> df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])
>>> df[0][0]
'  a  '
>>> df[0] = df[0].apply(lambda x: x.strip())
>>> df[0][0]

Note the usage of strip and not the regex which is much faster

Another option - use the apply function of the DataFrame object:

>>> df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])
>>> df.apply(lambda x: x.apply(lambda y: y.strip() if type(y) == type('') else y), axis=0)

   0   1
0  a  10
1  c   5

Git: How to remove proxy

Check if you have environment variable that could still define a proxy (picked up by curl, even if the git config does not include any proxy setting anymore):


Inserting created_at data with Laravel

In your User model, add the following line in the User class:

public $timestamps = true;

Now, whenever you save or update a user, Laravel will automatically update the created_at and updated_at fields.

If you want to set the created at manually you should use the date format Y-m-d H:i:s. The problem is that the format you have used is not the same as Laravel uses for the created_at field.

Update: Nov 2018 Laravel 5.6 "message": "Access level to App\\Note::$timestamps must be public", Make sure you have the proper access level as well. Laravel 5.6 is public.

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "" }
  maven { url "" }


You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "" }
  maven { url "" }

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'


Is there any way to redraw tmux window when switching smaller monitor to bigger one?

ps ax | grep tmux
17685 pts/22   S+     0:00 tmux a -t 13g2
17920 pts/11   S+     0:00 tmux a -t 13g2
18065 pts/19   S+     0:00 grep tmux

kill the other one.

Test if string is a number in Ruby on Rails

no you're just using it wrong. your is_number? has an argument. you called it without the argument

you should be doing is_number?(mystring)

Math.random() versus Random.nextInt(int)

According to this example Random.nextInt(n) has less predictable output then Math.random() * n. According to [sorted array faster than an unsorted array][1] I think we can say Random.nextInt(n) is hard to predict.

usingRandomClass : time:328 milesecond.

usingMathsRandom : time:187 milesecond.

package javaFuction;
import java.util.Random;
public class RandomFuction 
    static int array[] = new int[9999];
    static long sum = 0;
    public static void usingMathsRandom() {
        for (int i = 0; i < 9999; i++) {
         array[i] = (int) (Math.random() * 256);

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];

    public static void usingRandomClass() {
        Random random = new Random();
        for (int i = 0; i < 9999; i++) {
            array[i] = random.nextInt(256);

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];



    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        long end = System.currentTimeMillis();
        System.out.println("usingRandomClass " + (end - start));
        start = System.currentTimeMillis();
        end = System.currentTimeMillis();
        System.out.println("usingMathsRandom " + (end - start));



How do I change the UUID of a virtual disk?

If you've copied a disk (vmdk file) from one machine to another and need to change a disk's UUID in the copy, you don't need to change the Machine UUID as has been suggested by another answer.

All you need to do is to assign a new UUID to the disk image:

VBoxManage internalcommands sethduuid your-box-disk2.vmdk
UUID changed to: 5d34479f-5597-4b78-a1fa-94e200d16bbb

and then replace the old UUID with the newly generated one in two places in your *.vbox file

    <HardDisk uuid="{5d34479f-5597-4b78-a1fa-94e200d16bbb}" location="box-disk2.vmdk" format="VMDK" type="Normal"/>

and in

    <AttachedDevice type="HardDisk" hotpluggable="false" port="0" device="0">
      <Image uuid="{5d34479f-5597-4b78-a1fa-94e200d16bbb}"/>

It worked for me for VirtualBox ver. 5.1.8 running on Mac OS X El Capitan.

Shell Script — Get all files modified after <date>

This script will find files having a modification date of two minutes before and after the given date (and you can change the values in the conditions as per your requirement)


TODAY=$(date  -d "$(date +%F)" +%s)
TODAY_TIME=$(date -d "$(date +%T)" +%s)

for f in `ls`;
#       echo "File -> $f"
        MOD_DATE=$(stat -c %y "$f")
        MOD_DATE=${MOD_DATE% *}
#       echo MOD_DATE: $MOD_DATE
        MOD_DATE1=$(date -d "$MOD_DATE" +%s)
#       echo MOD_DATE: $MOD_DATE

if [[ ($DIFF_IN_DATE -ge -120) && ($DIFF_IN_DATE1 -le 120) && (DIFF_IN_DATE1 -ge -120) ]]
echo File lies in Next Hour = $f

#mv $PATH_SRC/$f  $PATH_DST/$f

For example you want files having modification date before the given date only, you may change 120 to 0 in $DIFF_IN_DATE parameter discarding the conditions of $DIFF_IN_DATE1 parameter.

Similarly if you want files having modification date 1 hour before and after given date, just replace 120 by 3600 in if CONDITION.

React Checkbox not sending onChange

To get the checked state of your checkbox the path would be:


The alternative is to get it from the event passed into the handleChange method:

What is the difference between 'java', 'javaw', and 'javaws'?

java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.

Write bytes to file

The simplest way would be to convert your hexadecimal string to a byte array and use the File.WriteAllBytes method.

Using the StringToByteArray() method from this question, you'd do something like this:

string hexString = "0CFE9E69271557822FE715A8B3E564BE";

File.WriteAllBytes("output.dat", StringToByteArray(hexString));

The StringToByteArray method is included below:

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))

How can I get the day of a specific date with PHP

$date = '2014-02-25';
date('D', strtotime($date));

In AngularJS, what's the difference between ng-pristine and ng-dirty?

pristine tells us if a field is still virgin, and dirty tells us if the user has already typed anything in the related field:

<script src=""></script>_x000D_
<form ng-app="" name="myForm">_x000D_
  <input name="email" ng-model="">_x000D_
  <div class="info" ng-show="$pristine">_x000D_
    Email is virgine._x000D_
  <div class="error" ng-show="$dirty">_x000D_
    E-mail is dirty_x000D_

A field that has registred a single keydown event is no more virgin (no more pristine) and is therefore dirty for ever.

Initializing default values in a struct

You can do it by using a constructor, like this:

struct Date
int day;
int month;
int year;


or like this:

struct Date
int day;
int month;
int year;


In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).

Android TextView Text not getting wrapped

I just removed android:lines="1" and added android:maxLines="2", this got the text to wrap automatically. The problem was the android:lines attribute. That causes the text wrapping to not happen.

I didnt have to use maxEms or singleLine="false" (deprecated API) to fix this.

Interfaces vs. abstract classes

The real question is: whether to use interfaces or base classes. This has been covered before.

In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.

What's the difference between an argument and a parameter?

Parameter is variable in the declaration of function.

Argument is the actual value of this variable that gets passed to function. enter image description here

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

I have some additions to above mentioned answers Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to

private SSLSocketFactory delegate;

This is my TLSSocketFactory class

public class TLSSocketFactory extends SSLSocketFactory {

private SSLSocketFactory delegate;

public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    delegate = context.getSocketFactory();

public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();

public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();

public Socket createSocket() throws IOException {
    return enableTLSOnSocket(delegate.createSocket());

public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port));

public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));

public Socket createSocket(InetAddress host, int port) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(host, port));

public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));

private Socket enableTLSOnSocket(Socket socket) {
    if(socket != null && (socket instanceof SSLSocket)) {
        ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
    return socket;

and this is how i used it with okhttp and retrofit

 OkHttpClient client=new OkHttpClient();
    try {
        client = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory())
    } catch (KeyManagementException e) {
    } catch (NoSuchAlgorithmException e) {

    Retrofit retrofit = new Retrofit.Builder()

sql query to return differences between two tables

There is a performance issue related with the left join as well as full join with large data.

In my opinion this is the best solution:

select [First Name], count(1) e from (select * from [Temp Test Data] union all select * from [Temp Test Data 2]) a group by [First Name] having e = 1

How do I use Maven through a proxy?

The above postings helped in resolving my problem. In addition to the above I had to make the following changes to make it work :

  • Modified Maven's JRE net settings(\jre\lib\ to use system proxy setting.

    https.proxyHost=proxy DNS
    https.proxyPort=proxy port
  • Included proxy server settings in settings.xml. I did not provide username and password settings as to use NTLM authentication.

Node.js version on the command line? (not the REPL)

Try nodejs instead of just node

$ nodejs -v

SFTP in Python? (platform independent)

Here is a sample using pysftp and a private key.

import pysftp

def upload_file(file_path):

    private_key = "~/.ssh/your-key.pem"  # can use password keyword in Connection instead
    srv = pysftp.Connection(host="your-host", username="user-name", private_key=private_key)
    srv.chdir('/var/web/public_files/media/uploads')  # change directory on remote server
    srv.put(file_path)  # To download a file, replace put with get
    srv.close()  # Close connection

pysftp is an easy to use sftp module that utilizes paramiko and pycrypto. It provides a simple interface to sftp.. Other things that you can do with pysftp which are quite useful:

data = srv.listdir()  # Get the directory and file listing in a list
srv.get(file_path)  # Download a file from remote server
srv.execute('pwd') # Execute a command on the server

More commands and about PySFTP here.

What is the difference between typeof and instanceof and when should one be used vs. the other?

Despite instanceof may be a little bit faster then typeof, I prefer second one because of such a possible magic:

function Class() {};
Class.prototype = Function;

var funcWannaBe = new Class;

console.log(funcWannaBe instanceof Function); //true
console.log(typeof funcWannaBe === "function"); //false
funcWannaBe(); //Uncaught TypeError: funcWannaBe is not a function

"NoClassDefFoundError: Could not initialize class" error

I had faced the same issue, because the jar library was copied by other Linux user(root), and the logged in user(process) did not have sufficient privilege to read the jar file content.

What is the best way to trigger onchange event in react js

You can simulate events using ReactTestUtils but that's designed for unit testing.

I'd recommend not using valueLink for this case and simply listening to change events fired by the plugin and updating the input's state in response. The two-way binding utils more as a demo than anything else; they're included in addons only to emphasize the fact that pure two-way binding isn't appropriate for most applications and that you usually need more application logic to describe the interactions in your app.

How do I specify a password to 'psql' non-interactively?

This can be done by creating a .pgpass file in the home directory of the (Linux) User. .pgpass file format:


You can also use wild card * in place of details.

Say I wanted to run tmp.sql without prompting for a password.

With the following code you can in *.sh file

echo "*:*:postgres:postgrespwd" > $HOME/.pgpass
echo "` chmod 0600 $HOME/.pgpass `"

echo " ` psql -h -p 5432  -U postgres  postgres  -f tmp.sql `        

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

If, like me, you prefer to deal with strongly typed objects** go with:

MyObj obj =  JsonConvert.DeserializeObject<MyObj>(jsonString);

This way you get to use intellisense and compile time type error checking.

You can easily create the required objects by copying your JSON into memory and pasting it as JSON objects (Visual Studio -> Edit -> Paste Special -> Paste JSON as Classes).

See here if you don't have that option in Visual Studio.

You will also need to make sure your JSON is valid. Add your own object at the start if it is just an array of objects. i.e. {"obj":[{},{},{}]}

** I know that dynamic makes things easier sometimes but I'm a bit ol'skool with this.


Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

The transaction manager has disabled its support for remote/network transactions

I had a store procedure that call another store Procedure in "linked server".when I execute it in ssms it was ok,but when I call it in application(By Entity Framework),I got this error. This article helped me and I used this script:

EXEC sp_serveroption @server = 'LinkedServer IP or Name',@optname = 'remote proc transaction promotion', @optvalue = 'false' ;

for more detail look at this: Linked server : The partner transaction manager has disabled its support for remote/network transactions

pass JSON to HTTP POST Request

you can pass the json object as the body(third argument) of the fetch request.

Newline in string attribute

I realize this is on older question but just wanted to add that


also works if doing this through code.

How to set a ripple effect on textview or imageview on Android?

Using libraries. This is one of them. Just add its dependency and put below code in xml before each elements that needs ripple effect:


MySQL - count total number of rows in php

mysqli_num_rows is used in php 5 and above.


// Check connection
if (mysqli_connect_errno())
  echo "Failed to connect to MySQL: " . mysqli_connect_error();

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  // Return the number of rows in result set
  printf("Result set has %d rows.\n",$rowcount);
  // Free result set

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day =


getDate with Jquery Datepicker

I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on jsFiddle

    // Datepicker
        dateFormat: 'yy-mm-dd',
        inline: true,
        minDate: new Date(2010, 1 - 1, 1),
        maxDate:new Date(2010, 12 - 1, 31),
        altField: '#datepicker_value',
        onSelect: function(){
            var day1 = $("#datepicker").datepicker('getDate').getDate();                 
            var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;             
            var year1 = $("#datepicker").datepicker('getDate').getFullYear();
            var fullDate = year1 + "-" + month1 + "-" + day1;
            var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";

Putting -moz-available and -webkit-fill-available in one width (css property)

CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit-prefixed declarations, and WebKit-based browsers will not understand -moz-prefixed declarations.

Because of this, we can simply declare width twice:

elem {
    width: 100%;
    width: -moz-available;          /* WebKit-based browsers will ignore this. */
    width: -webkit-fill-available;  /* Mozilla-based browsers will ignore this. */
    width: fill-available;

The width: 100% declared at the start will be used by browsers which ignore both the -moz and -webkit-prefixed declarations or do not support -moz-available or -webkit-fill-available.

Check element CSS display with JavaScript

To find out if it's visible with plain JavaScript, check whether the display property is 'none' (don't check for 'block', it could also be blank or 'inline' and still be visible):

var isVisible = ( != "none");

If you are using jQuery, you can use this instead:

var isVisible = $":visible");

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

Try this:

Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Range("A2:L" & Lastrow).Select

Let's pretend that the value of Lastrow is 50. When you use the following:

Range("A2:L2" & Lastrow).Select

Then it is selecting a range from A2 to L250.

Python object.__repr__(self) should be an expression?

>>> from datetime import date
>>> repr(        # calls
', 1, 16)'
>>> eval(_)                   # _ is the output of the last command, 1, 16)

The output is a string that can be parsed by the python interpreter and results in an equal object.

If that's not possible, it should return a string in the form of <...some useful description...>.

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)


On windows forms it is available, at the top of the class put

  static void Main(string[] args)
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
       //other stuff here

since windows is single threaded, its all you need, in the event its a service you need to put it right above the call to the service (since there is no telling what thread you'll be on).

using System.Security.Principal 

is also needed.

Using Font Awesome icon for bullet points, with a single list item element

@Tama, you may want to check this answer: Using Font Awesome icons as bullets

Basically you can accomplish this by using only CSS without the need for the extra markup as suggested by FontAwesome and the other answers here.

In other words, you can accomplish what you need using the same basic markup you mentioned in your initial post:



How to get HttpContext.Current in ASP.NET Core?

YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:

In public class Startup

add a property

public IConfigurationRoot Configuration { get; }

And then add a singleton IHttpContextAccessor to DI in ConfigureServices.

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

Then in Configure

    public void Configure(
              IApplicationBuilder app
             ,IHostingEnvironment env
             ,ILoggerFactory loggerFactory

add the DI Parameter IServiceProvider svp, so the method looks like:

    public void Configure(
           IApplicationBuilder app
          ,IHostingEnvironment env
          ,ILoggerFactory loggerFactory
          ,IServiceProvider svp)

Next, create a replacement class for System.Web:

namespace System.Web

    namespace Hosting
        public static class HostingEnvironment 
            public static bool m_IsHosted;

            static HostingEnvironment()
                m_IsHosted = false;

            public static bool IsHosted
                    return m_IsHosted;

    public static class HttpContext
        public static IServiceProvider ServiceProvider;

        static HttpContext()
        { }

        public static Microsoft.AspNetCore.Http.HttpContext Current
                // var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
                object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

                // Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
                Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
                // context.Response.WriteAsync("Test");

                return context;

    } // End Class HttpContext 


Now in Configure, where you added the IServiceProvider svp, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)

and set HostingEnvironment.IsHosted to true

System.Web.Hosting.HostingEnvironment.m_IsHosted = true;

this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)

    ServiceProvider = svp;
    System.Web.HttpContext.ServiceProvider = svp;
    System.Web.Hosting.HostingEnvironment.m_IsHosted = true;

    app.UseCookieAuthentication(new CookieAuthenticationOptions()
        AuthenticationScheme = "MyCookieMiddlewareInstance",
        LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
        AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest

       , CookieHttpOnly=false


Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start in global.asax.

I stress again, this only works if you actually added

services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at, and do some testing.

Perhaps a more maintainable method would be adding this helper class

namespace System.Web

    public static class HttpContext
        private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;

        public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
            m_httpContextAccessor = httpContextAccessor;

        public static Microsoft.AspNetCore.Http.HttpContext Current
                return m_httpContextAccessor.HttpContext;



And then calling HttpContext.Configure in Startup->Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)


Difference between and logger.debug

I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.

The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception, you might call Logger.error. If you want to print the value of a variable at any given point, you might call Logger.debug. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.

In the case of log4j at least, the ordering of log levels is:


Here is a short example from that article demonstrating how log levels work.

   // get a logger instance named ""
   Logger logger = Logger.getLogger("");

   // Now set its level. Normally you do not need to set the
   // level of a logger programmatically. This is usually done
   // in configuration files.

   Logger barlogger = Logger.getLogger("");

   // This request is enabled, because WARN >= INFO.
   logger.warn("Low fuel level.");

   // This request is disabled, because DEBUG < INFO.
   logger.debug("Starting search for nearest gas station.");

   // The logger instance barlogger, named "",
   // will inherit its level from the logger named
   // "" Thus, the following request is enabled
   // because INFO >= INFO."Located nearest gas station.");

   // This request is disabled, because DEBUG < INFO.
   barlogger.debug("Exiting gas station search");

How to add text to an existing div with jquery

Your html is invalid button is not a null tag. Try

<div id="Content">
   <button id="Add">Add</button>

git is not installed or not in the PATH

while @vitocorleone is technically correct. If you have already installed, there is no need to reinstall. You just need to add it to your path. You will find yourself doing this for many of the tools for the mean stack so you should get used to doing it. You don't want to have to be in the folder that holds the executable to run it.

  • Control Panel --> System and Security --> System
  • click on Advanced System Settings on the left.
  • make sure you are on the advanced tab
  • click the Environment Variables button on the bottom
  • under system variables on the bottom find the Path variable
  • at the end of the line type (assuming this is where you installed it)

    ;C:\Program Files (x86)\git\cmd

  • click ok, ok, and ok to save

This essentially tells the OS.. if you don't find this executable in the folder I am typing in, look in Path to fide where it is.

SimpleDateFormat parse loses timezone

All I needed was this :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

try {
    String d = sdf.format(new Date());
} catch (Exception e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

Output : slightly dubious, but I want only the date to be consistent

2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013

Left/Right float button inside div

Change display:inline to display:inline-block

.test {
  overflow: auto;
  white-space: nowrap;
  margin:0px auto;
  border:1px red solid;

How to Select Min and Max date values in Linq Query

This should work for you

//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();

//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max(); 

(From here)

How can I do string interpolation in JavaScript?

You could use Prototype's template system if you really feel like using a sledgehammer to crack a nut:

var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));

What are the uses of "using" in C#?

Since a lot of people still do:

using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {

I guess a lot of people still don't know that you can do:

using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {

Execute a shell function with timeout

This function uses only builtins

  • Maybe consider evaling "$*" instead of running $@ directly depending on your needs

  • It starts a job with the command string specified after the first arg that is the timeout value and monitors the job pid

  • It checks every 1 seconds, bash supports timeouts down to 0.01 so that can be tweaked

  • Also if your script needs stdin, read should rely on a dedicated fd (exec {tofd}<> <(:))

  • Also you might want to tweak the kill signal (the one inside the loop) which is default to -15, you might want -9

## forking is evil
timeout() {
    to=$1; shift
    $@ & local wp=$! start=0
     while kill -0 $wp; do
        read -t 1
        if [ $start -ge $to ]; then
            kill $wp && break

What is the default username and password in Tomcat?

For Window 7, Netbeans 8.0.2 , Apache Tomcat 8.0.15
The Tomcat Manager Username and password is like below pic..


Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

7-zip commandline

try this one. it worked for me. 7z.exe a d:\newFileName.7z "d:\ExistingFile.txt"

open cmd and if you have installed 7zip app then try this. on command prompt it will like c:\programs and files\7zip\7z.exe a d:\newFileName.7z "d:\ExistingFile.txt"

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

 * HTTP request types
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

 * HTTP request header constants
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));

    //.... code omitted ....//


How does DateTime.Now.Ticks exactly work?

Not really an answer to your question as asked, but thought I'd chip in about your general objective.

There already is a method to generate random file names in .NET.

See System.Path.GetTempFileName and GetRandomFileName.

Alternatively, it is a common practice to use a GUID to name random files.

How can I upload fresh code at github?

git init
git add .
git commit -m "Initial commit"

After this, make a new GitHub repository and follow on-screen instructions.

C#: what is the easiest way to subtract time?

This works too:

System.DateTime dTime = DateTime.Now();

// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0); 

System.DateTime result = dTime + tSpan;

To subtract a year:

DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

There is also

which aims

  • To encode entire script in a proprietary PHP application
  • To encode some classes and/or functions in a proprietary PHP application
  • To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
  • To do the feasibility study for a PHP to C converter

The extension is available from PECL.

How to disable a link using only CSS?

It's possible to do it in CSS

<a href="" target="_blank" class="disabled">Google</a>

See at:

Please note that the text-decoration: none; and color: black; is not needed but it makes the link look more like plain text.

Why has it failed to load main-class manifest attribute from a JAR file?

I'm not sure I believe your symptoms:

  • If the jre command isn't found, then running jre -cp app.jar should give the same error
  • Just adding a JAR file to the classpath shouldn't give the error you're seeing

I'd expect you to see this error if you run:

java -jar app.jar

The Main-Class header needs to be in the manifest for the JAR file - this is metadata about things like other required libraries. See the Sun documentation for how to create an appropriate manifest. Basically you need to create a text file which includes a line like this:

Main-Class: MainClass

Then run

jar cfm app.jar manifest.txt *.class

How do I get total physical memory size using PowerShell without WMI?

Let's not over complicate things...:

(Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).sum /1gb

How to add label in chart.js for pie chart

It is not necessary to use another library like newChart or use other people's pull requests to pull this off. All you have to do is define an options object and add the label wherever and however you want it in the tooltip.

var optionsPie = {
    tooltipTemplate: "<%= label %> - <%= value %>"

If you want the tooltip to be always shown you can make some other edits to the options:

 var optionsPie = {
        tooltipEvents: [],
        showTooltips: true,
        onAnimationComplete: function() {
            this.showTooltip(this.segments, true);
        tooltipTemplate: "<%= label %> - <%= value %>"

In your data items, you have to add the desired label property and value and that's all.

data = [
        value: 480000,
        highlight: "#FF5A5E",
        label: "Tobacco"

Now, all you have to do is pass the options object after the data to the new Pie like this: new Chart(ctx).Pie(data,optionsPie) and you are done.

This probably works best for pies which are not very small in size.

Pie chart with labels

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

How can I stage and commit all files, including newly added files, using a single command?

You can write a small script (look at Ian Clelland's answer) called git-commitall which uses several git commands to perform what you want to do.
Place this script in your anywhere in your $PATH. You can call it by git commitall ... very handy!

Found here (question and all answers unfortunately deleted, only visible with high reputation)

Download a file by jQuery.Ajax

That's it works so fine in any browser (I'm using core)

            function onDownload() {_x000D_
  const api = '@Url.Action("myaction", "mycontroller")'; _x000D_
  var form = new FormData(document.getElementById('form1'));_x000D_
  fetch(api, { body: form, method: "POST"})_x000D_
      .then(resp => resp.blob())_x000D_
      .then(blob => {_x000D_
          const url = window.URL.createObjectURL(blob);_x000D_
        $('#linkdownload').attr('download', '');_x000D_
          $('#linkdownload').attr("href", url);_x000D_
                  function() { });_x000D_
      .catch(() => alert('An error occurred'));_x000D_
 <button type="button" onclick="onDownload()" class="btn btn-primary btn-sm">Click to Process Files</button>_x000D_
 <a role="button" href="#" style="display: none" class="btn btn-sm btn-secondary" id="linkdownload">Click to download Attachments</a>_x000D_
 <form asp-controller="mycontroller" asp-action="myaction" id="form1"></form>_x000D_

        function onDownload() {
            const api = '@Url.Action("myaction", "mycontroller")'; 
            //form1 is your id form, and to get data content of form
            var form = new FormData(document.getElementById('form1'));

            fetch(api, { body: form, method: "POST"})
                .then(resp => resp.blob())
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    $('#linkdownload').attr('download', '');
                    $('#linkdownload').attr("href", url);
                            function() {

                .catch(() => alert('An error occurred'));                 


Most useful NLog configurations

Easier Way To Log each log level with a different layout using Conditional Layouts

<variable name="VerboseLayout" value="${level:uppercase=true}: ${longdate} | ${logger}    : 
${when:when=level == LogLevel.Trace:inner=MONITOR_TRACE ${message}} 
${when:when=level == LogLevel.Debug:inner=MONITOR_DEBUG ${message}} 
${when:when=level == LogLevel.Info:inner=MONITOR_INFO ${message}} 
${when:when=level == LogLevel.Warn:inner=MONITOR_WARN ${message}} 
${when:when=level == LogLevel.Error:inner=MONITOR_ERROR ${message}} 
${when:when=level == LogLevel.Fatal:inner=MONITOR_CRITICAL ${message}} |     
${exception:format=tostring} | ${newline} ${newline}" />

See for syntax

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?


with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.


User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run


has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.


User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection


whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.


User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
// only users that have posts from 2015 on forward are returned

Append key/value pair to hash with << in Ruby

There is merge!.

h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}

How to use linux command line ftp with a @ sign in my username?

I've never seen the -u parameter. But if you want to use an "@", how about stating it as "\@"?

That way it should be interpreted as you intend. You know something like

ftp -u user\@[email protected]

How to add new column to an dataframe (to the front not end)?

If you want to do it in a tidyverse manner, try add_column from tibble, which allows you to specifiy where to place the new column with .before or .after parameter:


df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
add_column(df, a = 0, .before = 1)

#   a b c d
# 1 0 1 2 3
# 2 0 1 2 3
# 3 0 1 2 3

Checkout Jenkins Pipeline Git SCM with credentials?

To explicitly checkout using a specific credentials

    stage('Checkout external proj') {
        steps {
            git branch: 'my_specific_branch',
                credentialsId: 'my_cred_id',
                url: 'ssh://[email protected]/proj/test_proj.git'

            sh "ls -lat"

To checkout based on the configred credentials in the current Jenkins Job

    stage('Checkout code') {
        steps {
            checkout scm

You can use both of the stages within a single Jenkins file.

How to resolve Unneccessary Stubbing exception

I had UnnecessaryStubbingException when I tried to use the when methods on a Spy object. Mockito.lenient() silenced the exception but the test results were not correct.

In case of Spy objects, one has to call the methods directly.

class ArithmTest {

    private Arithm arithm;

    void testAddition() {

        int res = arithm.add(2, 5);

        // doReturn(7).when(arithm).add(2, 5);
        assertEquals(res, 7);

UICollectionView spacing margins

You can use the collectionView:layout:insetForSectionAtIndex: method for your UICollectionView or set the sectionInset property of the UICollectionViewFlowLayout object attached to your UICollectionView:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(top, left, bottom, right);


UICollectionViewFlowLayout *aFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[aFlowLayout setSectionInset:UIEdgeInsetsMake(top, left, bottom, right)];

Updated for Swift 5

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
       return UIEdgeInsets(top: 25, left: 15, bottom: 0, right: 5)

How to get the number of columns in a matrix?

When want to get row size with size() function, below code can be used:


Another usage for it:

[height, width] = size(A)

So, you can get 2 dimension of your matrix.

How do I use Join-Path to combine more than two strings into a file path?

You can use the .NET Path class:

[IO.Path]::Combine('C:\', 'Foo', 'Bar')


Another reason for PHP to return http code 0 is timeout. In my case, I had the following configuration:

curl_setopt($http, CURLOPT_TIMEOUT_MS,500);

It turned out that the request to the endpoint I was pointing to always took more than 500 ms, always timing out and always returning http code 0.

If you remove this setting (CURLOPT_TIMEOUT_MS) or put a higher value (in my case 5000), you'll get the actual http code, in my case a 200 (as expected).


CSS3 opacity gradient?

Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip to text.

Create proper gradient:

background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);

Then clip the backgroud with text:

background-clip: text;
color: transparent;


Tested under Chrome 75 under Windows 10.

Supported platforms:

Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :


use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0);

SSH Key - Still asking for password and passphrase

I tried all the answers here and none of these answers worked! My password would not persist between sessions/restarts of my Mac.

What I found out from reading this OpenRadar and this Twitter discussion was that Apple purposely changed the behaviour for ssh-agent in macOS 10.12 Sierra to no longer automatically load the previous SSH keys. In order to maintain the same behaviour as El Cap I did the following:

  1. ssh-add -K ~/.ssh/id_rsa
    Note: change the path to where your id_rsa key is located.
  2. ssh-add -A
  3. Create (or edit if it exists) the following ~/.ssh/config file:

    Host *
      UseKeychain yes
      AddKeysToAgent yes
      IdentityFile ~/.ssh/id_rsa

And now my password is remembered between restarts of my Mac!

How to define constants in Visual C# like #define in C?

Check How to: Define Constants in C# on MSDN:

In C# the #define preprocessor directive cannot be used to define constants in the way that is typically used in C and C++.

adding 1 day to a DATETIME format value

There's more then one way to do this with DateTime which was introduced in PHP 5.2. Unlike using strtotime() this will account for daylight savings time and leap year.

$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

// Available in PHP 5.3

$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');

// Available in PHP 5.4

echo (new DateTime('2013-01-29'))->add(new DateInterval('P1D'))->format('Y-m-d H:i:s');

// Available in PHP 5.5

$start = new DateTimeImmutable('2013-01-29');
$datetime = $start->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

ASP.NET MVC JsonResult Date Format

Here's some JavaScript code I wrote which sets an <input type="date"> value from a date passed from ASP.NET MVC.

var setDate = function(id, d) {
  if (d !== undefined && d !== null) {
    var date = new Date(parseInt(d.replace("/Date(", "").replace(")/", ""), 10));
    var day = ('0' + date.getDate()).slice(-2);
    var month = ('0' + (date.getMonth() + 1)).slice(-2);
    var parsedDate = date.getFullYear() + "-" + (month) + "-" + (day);

You call this function like so:

setDate('#productCommissionStartDate', data.commissionStartDate);

Where commissionStartDate is the JSON date passed by MVC.

How to set DataGrid's row Background, based on a property value using data bindings

Use a DataTrigger:

<DataGrid ItemsSource="{Binding YourItemsSource}">
        <Style TargetType="DataGridRow"> 
                <DataTrigger Binding="{Binding State}" Value="State1">
                    <Setter Property="Background" Value="Red"></Setter>
                <DataTrigger Binding="{Binding State}" Value="State2">
                    <Setter Property="Background" Value="Green"></Setter>

Type definition in object literal in TypeScript

If you're trying to write a type annotation, the syntax is:

var x: { property: string; } = { property: 'hello' };

If you're trying to write an object literal, the syntax is:

var x = { property: 'hello' };

Your code is trying to use a type name in a value position.

How to add border radius on table row

Actual Spacing Between Rows

This is an old thread, but I noticed reading the comments from the OP on other answers that the original goal was apparently to have border-radius on the rows, and gaps between the rows. It does not appear that the current solutions exactly do that. theazureshadow's answer is headed in the right direction, but seems to need a bit more.

For those interested in such, here is a fiddle that does separate the rows and applies the radius to each row. (NOTE: Firefox currently has a bug in displaying/clipping background-color at the border radii.)

The code is as follows (and as theazureshadow noted, for earlier browser support, the various vendor prefixes for border-radius need added).

table { 
    border-collapse: separate; 
    border-spacing: 0 10px; 
    margin-top: -10px; /* correct offset on first border spacing if desired */
td {
    border: solid 1px #000;
    border-style: solid none;
    padding: 10px;
    background-color: cyan;
td:first-child {
    border-left-style: solid;
    border-top-left-radius: 10px; 
    border-bottom-left-radius: 10px;
td:last-child {
    border-right-style: solid;
    border-bottom-right-radius: 10px; 
    border-top-right-radius: 10px; 

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

I've tried many solutions and came up with this.

Options and selections of the dropdown are cleared using this only

$("#my-multi option:selected").prop("selected", false);
$("#my-multi option").remove();

But the interface is not updated. So you have to do this


Hence, the final code is

$("#my-multi option:selected").prop("selected", false);
$("#my-multi option").remove();

Suggestions and improvements are welcome.

How to do associative array/hashing in JavaScript

You can create one using like the following:

var dictionary = { Name:"Some Programmer", Age:24, Job:"Writing Programs"  };

// Iterate over using keys
for (var key in dictionary) {
  console.log("Key: " + key + " , " + "Value: "+ dictionary[key]);

// Access a key using object notation:
console.log("Her name is: " + dictionary.Name)

IllegalMonitorStateException on wait() call

Those who are using Java 7.0 or below version can refer the code which I used here and it works.

public class WaitTest {

    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void waitHere(long waitTime) {
        System.out.println("wait started...");
        try {
            condition.await(waitTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
        System.out.println("wait ends here...");

    public static void main(String[] args) {
        //Your Code
        new WaitTest().waitHere(10);
        //Your Code


Pandas: Convert Timestamp to

Use the .date method:

In [11]: t = pd.Timestamp('2013-12-25 00:00:00')

In [12]:
Out[12]:, 12, 25)

In [13]: ==, 12, 25)
Out[13]: True

To compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:

In [21]: pd.Timestamp(, 12, 25))
Out[21]: Timestamp('2013-12-25 00:00:00')

In [22]: ts = pd.DatetimeIndex([t])

In [23]: ts == pd.Timestamp(, 12, 25))
Out[23]: array([ True], dtype=bool)

What does "restore purchases" in In-App purchases mean?

Is it as optional functionality.

If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.

If you will provide restore mechanism then your purchase manager will see restored transaction.

If app should distinguish this options then you should provide functionality for restoring previously purchased products.

Get input value from TextField in iOS alert in Swift

Swift 3/4

You can use the below extension for your convenience.

Usage inside a ViewController:

showInputDialog(title: "Add number",
                subtitle: "Please enter the new number below.",
                actionTitle: "Add",
                cancelTitle: "Cancel",
                inputPlaceholder: "New number",
                inputKeyboardType: .numberPad)
{ (input:String?) in
    print("The new number is \(input ?? "")")

The extension code:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {

        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))

        self.present(alert, animated: true, completion: nil)

How to grep and replace

Usually not with grep, but rather with sed -i 's/string_to_find/another_string/g' or perl -i.bak -pe 's/string_to_find/another_string/g'.

change html input type by JS?

Here is what I have for mine.

Essentially you are utilizing the onfocus and onblur commands in the tag to trigger the appropriate javascript. It could be as simple as:

<span><input name="login_text_password" type="text" value="Password" onfocus="; this.setAttribute('type','password');" onblur="; this.setAttribute('type','text');" /></span>

An evolved version of this basic functionality checks for and empty string and returns the password input back to the original "Password" in the event of a null textbox:

    <script type="text/javascript">
        function password_set_attribute() {
            if (document.getElementsByName("login_text_password")[0].value.replace(/\s+/g, ' ') == "" || document.getElementsByName[0].value == null) {
                document.getElementsByName("login_text_password")[0].value = 'Password';
            else {

Where HTML looks like:

<span><input name="login_text_password" class="roundCorners" type="text" value="Password" onfocus="; this.setAttribute('type','password');" onblur="password_set_attribute();" /></span>

TypeError: 'int' object is not subscriptable

Just to be clear, all the answers so far are correct, but the reasoning behind them is not explained very well.

The sumall variable is not yet a string. Parentheticals will not convert to a string (e.g. summ = (int(birthday[0])+int(birthday[1])) still returns an integer. It looks like you most likely intended to type str((int(sumall[0])+int(sumall[1]))), but forgot to. The reason the str() function fixes everything is because it converts anything in it compatible to a string.

How do I add a custom script to my package.json file that runs a javascript file?

Steps are below:

  1. In package.json add:

        "script1": "bin/script1.js" 
  2. Create a bin folder in the project directory and add file runScript1.js with the code:

    #! /usr/bin/env node
    var shell = require("shelljs");
    shell.exec("node step1script.js");
  3. Run npm install shelljs in terminal

  4. Run npm link in terminal

  5. From terminal you can now run script1 which will run node script1.js


EF 5 Enable-Migrations : No context type was found in the assembly

I have been getting this same problem. I have even tried above enable migrations even though I have already done. But it keeps giving same error. Then I had to use the force switch to get overcome this problem. I am sure this will help in someone else's case as well as its a possible work around.

After enabling migration with force, you should update your database (Make sure default project is set correctly). Otherwise you will get another problem like explicit migrations are pending.

Then just execute your add-migrations or any other commands, it should work.

Enable-Migrations -ProjectName <PROJECT_NAME> -ContextTypeName <FULL_CONTEXT_NAMESPACE.YOUR_CONTEXT_NAME> -force

"break;" out of "if" statement?

This is actually the conventional use of the break statement. If the break statement wasn't nested in an if block the for loop could only ever execute one time.

MSDN lists this as their example for the break statement.

Using an index to get an item, Python

Same as any other language, just pass index number of element that you want to retrieve.

#!/usr/bin/env python
x = [2,3,4,5,6,7]

How to tell git to use the correct identity (name and email) for a given project?

Edit the config file with in ".git" folder to maintain the different username and email depends upon the repository

  • Go to Your repository
  • Show the hidden files and go to ".git" folder
  • Find the "config" file
  • Add the below lines at EOF


name = Bob

email = [email protected]

This below command show you which username and email set for this repository.

git config --get

git config --get

Example: for mine that config file in D:\workspace\eclipse\ipchat\.git\config

Here ipchat is my repo name

Sometimes adding a WCF Service Reference generates an empty reference.cs

When attempting to troubleshoot this problem with svcutil, I received the error referred to in dblood's answer ("referenced type cannot be used since it does not match imported DataContract").

In my case the underlying cause seemed to be an enum type that had the DataContract attribute, but whose members were not marked with the EnumMember attribute. The problem class svcutil pointed at had a property with that enum type.

This would fit better as a comment to dblood's answer, but not enough rep for that...

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

it should vary with the architecture because it represents the size of any object. So on a 32-bit system size_t will likely be at least 32-bits wide. On a 64-bit system it will likely be at least 64-bit wide.

java.lang.IllegalStateException: Fragment not attached to Activity

Sometimes this exception is caused by a bug in the support library implementation. Recently I had to downgrade from 26.1.0 to 25.4.0 to get rid of it.

How to get values from IGrouping

Assume that you have MyPayments class like

 public class Mypayment
    public int year { get; set; }
    public string month { get; set; }
    public string price { get; set; }
    public bool ispaid { get; set; }

and you have a list of MyPayments

public List<Mypayment> mypayments { get; set; }

and you want group the list by year. You can use linq like this:

List<List<Mypayment>> mypayments = (from IGrouping<int, Mypayment> item in yearGroup
                                                let mypayments1 = (from _payment in UserProjects.mypayments
                                                                   where _payment.year == item.Key
                                                                   select _payment).ToList()
                                                select mypayments1).ToList();

How to append one file to another in Linux from the shell?

Just for reference, using ddrescue provides an interruptible way of achieving the task if, for example, you have large files and the need to pause and then carry on at some later point:

ddrescue -o $(wc --bytes file1 | awk '{ print $1 }') file2 file1 logfile

The logfile is the important bit. You can interrupt the process with Ctrl-C and resume it by specifying the exact same command again and ddrescue will read logfile and resume from where it left off. The -o A flag tells ddrescue to start from byte A in the output file (file1). So wc --bytes file1 | awk '{ print $1 }' just extracts the size of file1 in bytes (you can just paste in the output from ls if you like).

As pointed out by ngks in the comments, the downside is that ddrescue will probably not be installed by default, so you will have to install it manually. The other complication is that there are two versions of ddrescue which might be in your repositories: see this askubuntu question for more info. The version you want is the GNU ddrescue, and on Debian-based systems is the package named gddrescue:

sudo apt install gddrescue

For other distros check your package management system for the GNU version of ddrescue.

Regex in JavaScript for validating decimal numbers

as compared from the answer gven by mic... it doesnt validate anything in some of the platforms which i work upon... to be precise it doesnt actually work out in Dream Viewer..

hereby.. i re-write it again..which will work on any platform.. "^[0-9]+(.[0-9]{1,2})?$".. thnkss..

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

try using concatenation of string

Statistics(string date)
        this->date += date;

acually this was a part of a class..

Excel tab sheet names vs. Visual Basic sheet names

Actually "Sheet1" object / code name can be changed. In VBA, click on Sheet1 in Excel Objects list. In the properties window, you can change Sheet1 to say rng.

Then you can reference rng as a global object without having to create a variable first. So debug.print works just fine. No more Worksheets("rng").name.

Unlike the tab, the object name has same restrictions as other variables (i.e. no spaces).

How can I list all commits that changed a specific file?

Use git log --all <filename> to view the commits influencing <filename> in all branches.

How to compare a local git branch with its remote branch?


git diff 'master' 'testlocalBranch'

If you are using editor like webstorm, you can right click on file select compare with branch and type/select your branch.

enter image description here

enter image description here

Full-screen iframe with a height of 100%

I ran into the same problem, I was pulling an iframe into a div. Try this:

<iframe src="" frameborder="0" scrolling="yes" seamless="seamless" style="display:block; width:100%; height:100vh;"></iframe>

The height is set to 100vh which stands for viewport height. Also, the width could be set to 100vw, although you'll likely run into problems if the source file is responsive (your frame will become very wide).

Unique constraint violation during insert: why? (Oracle)

Presumably, since you're not providing a value for the DB_ID column, that value is being populated by a row-level before insert trigger defined on the table. That trigger, presumably, is selecting the value from a sequence.

Since the data was moved (presumably recently) from the production database, my wager would be that when the data was copied, the sequence was not modified as well. I would guess that the sequence is generating values that are much lower than the largest DB_ID that is currently in the table leading to the error.

You could confirm this suspicion by looking at the trigger to determine which sequence is being used and doing a

SELECT <<sequence name>>.nextval
  FROM dual

and comparing that to

  FROM cmdb_db

If, as I suspect, the sequence is generating values that already exist in the database, you could increment the sequence until it was generating unused values or you could alter it to set the INCREMENT to something very large, get the nextval once, and set the INCREMENT back to 1.

How can I convert byte size into a human-readable format in Java?

Byte Units allows you to do it like this:

long input1 = 1024;
long input2 = 1024 * 1024;

Assert.assertEquals("1 KiB", BinaryByteUnit.format(input1));
Assert.assertEquals("1 MiB", BinaryByteUnit.format(input2));

Assert.assertEquals("1.024 KB", DecimalByteUnit.format(input1, "#.0"));
Assert.assertEquals("1.049 MB", DecimalByteUnit.format(input2, "#.000"));

NumberFormat format = new DecimalFormat("#.#");
Assert.assertEquals("1 KiB", BinaryByteUnit.format(input1, format));
Assert.assertEquals("1 MiB", BinaryByteUnit.format(input2, format));

I have written another library called storage-units that allows you to do it like this:

String formattedUnit1 = StorageUnits.formatAsCommonUnit(input1, "#");
String formattedUnit2 = StorageUnits.formatAsCommonUnit(input2, "#");
String formattedUnit3 = StorageUnits.formatAsBinaryUnit(input1);
String formattedUnit4 = StorageUnits.formatAsBinaryUnit(input2);
String formattedUnit5 = StorageUnits.formatAsDecimalUnit(input1, "#.00", Locale.GERMAN);
String formattedUnit6 = StorageUnits.formatAsDecimalUnit(input2, "#.00", Locale.GERMAN);
String formattedUnit7 = StorageUnits.formatAsBinaryUnit(input1, format);
String formattedUnit8 = StorageUnits.formatAsBinaryUnit(input2, format);

Assert.assertEquals("1 kB", formattedUnit1);
Assert.assertEquals("1 MB", formattedUnit2);
Assert.assertEquals("1.00 KiB", formattedUnit3);
Assert.assertEquals("1.00 MiB", formattedUnit4);
Assert.assertEquals("1,02 kB", formattedUnit5);
Assert.assertEquals("1,05 MB", formattedUnit6);
Assert.assertEquals("1 KiB", formattedUnit7);
Assert.assertEquals("1 MiB", formattedUnit8);

In case you want to force a certain unit, do this:

String formattedUnit9 = StorageUnits.formatAsKibibyte(input2);
String formattedUnit10 = StorageUnits.formatAsCommonMegabyte(input2);

Assert.assertEquals("1024.00 KiB", formattedUnit9);
Assert.assertEquals("1.00 MB", formattedUnit10);

How to set an environment variable in a running docker container

For a somewhat narrow use case, docker issue 8838 mentions this sort-of-hack:

You just stop docker daemon and change container config in /var/lib/docker/containers/[container-id]/config.json (sic)

This solution updates the environment variables without the need to delete and re-run the container, having to migrate volumes and remembering parameters to run.

However, this requires a restart of the docker daemon. And, until issue issue 2658 is addressed, this includes a restart of all containers.

C# DataTable.Select() - How do I format the filter criteria to include null?

try this:

var result = from r in myDataTable.AsEnumerable()  
            where r.Field<string>("Name") != "n/a" &&  
                  r.Field<string>("Name") != "" select r;  
DataTable dtResult = result.CopyToDataTable();  

Avoiding "resource is out of sync with the filesystem"

Just right click on the file or on the project and click Refresh. The error will vanish. I also faced the same issue and it worked for me.

How can I create numbered map markers in Google Maps V3?

Based on @dave1010 answer but with updated https links.

Numbered marker:|FF0000|000000

Text marker:|0|FF0000|12|_|Marker

Are static class variables possible in Python?

One very interesting point about Python's attribute lookup is that it can be used to create "virtual variables":

class A(object):


  def __init__(self,d):

  def say(self): 
      print("%s %s!"%(self.label,

class B(A):
  label="Bold"  # overrides A.label

A(5).say()      # Amazing 5!
B(3).say()      # Bold 3!

Normally there aren't any assignments to these after they are created. Note that the lookup uses self because, although label is static in the sense of not being associated with a particular instance, the value still depends on the (class of the) instance.

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

A bracket - [ or ] - means that end of the range is inclusive -- it includes the element listed. A parenthesis - ( or ) - means that end is exclusive and doesn't contain the listed element. So for [first1, last1), the range starts with first1 (and includes it), but ends just before last1.

Assuming integers:

  • (0, 5) = 1, 2, 3, 4
  • (0, 5] = 1, 2, 3, 4, 5
  • [0, 5) = 0, 1, 2, 3, 4
  • [0, 5] = 0, 1, 2, 3, 4, 5

Removing cordova plugins from the project

From the terminal (osx) I usually use

cordova plugin -l | xargs cordova plugins rm

Pipe, pipe everything!

To expand a bit: this command will loop through the results of cordova plugin -l and feed it to cordova plugins rm.

xargs is one of those commands that you wonder why you didn't know about before. See this tut.

Output data with no column headings using PowerShell

In your case, when you just select a single property, the easiest way is probably to bypass any formatting altogether:

get-qadgroupmember 'Domain Admins' | foreach { $_.Name }

This will get you a simple string[] without column headings or empty lines. The Format-* cmdlets are mainly for human consumption and thus their output is not designed to be easily machine-readable or -parseable.

For multiple properties I'd probably go with the -f format operator. Something along the lines of

alias | %{ "{0,-10}{1,-10}{2,-60}" -f $_.COmmandType,$_.Name,$_.Definition }

which isn't pretty but gives you easy and complete control over the output formatting. And no empty lines :-)

Can't change table design in SQL Server 2008

Prevent saving changes that require table re-creation

Five swift clicks

Prevent saving changes that require table re-creation in five clicks

  1. Tools
  2. Options
  3. Designers
  4. Prevent saving changes that require table re-creation
  5. OK.

After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.

Further explanation

  • By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*

  • When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.

*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.

Clear the entire history stack and start a new activity on Android

I found too simple hack just do this add new element in AndroidManifest as:-

<activity android:name=".activityName"

the android:noHistory will clear your unwanted activity from Stack.

How to send a stacktrace to log4j?

this would be good log4j error/exception logging - readable by splunk/other logging/monitoring s/w. everything is form of key-value pair. log4j would get the stack trace from Exception obj e

    try {
    } catch (Exception e) {
        log.error("api_name={} method={} _message=\"error description.\" msg={}", 
                  new Object[]{"api_name", "method_name", e.getMessage(), e});

How to run C program on Mac OS X using Terminal?

First make sure you correct your program:

#include <stdio.h>

int main(void) {
   printf("Hello, world!\n"); //printf instead of pintf
   return 0;

Save the file as HelloWorld.c and type in the terminal:

gcc -o HelloWorld HelloWorld.c

Afterwards just run the executable like this:


You should be seeing Hello World!

Detecting IE11 using CSS Capability/Feature Detection

This seems to work:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  

How do you scroll up/down on the console of a Linux VM

SHIFT + Page Up and SHIFT + Page Down are the correct keys to operate on the linux (virtual) console, but vmware console doesn't have those terminal settings. The virtual console has fixed scroll back size, it sounds like it's limited to video memory size according to this Linux virtual console Scrolling behavior documentation.

Replace text inside td using jQuery having td containing other elements

Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.

Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span> for instance:

<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td>


$('.replaceme').html('Whatever <b>HTML</b> you want here.');

How to update (append to) an href in jquery?

$("a.directions-link").attr("href", $("a.directions-link").attr("href")+"...your additions...");