Programs & Examples On #Paypal sandbox

The PayPal Sandbox is a self-contained environment within which you can prototype and test PayPal features and APIs. The PayPal Sandbox is an almost identical copy of the live PayPal website.

Test credit card numbers for use with PayPal sandbox

If a credit card is already added to a PayPal account then it won't let you use that card to process directly with Payments Advanced. The system expects buyers to login to PayPal and just choose that credit card as their funding source if they want to pay with it.

As for testing on the sandbox, I've always used old, expired credit cards I have laying around and they seem to work fine for me.

You could always try the ones starting on page 87 of the PayFlow documentation, too. They should work.

Why is String immutable in Java?

From the Security point of view we can use this practical example:

DBCursor makeConnection(String IP,String PORT,String USER,String PASS,String TABLE) {

    // if strings were mutable IP,PORT,USER,PASS can be changed by validate function
    Boolean validated = validate(IP,PORT,USER,PASS);

    // here we are not sure if IP, PORT, USER, PASS changed or not ??
    if (validated) {
         DBConnection conn = doConnection(IP,PORT,USER,PASS);

    // rest of the code goes here ....

how to sync windows time from a ntp time server in command

Use net time net time \\timesrv /set /yes

after your comment try this one in evelated prompt :

w32tm /config /update /manualpeerlist:yourtimerserver

Port 80 is being used by SYSTEM (PID 4), what is that?

If you are running Windows Server 2012 R2 then make sure to get rid of Work Folders: Removing Work Folders feature under File Server worked for me.

Get path to execution directory of Windows Forms application

Both of the examples are in VB.NET.

Debug path:

TextBox1.Text = My.Application.Info.DirectoryPath

EXE path:

TextBox2.Text = IO.Path.GetFullPath(Application.ExecutablePath)

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

HTML display result in text (input) field?

Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use

document.getElementById('sum').innerHTML = sum;

Getting list of files in documents folder

Swift 2.0 Compability

func listWithFilter () {

    let fileManager = NSFileManager.defaultManager()
           // We need just to get the documents folder url
    let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL

    do {
    // if you want to filter the directory contents you can do like this:
    if let directoryUrls = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants) {




 func listFiles() -> [String] {

    var theError = NSErrorPointer()
    let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
    if dirs != nil {
        let dir = dirs![0]
        do {
        let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir)
        return fileList as [String]
        }catch {


        let fileList = [""]
        return fileList
    let fileList = [""]
    return fileList


Convert a date format in epoch

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:

String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454

Date.getTime() returns the epoch time in milliseconds.

Setting a Sheet and cell as variable

Yes. For that ensure that you declare the worksheet

For example

Previous Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet3")

    Debug.Print ws.Cells(23, 4).Value
End Sub

New Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet4")

    Debug.Print ws.Cells(23, 4).Value
End Sub

Add missing dates to pandas dataframe

One issue is that reindex will fail if there are duplicate values. Say we're working with timestamped data, which we want to index by date:

df = pd.DataFrame({
    'timestamps': pd.to_datetime(
        ['2016-11-15 1:00','2016-11-16 2:00','2016-11-16 3:00','2016-11-18 4:00']),
df.index = pd.DatetimeIndex(df['timestamps']).floor('D')


            timestamps             values
2016-11-15  "2016-11-15 01:00:00"  a
2016-11-16  "2016-11-16 02:00:00"  b
2016-11-16  "2016-11-16 03:00:00"  c
2016-11-18  "2016-11-18 04:00:00"  d

Due to the duplicate 2016-11-16 date, an attempt to reindex:

all_days = pd.date_range(df.index.min(), df.index.max(), freq='D')

fails with:

ValueError: cannot reindex from a duplicate axis

(by this it means the index has duplicates, not that it is itself a dup)

Instead, we can use .loc to look up entries for all dates in range:



            timestamps             values
2016-11-15  "2016-11-15 01:00:00"  a
2016-11-16  "2016-11-16 02:00:00"  b
2016-11-16  "2016-11-16 03:00:00"  c
2016-11-17  NaN                    NaN
2016-11-18  "2016-11-18 04:00:00"  d

fillna can be used on the column series to fill blanks if needed.

How do I create JavaScript array (JSON format) dynamically?

What I do is something just a little bit different from @Chase answer:

var employees = {};

// ...and then:
employees.accounting = new Array();

for (var i = 0; i < someArray.length; i++) {
    var temp_item = someArray[i];

    // Maybe, here make something like:
    // = 'some value'

        "firstName" : temp_item.firstName,
        "lastName"  : temp_item.lastName,
        "age"       : temp_item.age

And that work form me!

I hope it could be useful for some body else!

How can I define fieldset border color?

I added it for all fieldsets with

fieldset {
        border: 1px solid lightgray;

I didnt work if I set it separately using for example

border-color : red

. Then a black line was drawn next to the red line.

How do I navigate to another page when PHP script is done?

if ($done)
    header("Location: /url/to/the/other/page");

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

Try this (it's VB-Code :-):


Catch exp As WebException
  Dim sResponse As String = New StreamReader(exp.Response.GetResponseStream()).ReadToEnd
End Try

Pandas percentage of total with groupby

You need to make a second groupby object that groups by the states, and then use the div method:

import numpy as np
import pandas as pd
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999) for _ in range(12)]})

state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
state = df.groupby(['state']).agg({'sales': 'sum'})
state_office.div(state, level='state') * 100

state office_id           
AZ    2          16.981365
      4          19.250033
      6          63.768601
CA    1          19.331879
      3          33.858747
      5          46.809373
CO    1          36.851857
      3          19.874290
      5          43.273852
WA    2          34.707233
      4          35.511259
      6          29.781508

the level='state' kwarg in div tells pandas to broadcast/join the dataframes base on the values in the state level of the index.

Efficiently convert rows to columns in sql server

There are several ways that you can transform data from multiple rows into columns.


In SQL Server you can use the PIVOT function to transform the data from rows to columns:

select Firstname, Amount, PostalCode, LastName, AccountNumber
  select value, columnname
  from yourtable
) d
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

See Demo.

Pivot with unknown number of columnnames

If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 

set @query = N'SELECT ' + @cols + N' from 
                select value, ColumnName
                from yourtable
            ) x
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

See Demo.

Using an aggregate function

If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable

See Demo.

Using multiple joins

This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

select fn.value as FirstName,
  a.value as Amount,
  pc.value as PostalCode,
  ln.value as LastName,
  an.value as AccountNumber
from yourtable fn
left join yourtable a
  on fn.somecol = a.somecol
  and a.columnname = 'Amount'
left join yourtable pc
  on fn.somecol = pc.somecol
  and pc.columnname = 'PostalCode'
left join yourtable ln
  on fn.somecol = ln.somecol
  and ln.columnname = 'LastName'
left join yourtable an
  on fn.somecol = an.somecol
  and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'

How do I send a POST request as a JSON?

If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request...

Python 2.x

import json
import urllib2

data = {
        'ids': [12, 3, 4, 5, 6]

req = urllib2.Request('')
req.add_header('Content-Type', 'application/json')

response = urllib2.urlopen(req, json.dumps(data))

Python 3.x

If you don't specify the header, it will be the default application/x-www-form-urlencoded type.

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {


} catch (\Exception $e) {

    return $e->getMessage();

In your code you've used catch (Exception $e) so Exception is being searched in/as:


Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

After placing the jar file in desired location, you need to add the jar file by right click on

Project --> properties --> Java Build Path --> Libraries --> Add Jar.

React Native Error: ENOSPC: System limit for number of file watchers reached

If you are running your project in Docker, you should do the echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf and all other commands in the host machine, since the container will inherit that setting automatically (and doing it directly inside it will not work).

How to detect input type=file "change" for the same file?

So, there is no way to 100% be sure they are selecting the same file unless you store each file and compare them programmatically.

The way you interact with files (what JS does when the user 'uploads' a file) is HTML5 File API and JS FileReader.

These tutorials show you how to capture and read the metadata (stored as js object) when a file is uploaded.

Create a function that fires 'onChange' that will read->store->compare metadata of the current file against the previous files. Then you can trigger your event when the desired file is selected.

add item to dropdown list in html using javascript

Since your script is in <head>, you need to wrap it in window.onload:

window.onload = function () {
    var select = document.getElementById("year");
    for(var i = 2011; i >= 1900; --i) {
        var option = document.createElement('option');
        option.text = option.value = i;
        select.add(option, 0);

You can also do it in this way

<body onload="addList()">

Reportviewer tool missing in visual studio 2017 RC

Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:

  1. If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:

    • Microsoft.DataTools.ReportingServices.vsix, and
    • Microsoft.RdlcDesigner.vsix
  2. Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:

    • Microsoft.ReportViewer.Common.dll
    • Microsoft.ReportViewer.DataVisualization.dll
    • Microsoft.ReportViewer.Design.dll
    • Microsoft.ReportViewer.ProcessingObjectModel.dll
    • Microsoft.ReportViewer.WinForms.dll
  3. Install the 2 components from 1 above

  4. Add the dlls from 2 above as references (Project>References>Add...)
  5. (Optional) Add Reporting tab to the toolbar
  6. Add Items to Reporting tab
  7. Browse to the bin folder or where you have the above dlls and add them

You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project

NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!

How to check if array is not empty?

len(self.table) checks for the length of the array, so you can use if-statements to find out if the length of the list is greater than 0 (not empty):

Python 2:

if len(self.table) > 0:
    #Do code here

Python 3:

if(len(self.table) > 0):
    #Do code here

It's also possible to use

if self.table:
    #Execute if self.table is not empty
    #Execute if self.table is empty

to see if the list is not empty.

What is the preferred syntax for defining enums in JavaScript?

As of writing, October 2014 - so here is a contemporary solution. Am writing the solution as a Node Module, and have included a test using Mocha and Chai, as well as underscoreJS. You can easily ignore these, and just take the Enum code if preferred.

Seen a lot of posts with overly convoluted libraries etc. The solution to getting enum support in Javascript is so simple it really isn't needed. Here is the code:

File: enums.js

_ = require('underscore');

var _Enum = function () {

   var keys =, function (value) {
      return value;
   var self = {
      keys: keys
   for (var i = 0; i < arguments.length; i++) {
      self[keys[i]] = i;
   return self;

var fileFormatEnum = Object.freeze(_Enum('CSV', 'TSV'));
var encodingEnum = Object.freeze(_Enum('UTF8', 'SHIFT_JIS'));

exports.fileFormatEnum = fileFormatEnum;
exports.encodingEnum = encodingEnum;

And a test to illustrate what it gives you:

file: enumsSpec.js

var chai = require("chai"),
    assert = chai.assert,
    expect = chai.expect,
    should = chai.should(),
    enums = require('./enums'),
    _ = require('underscore');

describe('enums', function () {

    describe('fileFormatEnum', function () {
        it('should return expected fileFormat enum declarations', function () {
            var fileFormatEnum = enums.fileFormatEnum;
            assert('{"keys":["CSV","TSV"],"CSV":0,"TSV":1}' === JSON.stringify(fileFormatEnum), 'Unexpected format');
            assert('["CSV","TSV"]' === JSON.stringify(fileFormatEnum.keys), 'Unexpected keys format');

    describe('encodingEnum', function () {
        it('should return expected encoding enum declarations', function () {
            var encodingEnum = enums.encodingEnum;
            assert('{"keys":["UTF8","SHIFT_JIS"],"UTF8":0,"SHIFT_JIS":1}' === JSON.stringify(encodingEnum), 'Unexpected format');
            assert('["UTF8","SHIFT_JIS"]' === JSON.stringify(encodingEnum.keys), 'Unexpected keys format');


As you can see, you get an Enum factory, you can get all the keys simply by calling enum.keys, and you can match the keys themselves to integer constants. And you can reuse the factory with different values, and export those generated Enums using Node's modular approach.

Once again, if you are just a casual user, or in the browser etc, just take the factory part of the code, potentially removing underscore library too if you don't wish to use it in your code.

Where are Docker images stored on the host machine?

The images are stored in /var/lib/docker/graph/<id>/layer.

Note that images are just diffs from the parent image. The parent ID is stored with the image's metadata /var/lib/docker/graph/<id>/json.

When you docker run an image. AUFS will 'merge' all layers into one usable file system.

Changing ImageView source

get ID of ImageView as

ImageView imgFp = (ImageView) findViewById(;

then Use


to set source image programatically instead from XML.

How to watch and reload ts-node when TypeScript files change

add this to your package.json file

scripts {
"dev": "nodemon --watch '**/*.ts' --exec 'ts-node' index.ts"

and to make this work you also need to install ts-node as dev-dependency

yarn add ts-node -D

run yarn dev to start the dev server

HTTPS connections over proxy servers

You can accomplish this using man-in-the-middle techniques with dynamic SSL generation. Take a look at mitmproxy - it's a Python based, SSL-capable MITM proxy.

Executing command line programs from within python

I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.

.war vs .ear file


tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge

Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure

war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes

ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files

Effective method to hide email from spam bots

Not my idea originally but I can't find the author:

<a href="mailto:[email protected]"

Add as many x's as you like. It works perfectly to read, copy and paste, and can't be read by a bot.

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.


To explicitly do this in XPath, you'd be looking at:


for the first one, for the second etc:


Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:


Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:


That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:


Hope that helps!

convert an enum to another type of enum

Based on Justin's answer above I came up with this:

    /// <summary>
    /// Converts Enum Value to different Enum Value (by Value Name) See
    /// </summary>
    /// <typeparam name="TEnum">The type of the enum to convert to.</typeparam>
    /// <param name="source">The source enum to convert from.</param>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    public static TEnum ConvertTo<TEnum>(this Enum source)
            return (TEnum) Enum.Parse(typeof(TEnum), source.ToString(), ignoreCase: true);
        catch (ArgumentException aex)
            throw new InvalidOperationException
                $"Could not convert {source.GetType().ToString()} [{source.ToString()}] to {typeof(TEnum).ToString()}", aex

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

This error is occur,because the function is not defined. In my case i have called the datepicker function without including the datepicker js file that time I got this error.

java.lang.OutOfMemoryError: Java heap space

  1. Upto my knowledge, Heap space is occupied by instance variables only. If this is correct, then why this error occurred after running fine for sometime as space for instance variables are alloted at the time of object creation.

That means you are creating more objects in your application over a period of time continuously. New objects will be stored in heap memory and that's the reason for growth in heap memory.

Heap not only contains instance variables. It will store all non-primitive data types ( Objects). These objects life time may be short (method block) or long (till the object is referenced in your application)

  1. Is there any way to increase the heap space?

Yes. Have a look at this oracle article for more details.

There are two parameters for setting the heap size:

-Xms:, which sets the initial and minimum heap size

-Xmx:, which sets the maximum heap size

  1. What changes should I made to my program so that It will grab less heap space?

It depends on your application.

  1. Set the maximum heap memory as per your application requirement

  2. Don't cause memory leaks in your application

  3. If you find memory leaks in your application, find the root cause with help of profiling tools like MAT, Visual VM , jconsole etc. Once you find the root cause, fix the leaks.

Important notes from oracle article

Cause: The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak.

Possible reasons:

  1. Improper configuration ( not allocating sufficiant memory)
  2. Application is unintentionally holding references to objects and this prevents the objects from being garbage collected
  3. Applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time. If the finalizer thread cannot keep up, with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.

On a different note, use better Garbage collection algorithms ( CMS or G1GC)

Have a look at this question for understanding G1GC

How can I format a list to print each element on a separate line in python?

Use str.join:

In [27]: mylist = ['10', '12', '14']

In [28]: print '\n'.join(mylist)

fatal: The current branch master has no upstream branch

First use git pull origin your_branch_name Then use git push origin your_branch_name

error: package does not exist

I had similar issues when migrating to androidx. this issue comes due to the Old Butter Knife library dependency.

if you are using butter knife then you should use at least butter knife version 9.0.0-SNAPSHOT or above.

implementation 'com.jakewharton:butterknife:9.0.0-SNAPSHOT' annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0-SNAPSHOT'

Pytorch reshape tensor dimension

This question has been thoroughly answered already, but I want to add for the less experienced python developers that you might find the * operator helpful in conjunction with view().

For example if you have a particular tensor size that you want a different tensor of data to conform to, you might try:

img = Variable(tensor.randn(20,30,3)) # tensor with goal shape
flat_size = 20*30*3
X = Variable(tensor.randn(50, flat_size)) # data tensor

X = X.view(-1, *img.size()) # sweet maneuver
print(X.size()) # size is (50, 20, 30, 3)

This works with numpy shape too:

img = np.random.randn(20,30,3)
flat_size = 20*30*3
X = Variable(tensor.randn(50, flat_size))
X = X.view(-1, *img.shape)
print(X.size()) # size is (50, 20, 30, 3)

How to find files recursively by file type and copy them to a directory while in ssh?

Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to

find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;

Just to sum up!

Regular Expression to select everything before and up to a particular text

This matches everything up to ".txt" (without including it):


How to add element to C++ array?

Since I got so many negative feedback I realized my solution was wrong so i changed it.

int arr[20] = {1,2,3,4,5};
int index = 5;

void push(int n){
    arr[index] = n;


New array will contain value from 1 to 6 and you can make function for deletion like this as well.

How to compare if two structs, slices or maps are equal?

You can use reflect.DeepEqual, or you can implement your own function (which performance wise would be better than using reflection):

m1 := map[string]int{   
m2 := map[string]int{   
fmt.Println(reflect.DeepEqual(m1, m2))

JavaScript naming conventions

As Geoff says, what Crockford says is good.

The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.

var footer = document.getElementById('footer');

var $footer = $('#footer');

Random integer in VB.NET

Dim rnd As Random = New Random

Force add despite the .gitignore file

Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel

Extract number from string with Oracle function

You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:

select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;

which will return "12345569".

also you can use this one:

select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers,
       regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters
from dual

which will return "12345569" for numbers and "StackOverFlow" for characters.

How to compare two dates in php

compare the result of maketime() for each of the time

Controller 'ngModel', required by directive '...', can't be found

I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"

Wrong one: ng-moel="" Right one: ng-model=""

enter image description here

How do I loop through items in a list box and then remove those item?

You have to go through the collection from the last item to the first. this code is in vb

for i as integer= list.items.count-1 to 0 step -1

Failed to allocate memory: 8

Everything else you read here and elsewhere is pure conjecture. The only sure-way to fix this problem is vote for this bug report.

The problem isn't related to emulator resolution or OpenGL, nor how much memory your computer has. I've got 24GB memory in my computer and most of the time I run with hw.ramSize=1024 I get error 8. Other times it works just fine without any configuration changes. I hope you caught that: I did not alter the emulator configuration at all and yet sometimes it runs and sometimes it fails.

There is a high probability it has something to do with memory fragmentation. I recommend reducing the value of hw.ramSize as a temporary workaround.

How to delete only the content of file in python

How to delete only the content of file in python

There is several ways of set the logical size of a file to 0, depending how you access that file:

To empty an open file:

def deleteContent(pfile):

To empty a open file whose file descriptor is known:

def deleteContent(fd):
    os.ftruncate(fd, 0)
    os.lseek(fd, 0, os.SEEK_SET)

To empty a closed file (whose name is known)

def deleteContent(fName):
    with open(fName, "w"):

I have a temporary file with some content [...] I need to reuse that file

That being said, in the general case it is probably not efficient nor desirable to reuse a temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFile and a context manager to almost transparently create/use/delete your temporary files:

import tempfile

with tempfile.TemporaryFile() as temp:
     # do whatever you want with `temp`

# <- `tempfile` guarantees the file being both closed *and* deleted
#     on exit of the context manager

Best way to check if an PowerShell Object exist?

You can also do

if ($ie) {
    # Do Something if $ie is not null

How to a convert a date to a number and back again in MATLAB


>> datestr(40189)
ans =

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
>> datenum(2010,1,11)-40189
ans =
>> datestr(40189+693960)
ans =

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)


To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

I write code bewlow. It works well in product version. Supprot Swift 4.2 +

extension UIButton{
 enum ImageTitleRelativeLocation {
    case imageUpTitleDown
    case imageDownTitleUp
    case imageLeftTitleRight
    case imageRightTitleLeft
 func centerContentRelativeLocation(_ relativeLocation: 
                                   spacing: CGFloat = 0) {
    assert(contentVerticalAlignment == .center,
           "only works with contentVerticalAlignment = .center !!!")

    guard (title(for: .normal) != nil) || (attributedTitle(for: .normal) != nil) else {
        assert(false, "TITLE IS NIL! SET TITTLE FIRST!")

    guard let imageSize = self.currentImage?.size else {
        assert(false, "IMGAGE IS NIL! SET IMAGE FIRST!!!")
    guard let titleSize = titleLabel?
        .systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) else {
            assert(false, "TITLELABEL IS NIL!")

    let horizontalResistent: CGFloat
    // extend contenArea in case of title is shrink
    if frame.width < titleSize.width + imageSize.width {
        horizontalResistent = titleSize.width + imageSize.width - frame.width
        print("horizontalResistent", horizontalResistent)
    } else {
        horizontalResistent = 0

    var adjustImageEdgeInsets: UIEdgeInsets = .zero
    var adjustTitleEdgeInsets: UIEdgeInsets = .zero
    var adjustContentEdgeInsets: UIEdgeInsets = .zero

    let verticalImageAbsOffset = abs((titleSize.height + spacing) / 2)
    let verticalTitleAbsOffset = abs((imageSize.height + spacing) / 2)

    switch relativeLocation {
    case .imageUpTitleDown: = -verticalImageAbsOffset
        adjustImageEdgeInsets.bottom = verticalImageAbsOffset
        adjustImageEdgeInsets.left = titleSize.width / 2 + horizontalResistent / 2
        adjustImageEdgeInsets.right = -titleSize.width / 2 - horizontalResistent / 2 = verticalTitleAbsOffset
        adjustTitleEdgeInsets.bottom = -verticalTitleAbsOffset
        adjustTitleEdgeInsets.left = -imageSize.width / 2 + horizontalResistent / 2
        adjustTitleEdgeInsets.right = imageSize.width / 2 - horizontalResistent / 2 = spacing
        adjustContentEdgeInsets.bottom = spacing
        adjustContentEdgeInsets.left = -horizontalResistent
        adjustContentEdgeInsets.right = -horizontalResistent
    case .imageDownTitleUp: = verticalImageAbsOffset
        adjustImageEdgeInsets.bottom = -verticalImageAbsOffset
        adjustImageEdgeInsets.left = titleSize.width / 2 + horizontalResistent / 2
        adjustImageEdgeInsets.right = -titleSize.width / 2 - horizontalResistent / 2 = -verticalTitleAbsOffset
        adjustTitleEdgeInsets.bottom = verticalTitleAbsOffset
        adjustTitleEdgeInsets.left = -imageSize.width / 2 + horizontalResistent / 2
        adjustTitleEdgeInsets.right = imageSize.width / 2 - horizontalResistent / 2 = spacing
        adjustContentEdgeInsets.bottom = spacing
        adjustContentEdgeInsets.left = -horizontalResistent
        adjustContentEdgeInsets.right = -horizontalResistent
    case .imageLeftTitleRight:
        adjustImageEdgeInsets.left = -spacing / 2
        adjustImageEdgeInsets.right = spacing / 2

        adjustTitleEdgeInsets.left = spacing / 2
        adjustTitleEdgeInsets.right = -spacing / 2

        adjustContentEdgeInsets.left = spacing
        adjustContentEdgeInsets.right = spacing
    case .imageRightTitleLeft:
        adjustImageEdgeInsets.left = titleSize.width + spacing / 2
        adjustImageEdgeInsets.right = -titleSize.width - spacing / 2

        adjustTitleEdgeInsets.left = -imageSize.width - spacing / 2
        adjustTitleEdgeInsets.right = imageSize.width + spacing / 2

        adjustContentEdgeInsets.left = spacing
        adjustContentEdgeInsets.right = spacing

    imageEdgeInsets = adjustImageEdgeInsets
    titleEdgeInsets = adjustTitleEdgeInsets
    contentEdgeInsets = adjustContentEdgeInsets


JQuery DatePicker ReadOnly

All of the listed solutions give a mediocre user experience or cause issues if you want to re-enable the datepicker with it's settings in-tact. I used a method similar to making a select read-only, which is to disable it but add a hidden field with the same name. Check it:


$("#datepicker").readonlyDatepicker(true); //makes the datepicker readonly
$("#datepicker").readonlyDatepicker(false); //makes the datepicker editable again

jQuery function:

$.fn.readonlyDatepicker = function (makeReadonly) {

        //find corresponding hidden field
        var name = $(this).attr('name');
        var $hidden = $('input[name="' + name + '"][type="hidden"]');

        //if it doesn't exist, create it
        if ($hidden.length === 0){
            $hidden = $('<input type="hidden" name="' + name + '"/>');

        if (makeReadonly){
            $(this).attr('disabled', true);
            $(this).bind('change.readonly', function(){
            $(this).attr('disabled', false);

Do we need to execute Commit statement after Update in SQL Server

Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.

ng-change get new value and original value

You can use something like ng-change=someMethod({{}}). By keeping your value in side {{expression}} it will evaluate expression in-line and gives you current value(value before ng-change method is called).

<select ng-model="selectedValue" ng-change="change(selectedValue, '{{selectedValue}}')">

How to use If Statement in Where Clause in SQL?

You have to use CASE Statement/Expression

Select * from Customer
WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
    (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
     CASE @Value
         WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL) 
         WHEN 3 THEN (CASE WHEN I.RecurringCharge like 
                               '%'+cast(@Total as varchar(50))+'%' 
                     or @Total is NULL )

How can I get column names from a table in Oracle?

describe YOUR_TABLE;

In your case :

describe EVENT_LOG;

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

No you are not required to close anything BUT the connection. Per JDBC specs closing any higher object will automatically close lower objects. Closing Connection will close any Statements that connection has created. Closing any Statement will close all ResultSets that were created by that Statement. Doesn't matter if Connection is poolable or not. Even poolable connection has to clean before returning to the pool.

Of course you might have long nested loops on the Connection creating lots of statements, then closing them is appropriate. I almost never close ResultSet though, seems excessive when closing Statement or Connection WILL close them.

ESLint not working in VS Code?

In my case, I had the .eslintrc.json file inside the .vscode folder. Once I moved it out to the root folder, ESLint started working correctly.

Navigation Controller Push View Controller

-  (void) loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                error:(NSError *)error{
    UINavigationController *nav = [self.storyboard instantiateViewControllerWithIdentifier:@"nav"];
    ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"LoggedInVC"];
    [nav pushViewController:vc animated:YES];
    [self presentViewController:nav animated:YES completion:nil];

"nav" is the Storyboard ID for my navigation controller "vc" is the Storyboard ID for my first view controller connected to my navigation controller

-hope this helps

How to send email using simple SMTP commands via Gmail?

As no one has mentioned - I would suggest to use great tool for such purpose - swaks

# yum info swaks
Installed Packages
Name        : swaks
Arch        : noarch
Version     : 20130209.0
Release     : 3.el6
Size        : 287 k
Repo        : installed
From repo   : epel
Summary     : Command-line SMTP transaction tester
URL         :
License     : GPLv2+
Description : Swiss Army Knife SMTP: A command line SMTP tester. Swaks can test
            : various aspects of your SMTP server, including TLS and AUTH.

It has a lot of options and can do almost everything you want.

GMAIL: STARTTLS, SSLv3 (and yes, in 2016 gmail still support sslv3)

$ echo "Hello world" | swaks -4 --server --from [email protected] --to [email protected] -tls --tls-protocol sslv3 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying
=== Connected to
<-  220 ESMTP h8sm76342lbd.48 - gsmtp
 -> EHLO
<- at your service, []
<-  250-SIZE 35882577
<-  250-8BITMIME
<-  250-STARTTLS
<-  250-CHUNKING
<-  250 SMTPUTF8
<-  220 2.0.0 Ready to start TLS
=== TLS started with cipher SSLv3:RC4-SHA:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Mountain View/O=Google Inc/"
 ~> EHLO
<~ at your service, []
<~  250-SIZE 35882577
<~  250-8BITMIME
<~  250-CHUNKING
<~  250 SMTPUTF8
<~  235 2.7.0 Accepted
 ~> MAIL FROM:<[email protected]>
<~  250 2.1.0 OK h8sm76342lbd.48 - gsmtp
 ~> RCPT TO:<[email protected]>
<~  250 2.1.5 OK h8sm76342lbd.48 - gsmtp
 ~> DATA
<~  354  Go ahead h8sm76342lbd.48 - gsmtp
 ~> Date: Wed, 17 Feb 2016 09:49:03 +0000
 ~> To: [email protected]
 ~> From: [email protected]
 ~> Subject: Test message
 ~> X-Mailer: swaks v20130209.0
 ~> Hello world
 ~> .
<~  250 2.0.0 OK 1455702544 h8sm76342lbd.48 - gsmtp
 ~> QUIT
<~  221 2.0.0 closing connection h8sm76342lbd.48 - gsmtp
=== Connection closed with remote host.

YAHOO: TLS aka SMTPS, tlsv1.2

$ echo "Hello world" | swaks -4 --server --from [email protected] --to [email protected] --tlsc --tls-protocol tlsv1_2 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying
=== Connected to
=== TLS started with cipher TLSv1.2:ECDHE-RSA-AES128-GCM-SHA256:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Sunnyvale/O=Yahoo Inc./OU=Information Technology/"
<~  220 ESMTP ready
 ~> EHLO
<~  250-SIZE 41697280
<~  250-8 BITMIME
<~  235 2.0.0 OK
 ~> MAIL FROM:<[email protected]>
<~  250 OK , completed
 ~> RCPT TO:<[email protected]>
<~  250 OK , completed
 ~> DATA
<~  354 Start Mail. End with CRLF.CRLF
 ~> Date: Wed, 17 Feb 2016 10:08:28 +0000
 ~> To: [email protected]
 ~> From: [email protected]
 ~> Subject: Test message
 ~> X-Mailer: swaks v20130209.0
 ~> Hello world
 ~> .
<~  250 OK , completed
 ~> QUIT
<~  221 Service Closing transmission
=== Connection closed with remote host.

I have been using swaks to send email notifications from nagios via gmail for last 5 years without any problem.

JavaScript: client-side vs. server-side validation

JavaScript can be modified at runtime.

I suggest a pattern of creating a validation structure on the server, and sharing this with the client.

You'll need separate validation logic on both ends, ex:

"required" attributes on inputs client-side

field.length > 0 server-side.

But using the same validation specification will eliminate some redundancy (and mistakes) of mirroring validation on both ends.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);

How do I put the image on the right side of the text in a UIButton?

Just update the insets when the title is changed. You need to compensate for the inset with an equal and opposite inset on the other side.

[thebutton setTitle:title forState:UIControlStateNormal];
thebutton.titleEdgeInsets = UIEdgeInsetsMake(0, -thebutton.imageView.frame.size.width, 0, thebutton.imageView.frame.size.width);
thebutton.imageEdgeInsets = UIEdgeInsetsMake(0, thebutton.titleLabel.frame.size.width, 0, -thebutton.titleLabel.frame.size.width);

gcc warning" 'will be initialized after'

If you're seeing errors from library headers and you're using GCC, then you can disable warnings by including the headers using -isystem instead of -I.

Similar features exist in clang.

If you're using CMake, you can specify SYSTEM for include_directories.

datetimepicker is not a function jquery

I had the same problem with bootstrap datetimepicker extension. Including moment.js before datetimepicker.js was the solution.

What's the name for hyphen-separated case?

This casing can also be called a "slug", and the process of turning a phrase into it "slugify".

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

Those seem to be MySQL data types.

According to the documentation they take:

  1. tinyint = 1 byte
  2. smallint = 2 bytes
  3. mediumint = 3 bytes
  4. int = 4 bytes
  5. bigint = 8 bytes

And, naturally, accept increasingly larger ranges of numbers.

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

When programming I often have strings with just plain A-Za-z and 0-9. No need for difficult Index actions. This extension is based on the plain old left / mid / right functions.

extension String {

    // LEFT
    // Returns the specified number of chars from the left of the string
    // let str = "Hello"
    // print(str.left(3))         // Hel
    func left(_ to: Int) -> String {
        return "\(self[..<self.index(startIndex, offsetBy: to)])"

    // RIGHT
    // Returns the specified number of chars from the right of the string
    // let str = "Hello"
    // print(str.left(3))         // llo
    func right(_ from: Int) -> String {
        return "\(self[self.index(startIndex, offsetBy: self.length-from)...])"

    // MID
    // Returns the specified number of chars from the startpoint of the string
    // let str = "Hello"
    // print(str.left(2,amount: 2))         // ll
    func mid(_ from: Int, amount: Int) -> String {
        let x = "\(self[self.index(startIndex, offsetBy: from)...])"
        return x.left(amount)

How would I stop a while loop after n amount of time?

I have read this but I just want to ask something, wouldn't something like I have written work at all? I have done the testing for 5,10 and 20 seconds. Its time isn't exactly accurate but they are really close to the actual values.

import time

while begin_time<5:

print("The Work is Done")

Clear History and Reload Page on Login/Logout Using Ionic Framework

Reload the page isn't the best approach.

you can handle state change events for reload data without reload the view itself.

read about ionicView life-cycle here:

and handle the event beforeEnter for data reload.

$scope.$on('$ionicView.beforeEnter', function(){
  // Any thing you can think of

How to get difference between two dates in Year/Month/Week/Day?

int day=0,month=0,year=0;
DateTime smallDate = Convert.ToDateTime(string.Format("{0}", "01.01.1900"));
DateTime bigDate = Convert.ToDateTime(string.Format("{0}", "05.06.2019"));
TimeSpan timeSpan = new TimeSpan();

//timeSpan is diff between bigDate and smallDate as days
timeSpan = bigDate - smallDate;

//year is totalDays / 365 as int
year = timeSpan.Days / 365;

//smallDate.AddYears(year) is closing the difference for year because we found the year variable
smallDate = smallDate.AddYears(year);

//again subtraction because we don't need the year now
timeSpan = bigDate - smallDate;

//month is totalDays / 30 as int
month = timeSpan.Days / 30;

//smallDate.AddMonths(month) is closing the difference for month because we found the month variable
smallDate = smallDate.AddMonths(month);
if (bigDate > smallDate)
    timeSpan = bigDate - smallDate;
    day = timeSpan.Days;
//else it is mean already day is 0

Vue Js - Loop via v-for X times (in a range)

The same goes for v-for in range:

<li v-for="n in 20 " :key="n">{{n}}</li>

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.


sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean


sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

What is the best way to auto-generate INSERT statements for a SQL Server table?

Do you have data in a production database yet? If so, you could setup a period refresh of the data via DTS. We do ours weekly on the weekends and it is very nice to have clean, real data every week for our testing.

If you don't have production yet, then you should create a database that is they want you want it (fresh). Then, duplicate that database and use that newly created database as your test environment. When you want the clean version, simply duplicate your clean one again and Bob's your uncle.

Git Push ERROR: Repository not found

If you clone from github using https but you are using ssh to push, you can also get this error.

To correct this, open .git/config and replace:

url =


url = [email protected]:company/project.git

And you should be able to push with no warning...

How to list all available Kafka brokers in a cluster?

I did it like this



for i in `echo dump | nc $ZK_HOST $ZK_PORT | grep brokers`
    echo $i
    DETAIL=`zkCli -server "$ZK_HOST:$ZK_PORT" get $i 2>/dev/null | tail -n 1`
    echo $DETAIL

Simulate low network connectivity for Android

This may sound a little crazy, but a microwave oven serves as a microwave shield. Therefore, putting your device inside a microwave oven (DO NOT turn on the microwave oven while your device is inside!) will cause your signal strength to drop significantly. It definitely beats standing inside an elevator...

Jackson and generic type reference

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

Comparing Java enum members: == or equals()?

Enums are classes that return one instance (like singletons) for each enumeration constant declared by public static final field (immutable) so that == operator could be used to check their equality rather than using equals() method

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

The error code 0x800A03EC (or -2146827284) means NAME_NOT_FOUND; in other words, you've asked for something, and Excel can't find it.

This is a generic code, which can apply to lots of things it can't find e.g. using properties which aren't valid at that time like PivotItem.SourceNameStandard throws this when a PivotItem doesn't have a filter applied. Worksheets["BLAHBLAH"] throws this, when the sheet doesn't exist etc. In general, you are asking for something with a specific name and it doesn't exist. As for why, that will taking some digging on your part.

Check your sheet definitely does have the Range you are asking for, or that the .CellName is definitely giving back the name of the range you are asking for.

How to make a div fill a remaining horizontal space?

I ran into this same problem trying to layout some jqueryUI controls. Although the common philosophy now is "use DIV instead of TABLE", I found in my case using TABLE worked much better. In particular, if you need to have straightforward alignment within the two elements (e.g., vertical centering, horizontal centering, etc.) the options available with TABLE give simple, intuitive controls for this.

Here's my solution:

  <title>Sample solution for fixed left, variable right layout</title>
  <style type="text/css">
    #controls {
      width: 100%;
    #RightSide {

<div id="controls">
  <table border="0" cellspacing="2" cellpadding="0">
      <TD width="99%" ALIGN="CENTER">
        <div id="RightSide">Right</div>

Getting the current date in visual Basic 2008

If you need exact '/' delimiters, for example: 09/20/2013 rather than 09.20.2013, use escape sequence '/':

Dim regDate As Date = Date.Now()
Dim strDate As String = regDate.ToString("MM\/dd\/yyyy")

How to mount a single file in a volume

For me, the issue was that I had a broken symbolic link on the file I was trying to mount into the container

jQuery ajax post file field

I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)

function verify1() {
        type: 'POST',
        data: new FormData($("#infoForm1")[0]),
        processData: false, 
        contentType: false, 
        success: function(returnval) {

Just print the file details and check. You will get Output. If error let me know.

HTTP GET request in JavaScript?

In jQuery:

    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

If you are not limited to just a camera which wasn't in one of your constraints perhaps you can move to using a range sensor like the Xbox Kinect. With this you can perform depth and colour based matched segmentation of the image. This allows for faster separation of objects in the image. You can then use ICP matching or similar techniques to even match the shape of the can rather then just its outline or colour and given that it is cylindrical this may be a valid option for any orientation if you have a previous 3D scan of the target. These techniques are often quite quick especially when used for such a specific purpose which should solve your speed problem.

Also I could suggest, not necessarily for accuracy or speed but for fun you could use a trained neural network on your hue segmented image to identify the shape of the can. These are very fast and can often be up to 80/90% accurate. Training would be a little bit of a long process though as you would have to manually identify the can in each image.

Set drawable size programmatically

i didn't have time to dig why the setBounds() method is not working on bitmap drawable as expected but i have little tweaked @androbean-studio solution to do what setBounds should do...

 * Created by ceph3us on 23.05.17.
 * file belong to
 * this class wraps drawable and forwards draw canvas
 * on it wrapped instance by using its defined bounds
public class WrappedDrawable extends Drawable {

    private final Drawable _drawable;
    protected Drawable getDrawable() {
        return _drawable;

    public WrappedDrawable(Drawable drawable) {
        _drawable = drawable;

    public void setBounds(int left, int top, int right, int bottom) {
        //update bounds to get correctly
        super.setBounds(left, top, right, bottom);
        Drawable drawable = getDrawable();
        if (drawable != null) {
            drawable.setBounds(left, top, right, bottom);

    public void setAlpha(int alpha) {
        Drawable drawable = getDrawable();
        if (drawable != null) {

    public void setColorFilter(ColorFilter colorFilter) {
        Drawable drawable = getDrawable();
        if (drawable != null) {

    public int getOpacity() {
        Drawable drawable = getDrawable();
        return drawable != null
                ? drawable.getOpacity()
                : PixelFormat.UNKNOWN;

    public void draw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (drawable != null) {

    public int getIntrinsicWidth() {
        Drawable drawable = getDrawable();
        return drawable != null
                ? drawable.getBounds().width()
                : 0;

    public int getIntrinsicHeight() {
        Drawable drawable = getDrawable();
        return drawable != null ?
                : 0;


// get huge drawable 
final Drawable drawable = resources.getDrawable(R.drawable.g_logo);
// create our wrapper           
WrappedDrawable wrappedDrawable = new WrappedDrawable(drawable);
// set bounds on wrapper 
// use wrapped drawable 
Button.setCompoundDrawablesWithIntrinsicBounds(wrappedDrawable ,null, null, null);


before: enter image description here after: enter image description here

Math constant PI value in C

In C Pi is defined in math.h: #define M_PI 3.14159265358979323846

Getting list of tables, and fields in each, in a database


SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS for get all table name. Try it on sqlserver,

C# 'or' operator?

The single " | " operator will evaluate both sides of the expression.

    if (ActionsLogWriter.Close | ErrorDumpWriter.Close == true)
    // Do stuff here

The double operator " || " will only evaluate the left side if the expression returns true.

    if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
    // Do stuff here

C# has many similarities to C++ but their still are differences between the two languages ;)

Remove scroll bar track from ScrollView in Android

Solved my problem by adding this to my ListView:


state machines tutorials

State machines are very simple in C if you use function pointers.

Basically you need 2 arrays - one for state function pointers and one for state transition rules. Every state function returns the code, you lookup state transition table by state and return code to find the next state and then just execute it.

int entry_state(void);
int foo_state(void);
int bar_state(void);
int exit_state(void);

/* array and enum below must be in sync! */
int (* state[])(void) = { entry_state, foo_state, bar_state, exit_state};
enum state_codes { entry, foo, bar, end};

enum ret_codes { ok, fail, repeat};
struct transition {
    enum state_codes src_state;
    enum ret_codes   ret_code;
    enum state_codes dst_state;
/* transitions from end state aren't needed */
struct transition state_transitions[] = {
    {entry, ok,     foo},
    {entry, fail,   end},
    {foo,   ok,     bar},
    {foo,   fail,   end},
    {foo,   repeat, foo},
    {bar,   ok,     end},
    {bar,   fail,   end},
    {bar,   repeat, foo}};

#define EXIT_STATE end
#define ENTRY_STATE entry

int main(int argc, char *argv[]) {
    enum state_codes cur_state = ENTRY_STATE;
    enum ret_codes rc;
    int (* state_fun)(void);

    for (;;) {
        state_fun = state[cur_state];
        rc = state_fun();
        if (EXIT_STATE == cur_state)
        cur_state = lookup_transitions(cur_state, rc);

    return EXIT_SUCCESS;

I don't put lookup_transitions() function as it is trivial.

That's the way I do state machines for years.

Check if a string matches a regex in Bash script

You can use the test construct, [[ ]], along with the regular expression match operator, =~, to check if a string matches a regex pattern.

For your specific case, you can write:

[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"

Or more a accurate test:

[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
#           |^^^^^^^^ ^^^^^^ ^^^^^^  ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
#           |   |     ^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^ |
#           |   |          |                   |              |
#           |   |           \                  |              |
#           | --year--   --month--           --day--          |
#           |          either 01...09      either 01..09     end of line
# start of line            or 10,11,12         or 10..29
#                                              or 30, 31

That is, you can define a regex in Bash matching the format you want. This way you can do:

[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"

where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.

In other shells you can use grep. If your shell is POSIX compliant, do

(echo "$date" | grep -Eq  ^regex$) && echo "matched" || echo "did not match"

In fish, which is not POSIX-compliant, you can do

echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"

What is the difference between sscanf or atoi to convert a string to an integer?

When there is no concern about invalid string input or range issues, use the simplest: atoi()

Otherwise, the method with best error/range detection is neither atoi(), nor sscanf(). This good answer all ready details the lack of error checking with atoi() and some error checking with sscanf().

strtol() is the most stringent function in converting a string to int. Yet it is only a start. Below are detailed examples to show proper usage and so the reason for this answer after the accepted one.

// Over-simplified use
int strtoi(const char *nptr) {
  int i = (int) strtol(nptr, (char **)NULL, 10);
  return i; 

This is the like atoi() and neglects to use the error detection features of strtol().

To fully use strtol(), there are various features to consider:

  1. Detection of no conversion: Examples: "xyz", or "" or "--0"? In these cases, endptr will match nptr.

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (nptr == endptr) return FAIL_NO_CONVERT;
  2. Should the whole string convert or just the leading portion: Is "123xyz" OK?

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (*endptr != '\0') return FAIL_EXTRA_JUNK;
  3. Detect if value was so big, the the result is not representable as a long like "999999999999999999999999999999".

    errno = 0;
    long L = strtol(nptr, &endptr, 10);
    if (errno == ERANGE) return FAIL_OVERFLOW;
  4. Detect if the value was outside the range of than int, but not long. If int and long have the same range, this test is not needed.

    long L = strtol(nptr, &endptr, 10);
    if (L < INT_MIN || L > INT_MAX) return FAIL_INT_OVERFLOW;
  5. Some implementations go beyond the C standard and set errno for additional reasons such as errno to EINVAL in case no conversion was performed or EINVAL The value of the Base parameter is not valid.. The best time to test for these errno values is implementation dependent.

Putting this all together: (Adjust to your needs)

#include <errno.h>
#include <stdlib.h>

int strtoi(const char *nptr, int *error_code) {
  char *endptr;
  errno = 0;
  long i = strtol(nptr, &endptr, 10);

  if (errno == ERANGE || i > INT_MAX || i < INT_MIN) {
    errno = ERANGE;
    i = i > 0 : INT_MAX : INT_MIN;
    *error_code = FAIL_INT_OVERFLOW;
  if (errno == ERANGE) {
    *error_code = FAIL_OVERFLOW;

  else if (endptr == nptr) {
    *error_code = FAIL_NO_CONVERT;
  } else if (*endptr != '\0') {
    *error_code = FAIL_EXTRA_JUNK;
  } else if (errno) {
  return (int) i;

Note: All functions mentioned allow leading spaces, an optional leading sign character and are affected by locale change. Additional code is required for a more restrictive conversion.

Note: Non-OP title change skewed emphasis. This answer applies better to original title "convert string to integer sscanf or atoi"

Select random lines from a file

Sort the file randomly and pick first 100 lines:

$ sort -R input | head -n 100 >output

conversion from infix to prefix

This is the algorithm using stack.
Just follow these simple steps.

1.Reverse the given infix expression.

2.Replace '(' with ')' and ')' with '(' in the reversed expression.

3.Now apply standard infix to postfix subroutine.

4.Reverse the founded postfix expression, this will give required prefix expression.

In case you find step 3 difficult consult where a worked out example is also given.

CardView Corner Radius

If you're setting the card background programmatically, make use you use cardView.setCardBackgroundColor() and not cardView.setBackgroundColor() and make sure use using app:cardPreventCornerOverlap="true" on the cardView.xml. That fixed it for me.

Btw, the above code (in quotations) is in Kotlin and not Java. Use the java equivalent if you're using Java. and

204 responses are sometimes used in AJAX to track clicks and page activity. In this case, the only information being passed to the server in the get request is a cookie and not specific information in request parameters, so this doesn't seem to be the case here.

It seems that is the server behind google search suggestions. When you visit, the cookie is passed to Perhaps this is to start up some kind of session on the server? Whatever the use, I doubt it's a very standard use.

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;


C++ alignment when printing cout <<

C++20 std::format options <, ^ and >

According to the following should hold:

// left: "42    "
std::cout << std::format("{:<6}", 42);

// right: "    42"
std::cout << std::format("{:>6}", 42);

// center: "  42  "
std::cout << std::format("{:^6}", 42);

More information at: std::string formatting like sprintf

How to find out which JavaScript events fired?

Just thought I'd add that you can do this in Chrome as well:

Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).

You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).

For example:

  • Right click on the upvote button to the left
  • Select inspect element
  • Collapse the styles section (section on the far right - double chevron)
  • Expand the event listeners option
  • Now you can see the events bound to the upvote
  • Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.

    Another option that is a bit different but surprisingly awesome is Visual Event:

    It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.

    AnonymousAndrew has also pointed out monitorEvents(window); here

    Copy Data from a table in one Database to another separate database

    Don't forget to insert SET IDENTITY_INSERT MobileApplication1 ON to the top, else you will get an error. This is for SQL Server

    SET IDENTITY_INSERT MOB.MobileApplication1 ON
    INSERT INTO [SERVER1].DB.MOB.MobileApplication1 m
    SELECT ma.MobileApplicationId,
    FROM [SERVER2].DB.MOB.MobileApplication2 ma

    Git Server Like GitHub?

    If you want pull requests, there are the open source projects of RhodeCode and GitLab and the paid Stash

    Convert an enum to List<string>

    I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

      public enum CancelReasonsEnum
        [Description("In rush")]
        [Description("Need more coffee")]
        [Description("Call me back in 5 minutes!")]

    In a helper class (HelperMethods) I created the following method:

     public static List<string> GetListOfDescription<T>() where T : struct
            Type t = typeof(T);
            return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();

    When you call this helper you will get the list of item descriptions.

     List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

    ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

     public static string GetDescription(this Enum value)
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name != null)
                FieldInfo field = type.GetField(name);
                if (field != null)
                    DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (attr != null)
                        return attr.Description;
            return null;
            /* how to use
                MyEnum x = MyEnum.NeedMoreCoffee;
                string description = x.GetDescription();

    How to apply a patch generated with git format-patch?

    Note: You can first preview what your patch will do:

    First the stats:

    git apply --stat a_file.patch

    Then a dry run to detect errors:

    git apply --check a_file.patch

    Finally, you can use git am to apply your patch as a commit. This also allows you to sign off an applied patch.
    This can be useful for later reference.

    git am --signoff < a_file.patch 

    See an example in this article:

    In your git log, you’ll find that the commit messages contain a “Signed-off-by” tag. This tag will be read by Github and others to provide useful info about how the commit ended up in the code.


    Fastest Way of Inserting in Entity Framework

    SqlBulkCopy is super quick

    This is my implementation:

    // at some point in my calling code, I will call:
    var myDataTable = CreateMyDataTable();
    myDataTable.Rows.Add(Guid.NewGuid,tableHeaderId,theName,theValue); // e.g. - need this call for each row to insert
    var efConnectionString = ConfigurationManager.ConnectionStrings["MyWebConfigEfConnection"].ConnectionString;
    var efConnectionStringBuilder = new EntityConnectionStringBuilder(efConnectionString);
    var connectionString = efConnectionStringBuilder.ProviderConnectionString;
    BulkInsert(connectionString, myDataTable);
    private DataTable CreateMyDataTable()
        var myDataTable = new DataTable { TableName = "MyTable"};
    // this table has an identity column - don't need to specify that
        myDataTable.Columns.Add("MyTableRecordGuid", typeof(Guid));
        myDataTable.Columns.Add("MyTableHeaderId", typeof(int));
        myDataTable.Columns.Add("ColumnName", typeof(string));
        myDataTable.Columns.Add("ColumnValue", typeof(string));
        return myDataTable;
    private void BulkInsert(string connectionString, DataTable dataTable)
        using (var connection = new SqlConnection(connectionString))
            SqlTransaction transaction = null;
                transaction = connection.BeginTransaction();
                using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
                    sqlBulkCopy.DestinationTableName = dataTable.TableName;
                    foreach (DataColumn column in dataTable.Columns) {
                        sqlBulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
            catch (Exception)

    How to match, but not capture, part of a regex?

    By far the simplest (works for python) is '123-(apple|banana)-?456'.

    How to modify a text file?

    The fileinput module of the Python standard library will rewrite a file inplace if you use the inplace=1 parameter:

    import sys
    import fileinput
    # replace all occurrences of 'sit' with 'SIT' and insert a line after the 5th
    for i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):
        sys.stdout.write(line.replace('sit', 'SIT'))  # replace 'sit' and write
        if i == 4: sys.stdout.write('\n')  # write a blank line after the 5th line

    SOAP or REST for Web Services?

    I am looking at the same, and i think, they are different tools for different problems.

    Simple Object Access Protocol (SOAP) standard an XML language defining a message architecture and message formats, is used by Web services it contain a description of the operations. WSDL is an XML-based language for describing Web services and how to access them. will run on SMTP,HTTP,FTP etc. Requires middleware support, well defined mechanisam to define services like WSDL+XSD, WS-Policy SOAP will return XML based data SOAP provide standards for security and reliability

    Representational State Transfer (RESTful) web services. they are second generation Web Services. RESTful web services, communicate via HTTP than SOAP-based services and do not require XML messages or WSDL service-API definitions. for REST no middleware is required only HTTP support is needed.WADL Standard, REST can return XML, plain text, JSON, HTML etc

    It is easier for many types of clients to consume RESTful web services while enabling the server side to evolve and scale. Clients can choose to consume some or all aspects of the service and mash it up with other web-based services.

    1. REST uses standard HTTP so it is simplerto creating clients, developing APIs
    2. REST permits many different data formats like XML, plain text, JSON, HTML where as SOAP only permits XML.
    3. REST has better performance and scalability.
    4. Rest and can be cached and SOAP can't
    5. Built-in error handling where SOAP has No error handling
    6. REST is particularly useful PDA and other mobile devices.

    REST is services are easy to integrate with existing websites.

    SOAP has set of protocols, which provide standards for security and reliability, among other things, and interoperate with other WS conforming clients and servers. SOAP Web services (such as JAX-WS) are useful in handling asynchronous processing and invocation.

    For Complex API's SOAP will be more usefull.

    OR is not supported with CASE Statement in SQL Server

    select id,phno,case gender
    when 'G' then 'M'
    when 'L' then 'F'
    'No gender'
    as gender 
    from contacts

    Using multiple delimiters in awk

    I see many perfect answers are up on the board, but still would like to upload my piece of code too,

    awk -F"/" '{print $3 " " $5 " " $7}' sam | sed 's/ cat.* =//g'

    Why does configure say no C compiler found when GCC is installed?

    Sometime gcc had created as /usr/bin/gcc32. so please create a ln -s /usr/bin/gcc32 /usr/bin/gcc and then compile that ./configure.

    Subset data.frame by date

    Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:

     EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")

    After that you can do this:

     EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )

    R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.

    How to pass multiple parameters to a get method in ASP.NET Core

    Why not using just one controller action?

    public string Get(int? id, string firstName, string lastName, string address)
       if (id.HasValue)
       else if (string.IsNullOrEmpty(address))
          GetByName(firstName, lastName);
          GetByNameAddress(firstName, lastName, address);

    Another option is to use attribute routing, but then you'd need to have a different URL format:

    public string Get(int id)
    public string Get(string firstName, string lastName, string address)

    stringstream, string, and char* conversion confusion

    stringstream.str() returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That's why your code prints garbage.

    You could copy that temporary string object to some other string object and take the C string from that one:

    const std::string tmp = stringstream.str();
    const char* cstr = tmp.c_str();

    Note that I made the temporary string const, because any changes to it might cause it to re-allocate and thus render cstr invalid. It is therefor safer to not to store the result of the call to str() at all and use cstr only until the end of the full expression:

    use_c_str( stringstream.str().c_str() );

    Of course, the latter might not be easy and copying might be too expensive. What you can do instead is to bind the temporary to a const reference. This will extend its lifetime to the lifetime of the reference:

      const std::string& tmp = stringstream.str();   
      const char* cstr = tmp.c_str();

    IMO that's the best solution. Unfortunately it's not very well known.

    Angular2: custom pipe could not be found

    I encountered a similar issue, but putting it in my page’s module didn’t work.

    I had created a component, which needed a pipe. This component was declared and exported in a ComponentsModule file, which holds all of the app’s custom components.

    I had to put my PipesModule in my ComponentsModule as an import, in order for these components to use these pipes and not in the page’s module using that component.

    Credits: enter link description here Answer by: tumain using a form to insert data into an sql server table

    Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

        <form id="form1" runat="server">
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <br />
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Button" />

    Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

    If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

    Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

    The button is a web control Button Add a Click event to the button call it Button1Click:

    void Button1Click(Object sender,EventArgs e) { }

    Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

    So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

    String firstBox = TextBox1.Text;

    In the same way you can populate the objects when event occur.

    Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

    How do I enable NuGet Package Restore in Visual Studio?

    Ivan Branets 's solution is essentially what fixed this for me, but some more details could be shared.

    In my case, I was in VS 2015 using Auto Package restore and TFS. This is all pretty default stuff.

    The problem was that when another developer tried to get a solution from TFS, some packages were not fully getting restored. (Why, that I'm not quite sure yet.) But the packages folder contained a folder for the reference and the NuGet package, but it wasn't getting expanded (say a lib folder containing a .dll was missing.) This half there, but not really quite right concept was preventing the package from being restored.

    You'll recognize this because the reference will have a yellow exclamation point about not being resolved.

    So, the solution of deleting the folder within packages removes the package restore blocking issue. Then you can right click at the top solution level to get the option to restore packages, and now it should work.

    How to read from a text file using VBScript?

    Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
    Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
    Dim inFile: Set inFile = obj.OpenTextFile("out.txt")
    ' Read file
    Dim strRetVal : strRetVal = inFile.ReadAll
    ' Write file
    outFile.write (strRetVal)

    How to change column order in a table using sql query in sql server 2005?

    Try this command:

    alter table students modify age int(5) first; 

    This will change the position of age to the first position.

    Oracle SQL convert date format from DD-Mon-YY to YYYYMM

    As offer_date is an number, and is of lower accuracy than your real dates, this may work...
    - Convert your real date to a string of format YYYYMM
    - Conver that value to an INT
    - Compare the result you your offer_date

        offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
    AND offer_rate > 0 

    Also, by doing all the manipulation on the create_date you only do the processing on one value.

    Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

    How to parse a CSV in a Bash script?

    As an alternative to cut- or awk-based one-liners, you could use the specialized csvtool aka ocaml-csv:

    $ csvtool -t ',' col "$index" - < csvfile | grep "$value"

    According to the docs, it handles escaping, quoting, etc.

    php variable in html no other way than: <?php echo $var; ?>

    I really think you should adopt Smarty template engine as a standard php lib for your projects.

    Name: {$name|capitalize}<br>

    Java Comparator class to sort arrays

    The answer from @aioobe is excellent. I just want to add another way for Java 8.

    int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
    Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);

    For me it's intuitive and easy to remember with Java 8 syntax.

    How can I use Guzzle to send a POST request in JSON?

    I use the following code that works very reliably.

    The JSON data is passed in the parameter $request, and the specific request type passed in the variable $searchType.

    The code includes a trap to detect and report an unsuccessful or invalid call which will then return false.

    If the call is sucessful then json_decode ($result->getBody(), $return=true) returns an array of the results.

        public function callAPI($request, $searchType) {
        $guzzleClient = new GuzzleHttp\Client(["base_uri" => ""]);
        try {
            $result = $guzzleClient->post( $searchType, ["json" => $request]);
        } catch (Exception $e) {
            $error = $e->getMessage();
            $error .= '<pre>'.print_r($request, $return=true).'</pre>';
            $error .= 'No returnable data';
            Event::logError(__LINE__, __FILE__, $error);
            return false;
        return json_decode($result->getBody(), $return=true);

    Valid characters of a hostname?

    Checkout this wiki, specifically the section Restrictions on valid host names

    Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, "" is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

    The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

    Change WPF window background image in C# code

    Uri resourceUri = new Uri(@"/cCleaner;component/Images/cleanerblack.png", UriKind.Relative);
                StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
                BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
                var brush = new ImageBrush();
                brush.ImageSource = temp;
                frame8.Background = brush;

    Failed to execute 'createObjectURL' on 'URL':

    If you are using ajax, it is possible to add the options xhrFields: { responseType: 'blob' }:

      url: 'yourURL',
      type: 'POST',
      data: yourData,
      xhrFields: { responseType: 'blob' },
      success: function (data, textStatus, jqXHR) {
        let src = window.URL.createObjectURL(data);

    Simple way to count character occurrences in a string

    This is simple code, but of course a little bit slower.

    String s = ...;
    int countDollar = s.length()-s.replaceAll("\\$","").length();
    int counta = s.length()-s.replaceAll("a","").length();

    An even better answer is here in a duplicate question

    What does body-parser do with express?

    Keep it simple :

    • if you used post so you will need the body of the request, so you will need body-parser.

    • No need to install body-parser with express, but you have to use it if you will receive post request.

      app.use(bodyParser.urlencoded({ extended: false }));

      { extended: false } false meaning, you do not have nested data inside your body object.

      Note that: the request data embedded within the request as a body Object.

    What does "Changes not staged for commit" mean

    What worked for me was to go to the root folder, where .git/ is. I was inside one the child folders and got there error.

    VBA (Excel) Initialize Entire Array without Looping

    For VBA you need to initialise in two lines.

    Sub TestArray()
    Dim myArray
    myArray = Array(1, 2, 4, 8)
    End Sub

    How to assign string to bytes array

    Arrays are values... slices are more like pointers. That is [n]type is not compatible with []type as they are fundamentally two different things. You can get a slice that points to an array by using arr[:] which returns a slice that has arr as it's backing storage.

    One way to convert a slice of for example []byte to [20]byte is to actually allocate a [20]byte which you can do by using var [20]byte (as it's a value... no make needed) and then copy data into it:

    buf := make([]byte, 10)
    var arr [10]byte
    copy(arr[:], buf)

    Essentially what a lot of other answers get wrong is that []type is NOT an array.

    [n]T and []T are completely different things!

    When using reflect []T is not of kind Array but of kind Slice and [n]T is of kind Array.

    You also can't use map[[]byte]T but you can use map[[n]byte]T.

    This can sometimes be cumbersome because a lot of functions operate for example on []byte whereas some functions return [n]byte (most notably the hash functions in crypto/*). A sha256 hash for example is [32]byte and not []byte so when beginners try to write it to a file for example:

    sum := sha256.Sum256(data)

    they will get an error. The correct way of is to use


    However, what is it that you want? Just accessing the string bytewise? You can easily convert a string to []byte using:

    bytes := []byte(str)

    but this isn't an array, it's a slice. Also, byte != rune. In case you want to operate on "characters" you need to use rune... not byte.

    Loading local JSON file

    If you want to let the user select the local json file (anywhere on the filesystem), then the following solution works.

    It uses uses FileReader and JSON.parser (and no jquery).

    <form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">
        <h2>Json File</h2>
         <input type='file' id='fileinput'>
         <input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
    <script type="text/javascript">
      function loadFile() {
        var input, file, fr;
        if (typeof window.FileReader !== 'function') {
          alert("The file API isn't supported on this browser yet.");
        input = document.getElementById('fileinput');
        if (!input) {
          alert("Um, couldn't find the fileinput element.");
        else if (!input.files) {
          alert("This browser doesn't seem to support the `files` property of file inputs.");
        else if (!input.files[0]) {
          alert("Please select a file before clicking 'Load'");
        else {
          file = input.files[0];
          fr = new FileReader();
          fr.onload = receivedText;
        function receivedText(e) {
          let lines =;
          var newArr = JSON.parse(lines); 

    Here is a good intro on FileReader:

    Replace CRLF using powershell

    For CMD one line LF-only:

    powershell -NoProfile -command "((Get-Content 'prueba1.txt') -join \"`n\") + \"`n\" | Set-Content -NoNewline 'prueba1.txt'"

    so you can create a .bat

    What is let-* in Angular 2 templates?

    update Angular 5

    ngOutletContext was renamed to ngTemplateOutletContext

    See also


    Templates (<template>, or <ng-template> since 4.x) are added as embedded views and get passed a context.

    With let-col the context property $implicit is made available as col within the template for bindings. With let-foo="bar" the context property bar is made available as foo.

    For example if you add a template

    <ng-template #myTemplate let-col let-foo="bar">
    <!-- render above template with a custom context -->
    <ng-template [ngTemplateOutlet]="myTemplate"
                                               $implicit: 'some col value',
                                               bar: 'some bar value'

    See also this answer and ViewContainerRef#createEmbeddedView.

    *ngFor also works this way. The canonical syntax makes this more obvious

    <ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">

    where NgFor adds the template as embedded view to the DOM for each item of items and adds a few values (item, index, odd) to the context.

    See also Using $implict to pass multiple parameters

    JavaScript query string

    I like to keep it simple, readable and small.

    function searchToObject(search) {
        var pairs = search.substring(1).split("&"),
            obj = {}, pair;
        for (var i in pairs) {
            if (pairs[i] === "") continue;
            pair = pairs[i].split("=");
            obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
        return obj;


    searchToObject('?query=myvalue')['query']; // spits out: 'myvalue'

    Concatenate columns in Apache Spark DataFrame

    In my case, I wanted a Tab delimited row.

    from pyspark.sql import functions as F'|','_c1','_c2','_c3','_c4')).show()

    This worked well like a hot knife over butter.

    Javascript Array Alert

    If you want to see the array as an array, you can say


    instead of all those document.writes.

    However, if you want to display them cleanly, one per line, in your popup, do this:


    Assign variable value inside if-statement

    Yes, you can assign the value of variable inside if.

    I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===.

    It will be better if you do something like this:

    int v;
    if((v = someMethod()) != 0) 
       return true;

    How can I get last characters of a string

    Following script shows the result for get last 5 characters and last 1 character in a string using JavaScript:

    var testword='ctl03_Tabs1';
    var last5=testword.substr(-5); //Get 5 characters
    var last1=testword.substr(-1); //Get 1 character

    Output :

    Tabs1 // Got 5 characters

    1 // Got 1 character

    How can I change image source on click with jQuery?

    It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :

    $(function() {
       return false;

    Interesting question on the differences between prevent default and return false.

    In this case, return false will work just fine because the event doesn't need to be propagated.

    How do I make a Git commit in the past?

    To make a commit that looks like it was done in the past you have to set both GIT_AUTHOR_DATE and GIT_COMMITTER_DATE:

    GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git commit -m '...'

    where date -d'...' can be exact date like 2019-01-01 12:00:00 or relative like 5 months ago 24 days ago.

    To see both dates in git log use:

    git log --pretty=fuller

    This also works for merge commits:

    GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git merge <branchname> --no-ff

    How to dynamically insert a <script> tag via jQuery after page load?

    Here's the correct way to do it with modern (2014) JQuery:

    $(function () {
        .attr('type', 'text/javascript')
        .text('some script here')

    or if you really want to replace a div you could do:

    $(function () {
        .attr('type', 'text/javascript')
        .text('some script here')

    How to convert Integer to int?

    As already written elsewhere:

    • For Java 1.5 and later you don't need to do (almost) anything, it's done by the compiler.
    • For Java 1.4 and before, use Integer.intValue() to convert from Integer to int.

    BUT as you wrote, an Integer can be null, so it's wise to check that before trying to convert to int (or risk getting a NullPointerException).

    pstmt.setInt(1, (tempID != null ? tempID : 0));  // Java 1.5 or later


    pstmt.setInt(1, (tempID != null ? tempID.intValue() : 0));  // any version, no autoboxing  

    * using a default of zero, could also do nothing, show a warning or ...

    I mostly prefer not using autoboxing (second sample line) so it's clear what I want to do.

    Angular 4: How to include Bootstrap?

    Angular 6 CLI, just do:

    ng add @ng-bootstrap/schematics

    Get the data received in a Flask request

    Here's an example of posting form data to add a user to a database. Check request.method == "POST" to check if the form was submitted. Use keys from request.form to get the form data. Render an HTML template with a <form> otherwise. The fields in the form should have name attributes that match the keys in request.form.

    from flask import Flask, request, render_template
    app = Flask(__name__)
    @app.route("/user/add", methods=["GET", "POST"])
    def add_user():
        if request.method == "POST":
            user = User(
            return redirect(url_for("index"))
        return render_template("add_user.html")
    <form method="post">
        <label for="username">Username</label>
        <input type="text" name="username" id="username">
        <label for="email">Email</label>
        <input type="email" name="email" id="email">
        <input type="submit">

    Why is jquery's .ajax() method not sending my session cookie?

    After trying out the other solutions and still not getting it to work, I found out what the problem was in my case. I changed contentType from "application/json" to "text/plain".

    $.ajax(fullUrl, {
        type: "GET",
        contentType: "text/plain",
        xhrFields: {
             withCredentials: true
        crossDomain: true

    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.

    Add button to navigationbar programmatically

    Try this.It work for me. Add button to navigation bar programmatically, Also we set image to navigation bar button,

    Below is Code:-

      UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:
      [[UIImage imageNamed:@"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] 
      style:UIBarButtonItemStylePlain target:self action:@selector(SaveButtonClicked)];
        // Add save button code.

    How to retrieve data from sqlite database in android and display it in TextView

    You may use this following code actually it is rough but plz check it out

    db = openOrCreateDatabase("sms.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
    Cursor cc = db.rawQuery("SELECT * FROM datatable", null);
    final ArrayList<String> row1 = new ArrayList<String>();
    final ArrayList<String> row2 = new ArrayList<String>();
    if(cc!=null) {
        for (int i=0; i<cc.getCount(); i++) {
        String number  = cc.getString(0);
        String message = cc.getString(1);
        final EditText et3 = (EditText) findViewById(;
        final EditText et4 = (EditText) findViewById(;
        Button bt1 = (Button) findViewById(;
        bt1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                switch (v.getId()) {

    Maven: How to change path to target directory from command line?

    You should use profiles.


    And start maven with your profile

    mvn compile -PotherOutputDir

    If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :


    And compile like this :

    mvn compile -DbuildDirectory=test

    That's because you can't change the target directory by using

    Currency format for display

    If you just have the currency symbol and the number of decimal places, you can use the following helper function, which respects the symbol/amount order, separators etc, only changing the currency symbol itself and the number of decimal places to display to.

    public static string FormatCurrency(string currencySymbol, Decimal currency, int decPlaces)
        NumberFormatInfo localFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
        localFormat.CurrencySymbol = currencySymbol;
        localFormat.CurrencyDecimalDigits = decPlaces;
        return currency.ToString("c", localFormat);

    Index Error: list index out of range (Python)

    Generally it means that you are providing an index for which a list element does not exist.

    E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

    How to populate/instantiate a C# array with a single value?

    Here's another version for us Framework users abandoned by Microsoft. It is 4 times as fast as Array.Clear and faster than Panos Theof's solution and Eric J's and Petar Petrov's parallel one - up to two times as fast for large arrays.

    First I want to present you the function's ancestor, because that makes it easier to understand the code. Performance-wise this is pretty much on par with Panos Theof's code, and for some things that may already be enough:

    public static void Fill<T> (T[] array, int count, T value, int threshold = 32)
        if (threshold <= 0)
            throw new ArgumentException("threshold");
        int current_size = 0, keep_looping_up_to = Math.Min(count, threshold);
        while (current_size < keep_looping_up_to)
            array[current_size++] = value;
        for (int at_least_half = (count + 1) >> 1; current_size < at_least_half; current_size <<= 1)
            Array.Copy(array, 0, array, current_size, current_size);
        Array.Copy(array, 0, array, current_size, count - current_size);

    As you can see, this is based on repeated doubling of the already-initialised part. This is simple and efficient, but it runs afoul of modern memory architectures. Hence was born a version that uses doubling only to create a cache-friendly seed block, which is then blasted iteratively over the target area:

    const int ARRAY_COPY_THRESHOLD = 32;  // 16 ... 64 work equally well for all tested constellations
    const int L1_CACHE_SIZE = 1 << 15;
    public static void Fill<T> (T[] array, int count, T value, int element_size)
        int current_size = 0, keep_looping_up_to = Math.Min(count, ARRAY_COPY_THRESHOLD);
        while (current_size < keep_looping_up_to)
            array[current_size++] = value;
        int block_size = L1_CACHE_SIZE / element_size / 2;
        int keep_doubling_up_to = Math.Min(block_size, count >> 1);
        for ( ; current_size < keep_doubling_up_to; current_size <<= 1)
            Array.Copy(array, 0, array, current_size, current_size);
        for (int enough = count - block_size; current_size < enough; current_size += block_size)
            Array.Copy(array, 0, array, current_size, block_size);
        Array.Copy(array, 0, array, current_size, count - current_size);

    Note: the earlier code needed (count + 1) >> 1 as limit for the doubling loop to ensure that the final copy operation has enough fodder to cover all that is left. This would not be the case for odd counts if count >> 1 were to be used instead. For the current version this is of no significance since the linear copy loop will pick up any slack.

    The size of an array cell must be passed as a parameter because - the mind boggles - generics aren't allowed to use sizeof unless they use a constraint (unmanaged) that may or may not become available in the future. Wrong estimates are not a big deal but performance is best if the value is accurate, for the following reasons:

    • Underestimating the element size can lead to block sizes greater than half the L1 cache, hence increasing the likelihood of copy source data getting evicted from L1 and having to be re-fetched from slower cache levels.

    • Overestimating the element size results in under-utilisation of the CPU's L1 cache, meaning the linear block copy loop gets executed more often than it would be with optimal utilisation. Thus, more of the fixed loop/call overhead is incurred than strictly necessary.

    Here's a benchmark pitting my code against Array.Clear and the other three solutions mentioned previously. The timings are for filling integer arrays (Int32[]) of the given sizes. In order to reduce variation caused by cache vagaries etc. each test was executed twice, back to back, and the timings were taken for the second execution.

    array size   Array.Clear      Eric J.   Panos Theof  Petar Petrov   Darth Gizka
         1000:       0,7 µs        0,2 µs        0,2 µs        6,8 µs       0,2 µs 
        10000:       8,0 µs        1,4 µs        1,2 µs        7,8 µs       0,9 µs 
       100000:      72,4 µs       12,4 µs        8,2 µs       33,6 µs       7,5 µs 
      1000000:     652,9 µs      135,8 µs      101,6 µs      197,7 µs      71,6 µs 
     10000000:    7182,6 µs     4174,9 µs     5193,3 µs     3691,5 µs    1658,1 µs 
    100000000:   67142,3 µs    44853,3 µs    51372,5 µs    35195,5 µs   16585,1 µs 

    Should the performance of this code not be sufficient then a promising avenue would be parallelising the linear copy loop (with all threads using the same source block), or our good old friend P/Invoke.

    Note: clearing and filling of blocks is normally done by runtime routines that branch to highly specialised code using MMX/SSE instructions and whatnot, so in any decent environment one would simply call the respective moral equivalent of std::memset and be assured of professional performance levels. IOW, by rights the library function Array.Clear should leave all our hand-rolled versions in the dust. The fact that it is the other way around shows how far out of whack things really are. Same goes for having to roll one's own Fill<> in the first place, because it is still only in Core and Standard but not in the Framework. .NET has been around for almost twenty years now and we still have to P/Invoke left and right for the most basic stuff or roll our own...

    String contains another two strings

    string d = "You hit someone for 50 damage";
    string a = "damage";
    string b = "someone";
    string c = "you";
    if(d.Contains(a) && d.Contains(b))
        Console.WriteLine(" " + d);

    Cannot resolve symbol 'AppCompatActivity'

    This happens because of one the following reasons:

    1. You do not have the SDK API installed (this was my problem)
    2. Your project/Android Studio doesn’t know where the needed files are
    3. Your project references an outdated compile version that does not support AppCompatActivity
    4. There is a typo

    Possible solutions:

    1. Check your .gradle file to make sure you’re not referencing an outdated version. AppCompatActivity was added in version 25.1.0 and belongs to Maven artifact, so do not use any version earlier than this. In your build.gradle (Module: app) file you should have the dependency listed:

      dependencies { compile '' }

      You may be using a different version, but just make sure you have listed the dependency.

    2. Open the SDK manager and download every API 7 or newer. If you were missing the needed API it will fix that issue, and downloading all the newer API’s can save you some hassle later on as well.

    3. Check for typos in your import statement. Make sure it doesn’t say “AppCompactActivity” instead of “AppCompatActivity”.
    4. Resync your project (File >Sync project with Gradle files)
    5. Rebuild your project (Build >rebuild)
    6. Clean your project (Build >clean project)
    7. Close and restart Android Studio
    8. Update Android Studio
    9. Regenerate your libraries folder – In Android Studio, view your files in project view. Find the folder YourProjectName >.idea >libraries. Rename the folder to “libraries_delete_me”. Close and reopen Android Studio. Open your project again and the libraries folder should be regenerated with all of the files; you can now delete the “libraries_delete_me” folder.

    SQL Add foreign key to existing column

    If the table has already been created:

    First do:

    ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);


    ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);

    Android studio - Failed to find target android-18

    I've had a similar problem occurr when I had both Eclipse, Android Studio and the standalone Android SDK installed (the problem lied where the AVD Manager couldn't find target images). I had been using Eclipse for Android development but have moved over to Android Studio, and quickly found that Android Studio couldn't find my previously created AVDs.

    The problem could potentially lie in that Android Studio is looking at it's own Android SDK (found in C:\Users\username\AppData\Local\Android\android-studio\sdk) and not a previously installed standalone SDK, which I had installed at C:\adt\sdk.

    Renaming Android Studio's SDK folder, in C:\Users... (only rename it, just in case things break) then creating a symbolic link between the Android Studio SDK location and a standalone Android SDK fixes this issue.

    I also used the Link Shell Extension ( just to take the tedium out of creating symbolic links.

    Removing carriage return and new-line from the end of a string in c#

    string k = "This is my\r\nugly string. I want\r\nto change this. Please \r\n help!";
    k = System.Text.RegularExpressions.Regex.Replace(k, @"\r\n+", " ");

    How to parse string into date?

    CONVERT(DateTime, ExpireDate, 121) AS ExpireDate

    will do what is needed, result:

    2012-04-24 00:00:00.000

    CSS: Change image src on img:hover

    Here is an alternate approach using pure CSS. The idea is to include both the images in the HTML markup and have these displayed or hidden accordingly on :hover


       <img src="" /> 
       <img src="" />


    a img:last-child {
      display: none;  
    a:hover img:last-child {
      display: block;  
    a:hover img:first-child {
      display: none;  


    Note that the images used are of the same dimensions for proper display. Also, these images file sizes are quite small so loading multiple is not an issue in this case but may be if you are looking to toggle display of large sized images.

    Connecting client to server using

    You need to make sure that you add forward slash before your link to

    <script src="/"></script>

    Then in the view/controller just do:

    var socket = io.connect()

    That should solve your problem.

    Getting all types in a namespace via reflection

    Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.GetExportedTypes() checking the value of type.Namespace. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.GetAssemblies()

    remove table row with specific id


    Might not work with numeric id's though.

    Undefined behavior and sequence points

    C++98 and C++03

    This answer is for the older versions of the C++ standard. The C++11 and C++14 versions of the standard do not formally contain 'sequence points'; operations are 'sequenced before' or 'unsequenced' or 'indeterminately sequenced' instead. The net effect is essentially the same, but the terminology is different.

    Disclaimer : Okay. This answer is a bit long. So have patience while reading it. If you already know these things, reading them again won't make you crazy.

    Pre-requisites : An elementary knowledge of C++ Standard

    What are Sequence Points?

    The Standard says

    At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. (§1.9/7)

    Side effects? What are side effects?

    Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).

    For example:

    int x = y++; //where y is also an int

    In addition to the initialization operation the value of y gets changed due to the side effect of ++ operator.

    So far so good. Moving on to sequence points. An alternation definition of seq-points given by the comp.lang.c author Steve Summit:

    Sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.

    What are the common sequence points listed in the C++ Standard ?

    Those are:

    • at the end of the evaluation of full expression (§1.9/16) (A full-expression is an expression that is not a subexpression of another expression.)1

      Example :

      int a = 5; // ; is a sequence point here
    • in the evaluation of each of the following expressions after the evaluation of the first expression (§1.9/18) 2

      • a && b (§5.14)
      • a || b (§5.15)
      • a ? b : c (§5.16)
      • a , b (§5.18) (here a , b is a comma operator; in func(a,a++) , is not a comma operator, it's merely a separator between the arguments a and a++. Thus the behaviour is undefined in that case (if a is considered to be a primitive type))
    • at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body (§1.9/17).

    1 : Note : the evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument

    2 : The operators indicated are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation and the operands form an argument list, without an implied sequence point between them.

    What is Undefined Behaviour?

    The Standard defines Undefined Behaviour in Section §1.3.12 as

    behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements 3.

    Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior.

    3 : permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with- out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

    In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.

    What is the relation between Undefined Behaviour and Sequence Points?

    Before I get into that you must know the difference(s) between Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behaviour.

    You must also know that the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.

    For example:

    int x = 5, y = 6;
    int z = x++ + y++; //it is unspecified whether x++ or y++ will be evaluated first.

    Another example here.

    Now the Standard in §5/4 says

    • 1) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

    What does it mean?

    Informally it means that between two sequence points a variable must not be modified more than once. In an expression statement, the next sequence point is usually at the terminating semicolon, and the previous sequence point is at the end of the previous statement. An expression may also contain intermediate sequence points.

    From the above sentence the following expressions invoke Undefined Behaviour:

    i++ * ++i;   // UB, i is modified more than once btw two SPs
    i = ++i;     // UB, same as above
    ++i = 2;     // UB, same as above
    i = ++i + 1; // UB, same as above
    ++++++i;     // UB, parsed as (++(++(++i)))
    i = (i, ++i, ++i); // UB, there's no SP between `++i` (right most) and assignment to `i` (`i` is modified more than once btw two SPs)

    But the following expressions are fine:

    i = (i, ++i, 1) + 1; // well defined (AFAIK)
    i = (++i, i++, i);   // well defined 
    int j = i;
    j = (++i, i++, j*i); // well defined

    • 2) Furthermore, the prior value shall be accessed only to determine the value to be stored.

    What does it mean? It means if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.

    For example in i = i + 1 all the access of i (in L.H.S and in R.H.S) are directly involved in computation of the value to be written. So it is fine.

    This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.

    Example 1:

    std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2

    Example 2:

    a[i] = i++ // or a[++i] = i or a[i++] = ++i etc

    is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. So the behaviour is undefined.

    Example 3 :

    int x = i + i++ ;// Similar to above

    Follow up answer for C++11 here.

    Find and copy files

    i faced an issue something like this...

    Actually, in two ways you can process find command output in copy command

    1. If find command's output doesn't contain any space i.e if file name doesn't contain space in it then you can use below mentioned command:

      Syntax: find <Path> <Conditions> | xargs cp -t <copy file path>

      Example: find -mtime -1 -type f | xargs cp -t inner/

    2. But most of the time our production data files might contain space in it. So most of time below mentioned command is safer:

      Syntax: find <path> <condition> -exec cp '{}' <copy path> \;

      Example find -mtime -1 -type f -exec cp '{}' inner/ \;

    In the second example, last part i.e semi-colon is also considered as part of find command, that should be escaped before press the enter button. Otherwise you will get an error something like this

    find: missing argument to `-exec'

    In your case, copy command syntax is wrong in order to copy find file into /home/shantanu/tosend. The following command will work:

    find /home/shantanu/processed/ -name '*2011*.xml' -exec cp  {} /home/shantanu/tosend \;

    How to validate an OAuth 2.0 access token for a resource server?

    OAuth v2 specs indicates:

    Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications.

    My Authorisation Server has a webservice (SOAP) endpoint that allows the Resource Server to know whether the access_token is valid.

    How to convert java.lang.Object to ArrayList?

    Rather Cast It to an Object Array.

    Object obj2 = from some source . . ;
    Object[] objects=(Object[])obj2;

    When do you use Java's @Override annotation and why?

    Whenever a method overrides another method, or a method implements a signature in an interface.

    The @Override annotation assures you that you did in fact override something. Without the annotation you risk a misspelling or a difference in parameter types and number.

    Reasons for using the set.seed function

    set.seed is a base function that it is able to generate (every time you want) together other functions (rnorm, runif, sample) the same random value.

    Below an example without set.seed

    > set.seed(NULL)
    > rnorm(5)
    [1]  1.5982677 -2.2572974  2.3057461  0.5935456  0.1143519
    > rnorm(5)
    [1]  0.15135371  0.20266228  0.95084266  0.09319339 -1.11049182
    > set.seed(NULL)
    > runif(5)
    [1] 0.05697712 0.31892399 0.92547023 0.88360393 0.90015169
    > runif(5)
    [1] 0.09374559 0.64406494 0.65817582 0.30179009 0.19760375
    > set.seed(NULL)
    > sample(5)
    [1] 5 4 3 1 2
    > sample(5)
    [1] 2 1 5 4 3

    Below an example with set.seed

    > set.seed(123)
    > rnorm(5)
    [1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774
    > set.seed(123)
    > rnorm(5)
    [1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774
    > set.seed(123)
    > runif(5)
    [1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
    > set.seed(123)
    > runif(5)
    [1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
    > set.seed(123)
    > sample(5)
    [1] 3 2 5 4 1
    > set.seed(123)
    > sample(5)
    [1] 3 2 5 4 1

    Is there a way to call a stored procedure with Dapper?

    Same from above, bit more detailed

    Using .Net Core


    public class TestController : Controller
        private string connectionString;
        public IDbConnection Connection
            get { return new SqlConnection(connectionString); }
        public TestController()
            connectionString = @"Data Source=OCIUZWORKSPC;Initial Catalog=SocialStoriesDB;Integrated Security=True";
        public JsonResult GetEventCategory(string q)
            using (IDbConnection dbConnection = Connection)
                var categories = dbConnection.Query<ResultTokenInput>("GetEventCategories", new { keyword = q },
        commandType: CommandType.StoredProcedure).FirstOrDefault();
                return Json(categories);
        public class ResultTokenInput
            public int ID { get; set; }
            public string name { get; set; }            

    Stored Procedure ( parent child relation )

    create PROCEDURE GetEventCategories
    @keyword as nvarchar(100)
        WITH CTE(Id, Name, IdHierarchy,parentId) AS
            e.EventCategoryID as Id, cast(e.Title as varchar(max)) as Name,
            cast(cast(e.EventCategoryID as char(5)) as varchar(max)) IdHierarchy,ParentID
            EventCategory e  where e.Title like '%'+@keyword+'%'
         -- WHERE 
          --  parentid = @parentid
          UNION ALL
            p.EventCategoryID as Id, cast(p.Title + '>>' + as varchar(max)) as Name,
            c.IdHierarchy + cast(p.EventCategoryID as char(5)),p.ParentID
            EventCategory p 
          JOIN  CTE c ON c.Id = p.parentid
            where p.Title like '%'+@keyword+'%'
        ORDER BY 

    References in case

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Http;
    using SocialStoriesCore.Data;
    using Microsoft.EntityFrameworkCore;
    using Dapper;
    using System.Data;
    using System.Data.SqlClient;

    Best way to repeat a character in C#

    And yet another method

    new System.Text.StringBuilder().Append('\t', 100).ToString()

    Communication between tabs or windows

    There is a modern API dedicated for this purpose - Broadcast Channel

    It is as easy as:

    var bc = new BroadcastChannel('test_channel');
    bc.postMessage('This is a test message.'); /* send */
    bc.onmessage = function (ev) { console.log(ev); } /* receive */

    There is no need for the message to be just a DOMString, any kind of object can be sent.

    Probably, apart from API cleanness, it is the main benefit of this API - no object stringification.

    Currently supported only in Chrome and Firefox, but you can find a polyfill that uses localStorage.

    Django: multiple models in one template using forms

    This really isn't too hard to implement with ModelForms. So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST.

    if request.POST():
        a_valid = formA.is_valid()
        b_valid = formB.is_valid()
        c_valid = formC.is_valid()
        # we do this since 'and' short circuits and we want to check to whole page for form errors
        if a_valid and b_valid and c_valid:
            a =
            b =
            c =
            b.foreignkeytoA = a
            c.foreignkeytoB = b

    Here are the docs for custom validation.

    How to move screen without moving cursor in Vim?

    You may find answers to "Scrolling Vim relative to cursor, custom mapping" useful.

    You can use ScrollToPercent(0) from that question to do this.

    JQuery $.ajax() post - data in a java servlet

    Simple method to sending data using java script and ajex call.

    First right your form like this

    <form id="frm_details" method="post" name="frm_details">
    <input  id="email" name="email" placeholder="Your Email id" type="text" />
        <button class="subscribe-box__btn" type="submit">Need Assistance</button>

    javascript logic target on form id #frm_details after sumbit

            $("#frm_details").on("submit", function(event) {
                var formData = {
                    'email': $('input[name=email]').val() //for get email 
                    url: "/tsmisc/api/subscribe-newsletter",
                    type: "post",
                    data: formData,
                    success: function(d) {
    Request URL:
    Request Method:POST
    Status Code:200 
    Remote Address:
    From Data
    email:[email protected]

    jQuery: more than one handler for same event

    jquery will execute both handler since it allows multiple event handlers. I have created sample code. You can try it


    How to insert a text at the beginning of a file?

    If the file is only one line, you can use:

    sed 's/^/insert this /' oldfile > newfile

    If it's more than one line. one of:

    sed '1s/^/insert this /' oldfile > newfile
    sed '1,1s/^/insert this /' oldfile > newfile

    I've included the latter so that you know how to do ranges of lines. Both of these "replace" the start line marker on their affected lines with the text you want to insert. You can also (assuming your sed is modern enough) use:

    sed -i 'whatever command you choose' filename

    to do in-place editing.

    How to concatenate two strings in C++?

    strcat(destination,source) can be used to concatenate two strings in c++.

    To have a deep understanding you can lookup in the following link-

    Docker: How to delete all local Docker images

    Another way with xargs

    docker image ls -q | xargs -I {} docker image rm -f {}

    Simulating Key Press C#

    Instead of forcing an F5 keypress when you're just trying to get the page to postback, you can call a postback based on a JS event (even mousemove or timer_tick if you want it to fire all the time). Use the code at as a reference.

    UTF-8 problems while reading CSV file with fgetcsv

    Try putting this into the top of your file (before any other output):

    header('Content-Type: text/html; charset=UTF-8');

    Saving response from Requests to file

    As Peter already pointed out:

    In [1]: import requests
    In [2]: r = requests.get('')
    In [3]: type(r)
    Out[3]: requests.models.Response
    In [4]: type(r.content)
    Out[4]: str

    You may also want to check r.text.


    Double free or corruption after queue::push

    The problem is that your class contains a managed RAW pointer but does not implement the rule of three (five in C++11). As a result you are getting (expectedly) a double delete because of copying.

    If you are learning you should learn how to implement the rule of three (five). But that is not the correct solution to this problem. You should be using standard container objects rather than try to manage your own internal container. The exact container will depend on what you are trying to do but std::vector is a good default (and you can change afterwords if it is not opimal).

    #include <queue>
    #include <vector>
    class Test{
        std::vector<int> myArray;
        Test(): myArray(10){
    int main(){
        queue<Test> q
        Test t;

    The reason you should use a standard container is the separation of concerns. Your class should be concerned with either business logic or resource management (not both). Assuming Test is some class you are using to maintain some state about your program then it is business logic and it should not be doing resource management. If on the other hand Test is supposed to manage an array then you probably need to learn more about what is available inside the standard library.

    How to add local jar files to a Maven project?

    Yes , you can have but its not good idea.

    Instead install all these jars to maven repos

    Also See

    why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

    If you use MVC, tables, it works like this:


    Showing alert in angularjs when user leaves a page

    Lets seperate your question, you are asking about two different things:


    I'm trying to write a validation which alerts the user when he tries to close the browser window.


    I want to pop up a message when the user clicks on v1 that "he's about to leave from v1, if he wishes to continue" and same on clicking on v2.

    For the first question, do it this way:

    window.onbeforeunload = function (event) {
      var message = 'Sure you want to leave?';
      if (typeof event == 'undefined') {
        event = window.event;
      if (event) {
        event.returnValue = message;
      return message;

    And for the second question, do it this way:

    You should handle the $locationChangeStart event in order to hook up to view transition event, so use this code to handle the transition validation in your controller/s:

    function MyCtrl1($scope) {
        $scope.$on('$locationChangeStart', function(event) {
            var answer = confirm("Are you sure you want to leave this page?")
            if (!answer) {