Programs & Examples On #Pascalcasing

Pascal case is a language-independent naming convention in which each word of an identifier name begins with a capital letter, such as CustomerName, CustomerId, etc.

JSON Naming Convention (snake_case, camelCase or PascalCase)

Notably for me on NodeJS, if I'm working with databases and my field names are underscore separated, I also use them in the struct keys.

This is because db fields have a lot of acronyms/abbreviations so something like appSNSInterfaceRRTest looks a bit messy but app_sns_interface_rr_test is nicer.

In Javascript variables are all camelCase and class names (constructors) are ProperCase, so you'd see something like

var devTask = {
        task_id: 120,
        store_id: 2118,
        task_name: 'generalLedger'


generalLedgerTask = new GeneralLedgerTask( devTask );

And of course in JSON keys/strings are wrapped in double quotes, but then you just use the JSON.stringify and pass in JS objects, so don't need to worry about that.

I struggled with this a bit until I found this happy medium between JSON and JS naming conventions.

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

Here are sample apps:



Create a class :

public class HttpUtils {
  private static final String BASE_URL = "";
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {, params, responseHandler);
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {, params, responseHandler);

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
               , rp, new JsonHttpResponseHandler() {
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline

Please grant internet permission in your manifest file.

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

you can add compile '' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

How to open an external file from HTML

<a href="file://server/directory/file.xlsx" target="_blank"> if I remember correctly.

Saving binary data as file using JavaScript from a browser

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a); = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url; = name;;

saveByteArray([sampleBytes], 'example.txt');


Using ALTER to drop a column if it exists in MySQL

I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...

  1. get a new sql editor and execute SHOW TABLES to get a list of your tables
  2. select all of the rows, and choose copy to clipboard (unquoted) from the context menu
  3. paste the list of names into another editor tab
  4. write your query, ie ALTER TABLE x DROP a;
  5. do some copying and pasting, so you end up with separate query for each table
  6. Toggle whether the workbench should stop when an error occurs
  7. Hit execute and look through the output log

any tables which had the table now haven't any tables which didn't will have shown an error in the logs

then you can find/replace 'drop a' change it to 'ADD COLUMN b INT NULL' etc and run the whole thing again....

a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.

How to call Oracle MD5 hash function?

@user755806 I do not believe that your question was answered. I took your code but used the 'foo' example string, added a lower function and also found the length of the hash returned. In sqlplus or Oracle's sql developer Java database client you can use this to call the md5sum of a value. The column formats clean up the presentation.

column hash_key format a34;
column hash_key_len format 999999;
select dbms_obfuscation_toolkit.md5(
          input => UTL_RAW.cast_to_raw('foo')) as hash_key,
          input => UTL_RAW.cast_to_raw('foo'))) as hash_key_len
 from dual;

The result set

HASH_KEY                           HASH_KEY_LEN
---------------------------------- ------------
acbd18db4cc2f85cedef654fccc4a4d8             32

is the same value that is returned from a Linux md5sum command.

echo -n foo | md5sum
acbd18db4cc2f85cedef654fccc4a4d8  -
  1. Yes you can call or execute the sql statement directly in sqlplus or sql developer. I tested the sql statement in both clients against 11g.
  2. You can use any C, C#, Java or other programming language that can send a statement to the database. It is the database on the other end of the call that needs to be able to understand the sql statement. In the case of 11 g, the code will work.
  3. @tbone provides an excellent warning about the deprecation of the dbms_obfuscation_toolkit. However, that does not mean your code is unusable in 12c. It will work but you will want to eventually switch to dbms_crypto package. dbms_crypto is not available in my version of 11g.

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );

   $("#refresh-btn").on("click", RefreshTable);

   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


Using UPDATE in stored procedure with optional parameters

One Idea:

UPDATE tbl_ClientNotes
SET ordering=ISNULL(@ordering, ordering), 
    title=ISNULL(@title, title),  
    content=ISNULL(@content, content)
WHERE id=@id

How do I test if a variable is a number in Bash?

The accepted answer does not work here, I am on MacOS. The following code works:

if [ $(echo "$number" | grep -c '^[0-9]\+$') = 0 ]; then 
    echo "it is a number"
    echo "not a number"

Case Statement Equivalent in R

Here's a way using the switch statement:

df <- data.frame(name = c('cow','pig','eagle','pigeon'), 
                 stringsAsFactors = FALSE)
df$type <- sapply(df$name, switch, 
                  cow = 'animal', 
                  pig = 'animal', 
                  eagle = 'bird', 
                  pigeon = 'bird')

> df
    name   type
1    cow animal
2    pig animal
3  eagle   bird
4 pigeon   bird

The one downside of this is that you have to keep writing the category name (animal, etc) for each item. It is syntactically more convenient to be able to define our categories as below (see the very similar question How do add a column in a data frame in R )

myMap <- list(animal = c('cow', 'pig'), bird = c('eagle', 'pigeon'))

and we want to somehow "invert" this mapping. I write my own invMap function:

invMap <- function(map) {
  items <- as.character( unlist(map) )
  nams <- unlist(Map(rep, names(map), sapply(map, length)))
  names(nams) <- items

and then invert the above map as follows:

> invMap(myMap)
     cow      pig    eagle   pigeon 
"animal" "animal"   "bird"   "bird" 

And then it's easy to use this to add the type column in the data-frame:

df <- transform(df, type = invMap(myMap)[name])

> df
    name   type
1    cow animal
2    pig animal
3  eagle   bird
4 pigeon   bird

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

How to send a POST request using volley with string body?

I created a function for a Volley Request. You just need to pass the arguments :

public void callvolly(final String username, final String password){
    RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
    String url = ""; // <----enter your post url here
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        public void onResponse(String response) {
            //This code is executed if the server responds, whether or not the response contains data.
            //The String 'response' contains the server's response.
    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
        public void onErrorResponse(VolleyError error) {
            //This code is executed if there is an error.
    }) {
        protected Map<String, String> getParams() {
            Map<String, String> MyData = new HashMap<String, String>();
            MyData.put("username", username);             
            MyData.put("password", password);                
            return MyData;


Android Studio: /dev/kvm device permission denied

In order to make a virtual device in Linux - I have to follow this three command and it helps me to avoid trouble for building avd devices - the process are -

sudo apt install qemu-kvm
sudo adduser $USER kvm
sudo chown $USER /dev/kvm 

so, now you are good to go, restart android studio and start building application with emulator.

Posting JSON data via jQuery to ASP .NET MVC 4 controller action


Okay, so I have just spent several hours looking for a viable method for posting multiple parameters to an MVC 4 WEB API, but most of what I found was either for a 'GET' action or just flat out did not work. However, I finally got this working and I thought I'd share my solution.

  1. Use NuGet packages to download JSON-js json2 and Json.NET. Steps to install NuGet packages:

    (1) In Visual Studio, go to Website > Manage NuGet Packages... enter image description here

    (2) Type json (or something to that effect) into the search bar and find JSON-js json2 and Json.NET. Double-clicking them will install the packages into the current project.enter image description here

    (3) NuGet will automatically place the json file in ~/Scripts/json2.min.js in your project directory. Find the json2.min.js file and drag/drop it into the head of your website. Note: for instructions on installing .js (javascript) files, read this solution.

  2. Create a class object containing the desired parameters. You will use this to access the parameters in the API controller. Example code:

    Public Class PostMessageObj
    Private _body As String
    Public Property body As String
            Return _body
        End Get
        Set(value As String)
            _body = value
        End Set
    End Property
    Private _id As String
    Public Property id As String
            Return _id
        End Get
        Set(value As String)
            _id = value
        End Set
    End Property
    End Class
  3. Then we setup the actual MVC 4 Web API controller that we will be using for the POST action. In it, we will use Json.NET to deserialize the string object when it is posted. Remember to use the appropriate namespaces. Continuing with the previous example, here is my code:

    Public Sub PostMessage(<FromBody()> ByVal newmessage As String)
    Dim t As PostMessageObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PostMessageObj)(newmessage)
    Dim body As String = t.body
    Dim i As String =
    End Sub
  4. Now that we have our API controller set up to receive our stringified JSON object, we can call the POST action freely from the client-side using $.ajax; Continuing with the previous example, here is my code (replace localhost+rootpath appropriately):

    var url = 'http://<localhost+rootpath>/api/Offers/PostMessage';
    var dataType = 'json'
    var data = 'nothn'
    var tempdata = { body: 'this is a new message...Ip sum lorem.',
        id: '1234'
    var jsondata = JSON.stringify(tempdata)
        type: "POST",
        url: url,
        data: { '': jsondata},
        success: success(data),
        dataType: 'text'

As you can see we are basically building the JSON object, converting it into a string, passing it as a single parameter, and then rebuilding it via the JSON.NET framework. I did not include a return value in our API controller so I just placed an arbitrary string value in the success() function.

Author's notes

This was done in Visual Studio 2010 using ASP.NET 4.0, WebForms, VB.NET, and MVC 4 Web API Controller. For anyone having trouble integrating MVC 4 Web API with VS2010, you can download the patch to make it possible. You can download it from Microsoft's Download Center.

Here are some additional references which helped (mostly in C#):

Start / Stop a Windows Service from a non-Administrator user account

Below I have put together everything I learned about Starting/Stopping a Windows Service from a non-Admin user account, if anyone needs to know.

Primarily, there are two ways in which to Start / Stop a Windows Service. 1. Directly accessing the service through logon Windows user account. 2. Accessing the service through IIS using Network Service account.

Command line command to start / stop services:

C:/> net start <SERVICE_NAME>
C:/> net stop <SERVICE_NAME>

C# Code to start / stop services:

ServiceController service = new ServiceController(SERVICE_NAME);

//Start the service
if (service.Status == ServiceControllerStatus.Stopped)
      service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10.0));

//Stop the service
if (service.Status == ServiceControllerStatus.Running)
      service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10.0));

Note 1: When accessing the service through IIS, create a Visual Studio C# ASP.NET Web Application and put the code in there. Deploy the WebService to IIS Root Folder (C:\inetpub\wwwroot\) and you're good to go. Access it by the url http:///.

1. Direct Access Method

If the Windows User Account from which either you give the command or run the code is a non-Admin account, then you need to set the privileges to that particular user account so it has the ability to start and stop Windows Services. This is how you do it. Login to an Administrator account on the computer which has the non-Admin account from which you want to Start/Stop the service. Open up the command prompt and give the following command:

C:/>sc sdshow <SERVICE_NAME>

Output of this will be something like this:


It lists all the permissions each User / Group on this computer has with regards to .

A description of one part of above command is as follows:


It has the default owner, default group, and it has the Security descriptor control flags (A;;CCLCSWRPWPDTLOCRRC;;;SY):

ace_flags - n/a,
rights - CCLCSWRPWPDTLOCRRC,  please refer to the Access Rights and Access Masks and Directory Services Access Rights
CC: ADS_RIGHT_DS_CREATE_CHILD - Create a child DS object.
LC: ADS_RIGHT_ACTRL_DS_LIST - Enumerate a DS object.
SW: ADS_RIGHT_DS_SELF - Access allowed only after validated rights checks supported by the object are performed. This flag can be used alone to perform all validated rights checks of the object or it can be combined with an identifier of a specific validated right to perform only that check.
RP: ADS_RIGHT_DS_READ_PROP - Read the properties of a DS object.
WP: ADS_RIGHT_DS_WRITE_PROP - Write properties for a DS object.
DT: ADS_RIGHT_DS_DELETE_TREE - Delete a tree of DS objects.
LO: ADS_RIGHT_DS_LIST_OBJECT - List a tree of DS objects.
CR: ADS_RIGHT_DS_CONTROL_ACCESS - Access allowed only after extended rights checks supported by the object are performed. This flag can be used alone to perform all extended rights checks on the object or it can be combined with an identifier of a specific extended right to perform only that check.
RC: READ_CONTROL - The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL). (This is a Standard Access Right, please read more
object_guid - n/a,
inherit_object_guid - n/a,
account_sid - "SY": Local system. The corresponding RID is SECURITY_LOCAL_SYSTEM_RID.

Now what we need to do is to set the appropriate permissions to Start/Stop Windows Services to the groups or users we want. In this case we need the current non-Admin user be able to Start/Stop the service so we are going to set the permissions to that user. To do that, we need the SID of that particular Windows User Account. To obtain it, open up the Registry (Start > regedit) and locate the following registry key.

LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

Under that there is a seperate Key for each an every user account in this computer, and the key name is the SID of each account. SID are usually of the format S-1-5-21-2103278432-2794320136-1883075150-1000. Click on each Key, and you will see on the pane to the right a list of values for each Key. Locate "ProfileImagePath", and by it's value you can find the User Name that SID belongs to. For instance, if the user name of the account is SACH, then the value of "ProfileImagePath" will be something like "C:\Users\Sach". So note down the SID of the user account you want to set the permissions to.

Note2: Here a simple C# code sample which can be used to obtain a list of said Keys and it's values.

//LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList RegistryKey
RegistryKey profileList = Registry.LocalMachine.OpenSubKey(keyName);

//Get a list of SID corresponding to each account on the computer
string[] sidList = profileList.GetSubKeyNames();

foreach (string sid in sidList)
    //Based on above names, get 'Registry Keys' corresponding to each SID
    RegistryKey profile = Registry.LocalMachine.OpenSubKey(Path.Combine(keyName, sid));

    string strSID = sid;
    //UserName which is represented by above SID    
    string strUserName = (string)profile.GetValue("ProfileImagePath");

Now that we have the SID of the user account we want to set the permissions to, let's get down to it. Let's assume the SID of the user account is S-1-5-21-2103278432-2794320136-1883075150-1000. Copy the output of the [sc sdshow ] command to a text editor. It will look like this:


Now, copy the (A;;CCLCSWRPWPDTLOCRRC;;;SY) part of the above text, and paste it just before the S:(AU;... part of the text. Then change that part to look like this: (A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)

Then add sc sdset at the front, and enclose the above part with quotes. Your final command should look something like the following:


Now execute this in your command prompt, and it should give the output as follows if successful:

[SC] SetServiceObjectSecurity SUCCESS

Now we're good to go! Your non-Admin user account has been granted permissions to Start/Stop your service! Try loggin in to the user account and Start/Stop the service and it should let you do that.

2. Access through IIS Method

In this case, we need to grant the permission to the IIS user "Network Services" instead of the logon Windows user account. The procedure is the same, only the parameters of the command will be changed. Since we set the permission to "Network Services", replace SID with the string "NS" in the final sdset command we used previously. The final command should look something like this:


Execute it in the command prompt from an Admin user account, and voila! You have the permission to Start / Stop the service from any user account (irrespective of whether it ia an Admin account or not) using a WebMethod. Refer to Note1 to find out how to do so.

Insert a line at specific line number with sed or awk

sed -i '8i8 This is Line 8' FILE

inserts at line 8

8 This is Line 8

into file FILE

-i does the modification directly to file FILE, no output to stdout, as mentioned in the comments by glenn jackman.

ImportError: No module named apiclient.discovery

You should be able to get these dependencies with this simple install:

sudo pip install --upgrade google-api-python-client

This is described on the quick start page for python.

angularjs getting previous route path

You'll need to couple the event listener to $rootScope in Angular 1.x, but you should probably future proof your code a bit by not storing the value of the previous location on $rootScope. A better place to store the value would be a service:

var app = angular.module('myApp', [])
.service('locationHistoryService', function(){
    return {
        previousLocation: null,

        store: function(location){
            this.previousLocation = location;

        get: function(){
            return this.previousLocation;
.run(['$rootScope', 'locationHistoryService', function($location, locationHistoryService){
    $rootScope.$on('$locationChangeSuccess', function(e, newLocation, oldLocation){;

scale Image in an UIButton to AspectFit?

If you really want to scale an image, do it, but you should resize it before using it. Resizing it at run time will just lose CPU cycles.

This is the category I'm using to scale an image :


@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;


@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

UIImage *sourceImage = self;
UIImage *newImage = nil;

CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;

CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;

CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;

CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (!CGSizeEqualToSize(imageSize, targetSize)) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor) 
                scaleFactor = widthFactor;
                scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image

        if (widthFactor < heightFactor) {
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        } else if (widthFactor > heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;

// this is actually the interesting part:

UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);

CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width  = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();

if(newImage == nil) NSLog(@"could not scale image");

return newImage ;


You can use it to the size you want. Like :

[self.itemImageButton setImage:[stretchImage imageByScalingProportionallyToSize:CGSizeMake(20,20)]];

How can I convert a string with dot and comma into a float in Python

What about this?

 my_string = "123,456.908"
 commas_removed = my_string.replace(',', '') # remove comma separation
 my_float = float(commas_removed) # turn from string to float.

In short:

my_float = float(my_string.replace(',', ''))

How to compile C program on command line using MinGW?


Add your minGW's bin folder directory ( ex: C\mingw64\bin ) in System variables => Path. visual example


.c: gcc filename.c -o desire

.cpp: g++ filename.cpp -o desire


desire/ or ./desire

How should I validate an e-mail address?

Note that most of the regular expressions are not valid for international domain names (IDN) and new top level domains like .mobi or .info (if you check for country codes or .org, .com, .gov and so on).

A valid check should separate the local part (before the at-sign) and the domain part. You should also consider the max length of the local part and domain (in sum 255 chars including the at-sign).

The best approach is to transform the address in an IDN compatible format (if required), validate the local part (RFC), check the length of the address and the check the availability of the domain (DNS MX lookup) or simply send an email.

Prevent screen rotation on Android

Prevent Screen Rotation just add this following line in your Manifests.

        android:screenOrientation="portrait" />

This works for me.

Is there a color code for transparent in HTML?

When you have a 6 digit color code e.g. #ffffff, replace it with #ffffff00. Just add 2 zeros at the end to make the color transparent.

Here is an article describing the new standard in more depth:

How do I execute a stored procedure in a SQL Agent job?

You just need to add this line to the window there:

exec (your stored proc name) (and possibly add parameters)

What is your stored proc called, and what parameters does it expect?

read input separated by whitespace(s) or newline...?

Use 'q' as the the optional argument to getline.

#include <iostream>
#include <sstream>

int main() {
    std::string numbers_str;
    getline( std::cin, numbers_str, 'q' );

    int number;
    for ( std::istringstream numbers_iss( numbers_str );
          numbers_iss >> number; ) {
        std::cout << number << ' ';

How to combine multiple conditions to subset a data-frame using "OR"? <- subset(data , V1 > 2 | V2 < 4)

An alternative solution that mimics the behavior of this function and would be more appropriate for inclusion within a function body: <- data[ which( data$V1 > 2 | data$V2 < 4) , ]

Some people criticize the use of which as not needed, but it does prevent the NA values from throwing back unwanted results. The equivalent (.i.e not returning NA-rows for any NA's in V1 or V2) to the two options demonstrated above without the which would be: <- data[ !$V1 | data$V2) & ( data$V1 > 2 | data$V2 < 4)  , ]

Note: I want to thank the anonymous contributor that attempted to fix the error in the code immediately above, a fix that got rejected by the moderators. There was actually an additional error that I noticed when I was correcting the first one. The conditional clause that checks for NA values needs to be first if it is to be handled as I intended, since ...

> NA & 1
[1] NA
> 0 & NA

Order of arguments may matter when using '&".

Pass a JavaScript function as parameter

If you want to pass a function, just reference it by name without the parentheses:

function foo(x) {
function bar(func) {
    func("Hello World!");

//alerts "Hello World!"

But sometimes you might want to pass a function with arguments included, but not have it called until the callback is invoked. To do this, when calling it, just wrap it in an anonymous function, like this:

function foo(x) {
function bar(func) {

//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });

If you prefer, you could also use the apply function and have a third parameter that is an array of the arguments, like such:

function eat(food1, food2)
    alert("I like to eat " + food1 + " and " + food2 );
function myFunc(callback, args)
    //do stuff
    //execute callback when finished
    callback.apply(this, args);

//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]); 

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

Just for the record if somebody needs a way to handle signals on Windows. I had a requirement to handle from prog A calling prog B through os/exec but prog B never was able to terminate gracefully because sending signals through ex. cmd.Process.Signal(syscall.SIGTERM) or other signals are not supported on Windows. The way I handled is by creating a temp file as a signal ex. .signal.term through prog A and prog B needs to check if that file exists on interval base, if file exists it will exit the program and handle a cleanup if needed, I'm sure there are other ways but this did the job.

convert HTML ( having Javascript ) to PDF using JavaScript

We are also looking for some way to convert html files with complex javascript to pdf. The javasript in our files contains document.write and DOM manipulation.

We have tried using a combination of HtmlUnit to parse the files and Flying Saucer to render to pdf but the results are not satisfactory enough. It works, but in our case the pdf is not close enough to what the user wants.

If you want to try this out, here is a code snippet to convert a local html file to pdf.

URL url = new File("test.html").toURI().toURL();
WebClient webClient = new WebClient(); 
HtmlPage page = webClient.getPage(url);

OutputStream os = null;
   os = new FileOutputStream("test.pdf");

   ITextRenderer renderer = new ITextRenderer();
} finally{
   if(os != null) os.close();

Reset identity seed after deleting records in SQL Server

This is a common question and the answer is always the same: don't do it. Identity values should be treated as arbitrary and, as such, there is no "correct" order.

Break or return from Java 8 stream forEach?

Below you find the solution I used in a project. Instead forEach just use allMatch:

someObjects.allMatch(obj -> {
    return !some_condition_met;

What is the difference between new/delete and malloc/free?

There are a few things which new does that malloc doesn’t:

  1. new constructs the object by calling the constructor of that object
  2. new doesn’t require typecasting of allocated memory.
  3. It doesn’t require an amount of memory to be allocated, rather it requires a number of objects to be constructed.

So, if you use malloc, then you need to do above things explicitly, which is not always practical. Additionally, new can be overloaded but malloc can’t be.

In a word, if you use C++, try to use new as much as possible.

Install Windows Service created in Visual Studio

Another possible problem (which I ran into):

Be sure that the ProjectInstaller class is public. To be honest, I am not sure how exactly I did it, but I added event handlers to ProjectInstaller.Designer.cs, like:

this.serviceProcessInstaller1.BeforeInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_BeforeInstall);

I guess during the automatical process of creating the handler function in ProjectInstaller.cs it changed the class definition from

public class ProjectInstaller : System.Configuration.Install.Installer


partial class ProjectInstaller : System.Configuration.Install.Installer

replacing the public keyword with partial. So, in order to fix it it must be

public partial class ProjectInstaller : System.Configuration.Install.Installer

I use Visual Studio 2013 Community edition.

POST an array from an HTML form without javascript

check this one out.

<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">

<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">

<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">

<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">

it should end up like this in the $_POST[] array (PHP format for easy visualization)

$_POST[] = array(
    'tree' => array(

Resize on div element

If you just want to resize the div itself you need to specify that in css style. You need to add overflow and resize property.

Below is my code snippet

#div1 {
        width: 90%;
        height: 350px;
        padding: 10px;
        border: 1px solid #aaaaaa;
        overflow: auto;
        resize: both;

<div id="div1">


How do I point Crystal Reports at a new database

Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.

You will need to do this for the 'Subreports' nodes as well.

FYI, you can also do individual tables by selecting each individually, then choosing Update.

Why do I always get the same sequence of random numbers with rand()?

This is from


void srand(unsigned int seed); 

This function seeds the random number generator used by the function rand. Seeding srand with the same seed will cause rand to return the same sequence of pseudo-random numbers. If srand is not called, rand acts as if srand(1) has been called.

how to git commit a whole folder?

OR, even better just the ol' "drag and drop" the folder, onto your repository opened in git browser.

  1. Open your repository in the web portal , you will see the listing of all your files. If you have just recently created the repo, and initiated with a README, you will only see the README listing.

  2. Open your folder which you want to upload. drag and drop on the listing in browser. See the image here.

Simple way to create matrix of random numbers

#this is a function for a square matrix so on the while loop rows does not have to be less than cols.
#you can make your own condition. But if you want your a square matrix, use this code.

import random

import numpy as np

def random_matrix(R, cols):

        matrix = []

        rows =  0

        while  rows < cols:

            N = random.sample(R, cols)


            rows = rows + 1

    return np.array(matrix)

print(random_matrix(range(10), 5))
#make sure you understand the function random.sample

Android: remove left margin from actionbar's custom layout


    supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM;

    val parent = supportActionBar?.customView?.parent as Toolbar
    parent?.setPadding(0, 0, 0, 0)//for tab otherwise give space in tab
    parent?.setContentInsetsAbsolute(0, 0)

Maven Install on Mac OS X

brew install maven31 (if you have homebrew)

Equivalent function for DATEADD() in Oracle

Not my answer :

I wasn't too happy with the answers above and some additional searching yielded this :

SELECT SYSDATE AS current_date,

       SYSDATE + 1 AS plus_1_day,

       SYSDATE + 1/24 AS plus_1_hours,

       SYSDATE + 1/24/60 AS plus_1_minutes,

       SYSDATE + 1/24/60/60 AS plus_1_seconds

FROM   dual;

which I found very helpful. From

Why use Optional.of over Optional.ofNullable?

This depends upon scenarios.

Let's say you have some business functionality and you need to process something with that value further but having null value at time of processing would impact it.

Then, in that case, you can use Optional<?>.

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .orElse("Default value in case of null");

Get all files and directories in specific path fast

In .NET 4.0 there's the Directory.EnumerateFiles method which returns an IEnumerable<string> and is not loading all the files in memory. It's only once you start iterating over the returned collection that files will be returned and exceptions could be handled.

How can I change default dialog button text color in android 5

Here is how you do it: Simple way

// Initializing a new alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
builder.setNegativeButton(R.string.cancel, null);

// Create the alert dialog and change Buttons colour
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    public void onShow(DialogInterface arg0) {

What's in an Eclipse .classpath/.project file?

Complete reference is not available for the mentioned files, as they are extensible by various plug-ins.

Basically, .project files store project-settings, such as builder and project nature settings, while .classpath files define the classpath to use during running. The classpath files contains src and target entries that correspond with folders in the project; the con entries are used to describe some kind of "virtual" entries, such as the JVM libs or in case of eclipse plug-ins dependencies (normal Java project dependencies are displayed differently, using a special src entry).

T-SQL Cast versus Convert

CAST uses ANSI standard. In case of portability, this will work on other platforms. CONVERT is specific to sql server. But is very strong function. You can specify different styles for dates

Text in Border CSS HTML

I know a bit late to the party, however I feel the answers could do with some more investigation/input. I have managed to create the situation without using the fieldset tag - that is wrong anyway as if I'm not in a form then that isn't really what I should be doing.

/* Styles go here */

#info-block section {
    border: 2px solid black;

.file-marker > div {
    padding: 0 3px;
    height: 100px;
    margin-top: -0.8em;
.box-title {
    background: white none repeat scroll 0 0;
    display: inline-block;
    padding: 0 2px;
    margin-left: 8em;
<aside id="info-block">
  <section class="file-marker">
      <div class="box-title">
        Audit Trail
      <div class="box-contents">
        <div id="audit-trail">

This can be viewed in this plunk:

Outline box with title

What this achieves is the following:

  • no use of fieldsets.

  • minimal use if CSS to create effect with just some paddings.

  • Use of "em" margin top to create font relative title.

  • use of display inline-block to achieve natural width around the text.

Anyway I hope that helps future stylers, you never know.

How to force a view refresh without having it trigger automatically from an observable?

In some circumstances it might be useful to simply remove the bindings and then re-apply:

ko.applyBindings(viewModel, document.getElementById(element_id))

fastest way to export blobs from table into individual files

For me what worked by combining all the posts I have read is:

1.Enable OLE automation - if not enabled

sp_configure 'show advanced options', 1;  
sp_configure 'Ole Automation Procedures', 1;  

2.Create a folder where the generated files will be stored:


3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
enter image description here

CREATE TABLE [dbo].[Document](
    [Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Extension] [varchar](50) NULL,
    [FileName] [varchar](200) NULL,
    [Doc_Content] [varbinary](max) NULL   

INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
    SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)

Important note!

Don't forget to add in Doc_Content column the varbinary of file you want to generate!

4.Run the below script

DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max) 
, @fPath varchar(max)  
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it 
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num]  varchar(100) , [FileName]  varchar(100), [Doc_Content] varBinary(max) )

INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM  [dbo].[Document]

SELECT @i = COUNT(1) FROM @Doctable   

WHILE @i >= 1   


    @data = [Doc_Content],
    @fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
    @folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;  
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+  @fPath   

--Reset the variables for next use
SELECT @data = NULL  
, @init = NULL
, @fPath = NULL  
, @folderPath = NULL
SET @i -= 1

5.The results is shown below: enter image description here

Adding whitespace in Java

If you have an Instance of the EditText available at the point in your code where you want add whitespace, then this code below will work. There may be some things to consider, for example the code below may trigger any TextWatcher you have set to this EditText, idk for sure, just saying, but this will work when trying to append blank space like this: " ", hasn't worked.

messageInputBox.dispatchKeyEvent(new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_SPACE, 0, 0, 0, 0,

mysqldump exports only one table

Here I am going to export 3 tables from database named myDB in an sql file named table.sql

mysqldump -u root -p myDB table1 table2 table3 > table.sql

Converting Dictionary to List?

Probably you just want this:

dictList = dict.items()

Your approach has two problems. For one you use key and value in quotes, which are strings with the letters "key" and "value", not related to the variables of that names. Also you keep adding elements to the "temporary" list and never get rid of old elements that are already in it from previous iterations. Make sure you have a new and empty temp list in each iteration and use the key and value variables:

for key, value in dict.iteritems():
    temp = []
    aKey = key
    aValue = value

Also note that this could be written shorter without the temporary variables (and in Python 3 with items() instead of iteritems()):

for key, value in dict.items():
    dictList.append([key, value])

Can I configure a subdomain to point to a specific port on my server

If you want to host multiple websites in a single server in different ports then, method mentioned by MRVDOG won't work. Because browser won't resolve SRV records and will always hit :80 port. For example if your requirement is: maps to maps to

Because often you want to fully utilize the server space you have bought. Then you can try the following:

Step 1: Install proxy server. I will use Nginx here.

apt-get install nginx

Step 2: Edit /etc/nginx/nginx.conf file to add the port mappings. To do so, add the following lines:

server {
    listen 80;

    location / {
        proxy_pass http://localhost:8080;

server {
    listen 80;

    location / {
        proxy_pass http://localhost:8081;

This does the magic. So the file will end up looking like following:

user www-data;
worker_processes auto;
pid /run/;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;

http {

    # Basic Settings

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # SSL Settings

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    # Logging Settings

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Gzip Settings

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # Virtual Host Configs
server {
    listen 80;

    location / {
        proxy_pass http://localhost:8080;

server {
    listen 80;

    location / {
        proxy_pass http://localhost:8081;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

#mail {
#   # See sample authentication script at:
#   #
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }

Step 3: Start nginx:

/etc/init.d/nginx start.

Whenever you make any changes to configuration, you need to restart nginx:

/etc/init.d/nginx restart

Finally: Don't forget to add A records in your DNS configuration. All subdomains should point to domain. Like this: enter image description here

Put your static ip instead of

Further details:

Log4j2 configuration - No log4j2 configuration file found

Was following the documentations - Apache Log4j2 Configuratoin and Apache Log4j2 Maven in configuring log4j2 with yaml. As per the documentation, the following maven dependencies are required:




Just adding these didn't pick the configuration and always gave error. The way of debugging configuration by adding -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE helped in seeing the logs. Later had to download the source using Maven and debugging helped in understanding the depended classes of log4j2. They are listed in org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory:


Adding dependency mapping for jackson-dataformat-yaml will not have the first two classes. Hence, add the jackson-databind dependency to get yaml configuration working:


You may add the version by referring to the Test Dependencies section of log4j-api version item from MVN Repository. E.g. for 2.8.1 version of log4j-api, refer this link and locate the jackson-databind version.

Moreover, you can use the below Java code to check if the classes are available in the classpath:

System.out.println(ClassLoader.getSystemResource("log4j2.yml")); //Check if file is available in CP
ClassLoader cl = Thread.currentThread().getContextClassLoader(); //Code as in log4j2 API. Version: 2.8.1
 String [] classes = {"com.fasterxml.jackson.databind.ObjectMapper",

 for(String className : classes) {

MultipartException: Current request is not a multipart request

I was also facing the same issue with Postman for multipart. I fixed it by doing the following steps:

  • Do not select Content-Type in the Headers section.
  • In Body tab of Postman you should select form-data and select file type.

It worked for me.

What is the equivalent of the C# 'var' keyword in Java?

I have cooked up a plugin for IntelliJ that – in a way – gives you var in Java. It's a hack, so the usual disclaimers apply, but if you use IntelliJ for your Java development and want to try it out, it's at

Python: importing a sub-package or sub-module

The reason #2 fails is because sys.modules['module'] does not exist (the import routine has its own scope, and cannot see the module local name), and there's no module module or package on-disk. Note that you can separate multiple imported names by commas.

from package.subpackage.module import attribute1, attribute2, attribute3


from package.subpackage import module
print module.attribute1

What exactly does numpy.exp() do?

exp(x) = e^x where e= 2.718281(approx)

import numpy as np

print ar


[ 2.71828183  7.3890561  20.08553692]

JQuery/Javascript: check if var exists

For your case, and 99.9% of all others elclanrs answer is correct.

But because undefined is a valid value, if someone were to test for an uninitialized variable

var pagetype; //== undefined
if (typeof pagetype === 'undefined') //true

the only 100% reliable way to determine if a var exists is to catch the exception;

var exists = false;
try { pagetype; exists = true;} catch(e) {}
if (exists && ...) {}

But I would never write it this way

PHP - add 1 day to date format mm-dd-yyyy

$date = strtotime("+1 day");
echo date('m-d-y',$date);

How to save password when using Subversion from the console

Using plaintext may not be the best choice, if the password is ever used as something else.

I support the accepted answer, but it didn't work for me - for a very specific reason: I wanted to use either kwallet or gnome-keyring password stores. I tried changing the settings, all over the four files:


Even after it all was set the same, with password-stores and KWallet name (default might be wrong, right?) it didn't work and kept asking for password forever. The files in ~/.subversion had permissions 600.

Well, at that point, you may try to check one simple thing:

which svn

If you get:


then you may suspect with great likelihood that this client was built from source, locally, by your administrator (which may be yourself, as in my case).

Subversion is a nasty beast to compile, very easy to accidentally build without HTTP support, or - as in my example - without support for encrypted password stores (you need either Gnome or KDE development files, and a lot of them!). But the ./configure script won't tell you that, and you just get a less functional svn command.

In that case, you may go back to the client, which came with your distribution, usually in /usr/bin/svn. The downside is - you'll probably need to re-checkout the working copies, as there is no svn downgrade command. You can consult Linus Torvalds on what to think about Subversion, anyway ;)

JavaScript to scroll long page to DIV

For smooth scroll this code is useful

$('a[href*=#scrollToDivId]').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      var head_height = $('.header').outerHeight(); // if page has any sticky header get the header height else use 0 here
      if (target.length) {
          scrollTop: target.offset().top - head_height
        }, 1000);
        return false;

django no such table:

sqlall just prints the SQL, it doesn't execute it. syncdb will create tables that aren't already created, but it won't modify existing tables.

Can attributes be added dynamically in C#?

You can't. One workaround might be to generate a derived class at runtime and adding the attribute, although this is probably bit of an overkill.

How can I force division to be floating point? Division keeps rounding down to 0?

Add a dot (.) to indicate floating point numbers

>>> 4/3.

EditText, inputType values (xml)


is deprecated, instead use inputType :


Java enum - why use toString instead of name

name() is literally the textual name in the java code of the enum. That means it is limited to strings that can actually appear in your java code, but not all desirable strings are expressible in code. For example, you may need a string that begins with a number. name() will never be able to obtain that string for you.

How to add shortcut keys for java code in eclipse

Type "Sysout" and then Ctrl+Space. It expands to


To get specific part of a string in c#

If you want to get the strings separated by the , you can use

string b = a.Split(',')[0];

Java: get greatest common divisor

For int and long, as primitives, not really. For Integer, it is possible someone wrote one.

Given that BigInteger is a (mathematical/functional) superset of int, Integer, long, and Long, if you need to use these types, convert them to a BigInteger, do the GCD, and convert the result back.

private static int gcdThing(int a, int b) {
    BigInteger b1 = BigInteger.valueOf(a);
    BigInteger b2 = BigInteger.valueOf(b);
    BigInteger gcd = b1.gcd(b2);
    return gcd.intValue();

Singleton with Arguments in Java

Singletons are generally considered to be anti-patterns and shouldn't be used. They do not make code easy to test.

A singleton with an argument makes no sense anyway - what would happen if you wrote:

Singleton s = SingletonHolder.getInstance(1);
Singleton t = SingletonHolder.getInstance(2); //should probably throw IllegalStateException

Your singleton is also not thread-safe as multiple threads can make simultaneous calls to getInstance resulting in more than one instance being created (possibly with different values of x).

SQL Query to concatenate column values from multiple rows in Oracle

The LISTAGG analytic function was introduced in Oracle 11g Release 2, making it very easy to aggregate strings. If you are using 11g Release 2 you should use this function for string aggregation. Please refer below url for more information about string concatenation.

String Concatenation

How do I load an url in iframe with Jquery

Try $(this).load("/file_name.html");. This method targets a local file.

You can also target remote files (on another domain) take a look at:

How can I check if a Perl array contains a particular value?

You certainly want a hash here. Place the bad parameters as keys in the hash, then decide whether a particular parameter exists in the hash.

our %bad_params = map { $_ => 1 } qw(badparam1 badparam2 badparam3)

if ($bad_params{$new_param}) {
  print "That is a bad parameter\n";

If you are really interested in doing it with an array, look at List::Util or List::MoreUtils

Authenticated HTTP proxy with Java

You're almost there, you just have to append:


Read specific columns from a csv file with csv module?

a, 1, +
b, 2, -
c, 3, *
d, 4, /
column_names = ["Letter", "Number", "Symbol"]
df = pd.read_csv("sample.csv", names=column_names)
  Letter  Number Symbol
0      a       1      +
1      b       2      -
2      c       3      *
3      d       4      /

letters = df.Letter.to_list()
['a', 'b', 'c', 'd'] is not a function

The SIMPLEST answer is to put "data" into a pair of square brackets (i.e. [data]):

     $.getJSON("json/products.json").done(function (data) {

         var allProducts = [data].map(function (item) {
             return new getData(item);


Here, [data] is an array, and the ".map" method can be used on it. It works for me! enter image description here

What Ruby IDE do you prefer?

Once I found Geany (Ubuntu), I switched from TextMate (OSX) and never looked back. Geany is a lean, clean, speedy IDE that can be used either as a text editor or a light-weight IDE. It supports not only text editing features (syntax highlighting, code folding, auto-completion, auto-closing, symbol lists, code navigation, directory tree, multi-tabbed open files etc.) but also normal IDE features such as simple project management, compile-build-run within the main window. Unlike TextMate, it has a Terminal screen within its own window; you do not have to go back and force between your editor window and terminal window. Unlike TextMate, it supports international languages. Unlike TextMate, it supports multi-platforms, Unlike TextMate, it is open-source and free. Geany is now my favorite C/Ruby/XML development tool.

How to write a foreach in SQL Server?

Suppose that the column PractitionerId is a unique, then you can use the following loop

DECLARE @PractitionerId int = 0
WHILE(1 = 1)
  SELECT @PractitionerId = MIN(PractitionerId)
  FROM dbo.Practitioner WHERE PractitionerId > @PractitionerId
  IF @PractitionerId IS NULL BREAK
  SELECT @PractitionerId

Get class name of object as string in Swift

Swift 5.1

You can get class, struct, enum, protocol and NSObject names though Self.self.


Why dict.get(key) instead of dict[key]?

What is the dict.get() method?

As already mentioned the get method contains an additional parameter which indicates the missing value. From the documentation

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

An example can be

>>> d = {1:2,2:3}
>>> d[1]
>>> d.get(1)
>>> d.get(3)
>>> repr(d.get(3))
>>> d.get(3,1)

Are there speed improvements anywhere?

As mentioned here,

It seems that all three approaches now exhibit similar performance (within about 10% of each other), more or less independent of the properties of the list of words.

Earlier get was considerably slower, However now the speed is almost comparable along with the additional advantage of returning the default value. But to clear all our queries, we can test on a fairly large list (Note that the test includes looking up all the valid keys only)

def getway(d):
    for i in range(100):
        s = d.get(i)

def lookup(d):
    for i in range(100):
        s = d[i]

Now timing these two functions using timeit

>>> import timeit
>>> print(timeit.timeit("getway({i:i for i in range(100)})","from __main__ import getway"))
>>> print(timeit.timeit("lookup({i:i for i in range(100)})","from __main__ import lookup"))

As we can see the lookup is faster than the get as there is no function lookup. This can be seen through dis

>>> def lookup(d,val):
...     return d[val]
>>> def getway(d,val):
...     return d.get(val)
>>> dis.dis(getway)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_ATTR                0 (get)
              6 LOAD_FAST                1 (val)
              9 CALL_FUNCTION            1
             12 RETURN_VALUE        
>>> dis.dis(lookup)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_FAST                1 (val)
              6 BINARY_SUBSCR       
              7 RETURN_VALUE  

Where will it be useful?

It will be useful whenever you want to provide a default value whenever you are looking up a dictionary. This reduces

 if key in dic:
      val = dic[key]
      val = def_val

To a single line, val = dic.get(key,def_val)

Where will it be NOT useful?

Whenever you want to return a KeyError stating that the particular key is not available. Returning a default value also carries the risk that a particular default value may be a key too!

Is it possible to have get like feature in dict['key']?

Yes! We need to implement the __missing__ in a dict subclass.

A sample program can be

class MyDict(dict):
    def __missing__(self, key):
        return None

A small demonstration can be

>>> my_d = MyDict({1:2,2:3})
>>> my_d[1]
>>> my_d[3]
>>> repr(my_d[3])

Make div (height) occupy parent remaining height

Expanding the #down child to fill the remaining space of #container can be accomplished in various ways depending on the browser support you wish to achieve and whether or not #up has a defined height.


.container {_x000D_
  width: 100px;_x000D_
  height: 300px;_x000D_
  border: 1px solid red;_x000D_
  float: left;_x000D_
.up {_x000D_
  background: green;_x000D_
.down {_x000D_
  background: pink;_x000D_
.grid.container {_x000D_
  display: grid;_x000D_
  grid-template-rows: 100px;_x000D_
.flexbox.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
.flexbox.container .down {_x000D_
  flex-grow: 1;_x000D_
.calc .up {_x000D_
  height: 100px;_x000D_
.calc .down {_x000D_
  height: calc(100% - 100px);_x000D_
.overflow.container {_x000D_
  overflow: hidden;_x000D_
.overflow .down {_x000D_
  height: 100%;_x000D_
<div class="grid container">_x000D_
  <div class="up">grid_x000D_
    <br />grid_x000D_
    <br />grid_x000D_
    <br />_x000D_
  <div class="down">grid_x000D_
    <br />grid_x000D_
    <br />grid_x000D_
    <br />_x000D_
<div class="flexbox container">_x000D_
  <div class="up">flexbox_x000D_
    <br />flexbox_x000D_
    <br />flexbox_x000D_
    <br />_x000D_
  <div class="down">flexbox_x000D_
    <br />flexbox_x000D_
    <br />flexbox_x000D_
    <br />_x000D_
<div class="calc container">_x000D_
  <div class="up">calc_x000D_
    <br />calc_x000D_
    <br />calc_x000D_
    <br />_x000D_
  <div class="down">calc_x000D_
    <br />calc_x000D_
    <br />calc_x000D_
    <br />_x000D_
<div class="overflow container">_x000D_
  <div class="up">overflow_x000D_
    <br />overflow_x000D_
    <br />overflow_x000D_
    <br />_x000D_
  <div class="down">overflow_x000D_
    <br />overflow_x000D_
    <br />overflow_x000D_
    <br />_x000D_


CSS's grid layout offers yet another option, though it may not be as straightforward as the Flexbox model. However, it only requires styling the container element:

.container { display: grid; grid-template-rows: 100px }

The grid-template-rows defines the first row as a fixed 100px height, and the remain rows will automatically stretch to fill the remaining space.

I'm pretty sure IE11 requires -ms- prefixes, so make sure to validate the functionality in the browsers you wish to support.


CSS3's Flexible Box Layout Module (flexbox) is now well-supported and can be very easy to implement. Because it is flexible, it even works when #up does not have a defined height.

#container { display: flex; flex-direction: column; }
#down { flex-grow: 1; }

It's important to note that IE10 & IE11 support for some flexbox properties can be buggy, and IE9 or below has no support at all.

Calculated Height

Another easy solution is to use the CSS3 calc functional unit, as Alvaro points out in his answer, but it requires the height of the first child to be a known value:

#up { height: 100px; }
#down { height: calc( 100% - 100px ); }

It is pretty widely supported, with the only notable exceptions being <= IE8 or Safari 5 (no support) and IE9 (partial support). Some other issues include using calc in conjunction with transform or box-shadow, so be sure to test in multiple browsers if that is of concern to you.

Other Alternatives

If older support is needed, you could add height:100%; to #down will make the pink div full height, with one caveat. It will cause overflow for the container, because #up is pushing it down.

Therefore, you could add overflow: hidden; to the container to fix that.

Alternatively, if the height of #up is fixed, you could position it absolutely within the container, and add a padding-top to #down.

And, yet another option would be to use a table display:

#container { width: 300px; height: 300px; border: 1px solid red; display: table;}
#up { background: green; display: table-row; height: 0; }
#down { background: pink; display: table-row;}?

Cannot open Windows.h in Microsoft Visual Studio

Start Visual Studio. Go to Tools->Options and expand Projects and solutions. Select VC++ Directories from the tree and choose Include Files from the combo on the right.

You should see:


If this is missing, you found a problem. If not, search for a file. It should be located in

32 bit systems:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include

64 bit systems:

C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\Include

if VS was installed in the default directory.


T-SQL CASE Clause: How to specify WHEN NULL

CASE WHEN last_name IS NULL THEN '' ELSE ' '+last_name END

Duplicate / Copy records in the same MySQL table

You can alter the temporarily table to change the ID field to a bigint or so without the NOT NULL requirement, then set the ID to 0 in that temp table. After that add it back to the original table and the NULL will trigger the auto increment.

ALTER TABLE tmptable CHANGE id id bigint;
UPDATE tmptable SET id = NULL;

Executing multiple SQL queries in one statement with PHP

With mysqli you're able to use multiple statements for real using mysqli_multi_query().

Read more on multiple statements in the PHP Docs.

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

For those who want to use simpleUML in Android Studio and having issues in running SimpleUML.

First download simpleUML jar from here

Now follow the below steps.

Step 1:

Click on File and go to Settings (File ? Settings)

Step 2

Select Plugins from Left Panel and click Install plugin from disk


Step 3:

Locate the SimpleUML jar file and select it.


Step 4:

Now Restart Android Studio (File ? Invalidate Caches/Restart ? Just Restart)

Step 5:

After you restart Right Click the Package name and Select New Diagram or Add to simpleUML Diagram ? New Diagram.


Step 6:

Set a file name and create UML file. I created with name NewDiagram

enter image description here Step 7:

Now Right Click the Package name and Select the file you created. In my case it was NewDiagram

enter image description here

Step 8:

All files are stacked on top of one another. You can just drag and drop them and set a hierarchy.

enter image description here

Like this below, you can drag these classes

enter image description here

How do I output the difference between two specific revisions in Subversion?

To compare entire revisions, it's simply:

svn diff -r 8979:11390

If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:

svn diff -r PREV:HEAD

(Note, without anything specified afterwards, all files in the specified revisions are compared.)

You can compare a specific file if you add the file path afterwards:

svn diff -r 8979:HEAD /path/to/my/file.php

Show loading gif after clicking form submit using jQuery

The show() method only affects the display CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button element is a button and does not raise a submit event. You would need to change your selector to the form for that to work:

$('#login_form').submit(function() {
    $('#gif').css('visibility', 'visible');

Also note that return true; is redundant in your logic, so it can be removed.

How to get the location of the DLL currently executing?

You are looking for System.Reflection.Assembly.GetExecutingAssembly()

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");


The .Location property returns the location of the currently running DLL file.

Under some conditions the DLL is shadow copied before execution, and the .Location property will return the path of the copy. If you want the path of the original DLL, use the Assembly.GetExecutingAssembly().CodeBase property instead.

.CodeBase contains a prefix (file:\), which you may need to remove.

How to print jquery object/array

I was having similar problem and

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie

This solved my problem. Thanks Selvakumar Arumugam

MySQL Trigger after update only if row has changed

As a workaround, you could use the timestamp (old and new) for checking though, that one is not updated when there are no changes to the row. (Possibly that is the source for confusion? Because that one is also called 'on update' but is not executed when no change occurs) Changes within one second will then not execute that part of the trigger, but in some cases that could be fine (like when you have an application that rejects fast changes anyway.)

For example, rather than

IF NEW.a <> OLD.a or NEW.b <> OLD.b /* etc, all the way to NEW.z <> OLD.z */ 
  INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b) ;

you could use

IF NEW.ts <> OLD.ts 
  INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b) ;

Then you don't have to change your trigger every time you update the scheme (the issue you mentioned in the question.)

EDIT: Added full example

create table foo (a INT, b INT, ts TIMESTAMP);
create table bar (a INT, b INT);

INSERT INTO foo (a,b) VALUES(1,1);
INSERT INTO foo (a,b) VALUES(2,2);
INSERT INTO foo (a,b) VALUES(3,3);


        IF NEW.ts <> OLD.ts THEN  
            INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b);
        END IF;


select * from foo;
| a    | b    | ts                  |
|    1 |    1 | 2011-06-14 09:29:46 |
|    2 |    2 | 2011-06-14 09:29:46 |
|    3 |    3 | 2011-06-14 09:29:46 |
3 rows in set (0.00 sec)

-- UPDATE without change
UPDATE foo SET b = 3 WHERE a = 3;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

-- the timestamo didnt change
select * from foo WHERE a = 3;
| a    | b    | ts                  |
|    3 |    3 | 2011-06-14 09:29:46 |
1 rows in set (0.00 sec)

-- the trigger didn't run
select * from bar;
Empty set (0.00 sec)

-- UPDATE with change
UPDATE foo SET b = 4 WHERE a=3;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

-- the timestamp changed
select * from foo;
| a    | b    | ts                  |
|    1 |    1 | 2011-06-14 09:29:46 |
|    2 |    2 | 2011-06-14 09:29:46 |
|    3 |    4 | 2011-06-14 09:34:59 |
3 rows in set (0.00 sec)

-- and the trigger ran
select * from bar;
| a    | b    | ts                  |
|    3 |    4 | 2011-06-14 09:34:59 |
1 row in set (0.00 sec)

It is working because of mysql's behavior on handling timestamps. The time stamp is only updated if a change occured in the updates.

Documentation is here:

desc foo;
| Field | Type      | Null | Key | Default           | Extra                       |
| a     | int(11)   | YES  |     | NULL              |                             |
| b     | int(11)   | YES  |     | NULL              |                             |
| ts    | timestamp | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |

Constants in Kotlin -- what's a recommended way to create them?

You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants.kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file. The constants known at compile time must be marked with const.

So, in this case, it should be:

const val MY_CONST = "something"

and then you can import the constant using:

import package_name.MY_CONST

You can refer to this link

MySQL SELECT DISTINCT multiple columns

This will give DISTINCT values across all the columns:

    SELECT DISTINCT a AS value FROM my_table
    UNION SELECT DISTINCT b AS value FROM my_table
    UNION SELECT DISTINCT c AS value FROM my_table
) AS derived

Pandas read_csv from url

The problem you're having is that the output you get into the variable 's' is not a csv, but a html file. In order to get the raw csv, you have to modify the url to:


Your second problem is that read_csv expects a file name, we can solve this by using StringIO from io module. Third problem is that request.get(url).content delivers a byte stream, we can solve this using the request.get(url).text instead.

End result is this code:

from io import StringIO

import pandas as pd
import requests



>>> c.head()
    Country  Region
0   Algeria  AFRICA
1    Angola  AFRICA
2     Benin  AFRICA
3  Botswana  AFRICA
4   Burkina  AFRICA

What is __future__ in Python used for and how/when to use it, and how it works

There are some great answers already, but none of them address a complete list of what the __future__ statement currently supports.

Put simply, the __future__ statement forces Python interpreters to use newer features of the language.

The features that it currently supports are the following:


Prior to Python 2.1, the following code would raise a NameError:

def f():
    def g(value):
        return g(value-1) + 1

The from __future__ import nested_scopes directive will allow for this feature to be enabled.


Introduced generator functions such as the one below to save state between successive function calls:

def fib():
    a, b = 0, 1
    while 1:
       yield b
       a, b = b, a+b


Classic division is used in Python 2.x versions. Meaning that some division statements return a reasonable approximation of division ("true division") and others return the floor ("floor division"). Starting in Python 3.0, true division is specified by x/y, whereas floor division is specified by x//y.

The from __future__ import division directive forces the use of Python 3.0 style division.


Allows for parenthesis to enclose multiple import statements. For example:

from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,

Instead of:

from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \


from Tkinter import Tk, Frame, Button, Entry, Canvas, Text
from Tkinter import LEFT, DISABLED, NORMAL, RIDGE, END


Adds the statement with as a keyword in Python to eliminate the need for try/finally statements. Common uses of this are when doing file I/O such as:

with open('workfile', 'r') as f:
     read_data =


Forces the use of Python 3 parenthesis-style print() function call instead of the print MESSAGE style statement.


Introduces the literal syntax for the bytes object. Meaning that statements such as bytes('Hello world', 'ascii') can be simply expressed as b'Hello world'.


Replaces the use of the StopIteration exception used inside generator functions with the RuntimeError exception.

One other use not mentioned above is that the __future__ statement also requires the use of Python 2.1+ interpreters since using an older version will throw a runtime exception.


.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are:

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied

What are "res" and "req" parameters in Express functions?

Request and response.

To understand the req, try out console.log(req);.

Pointer arithmetic for void pointer in C

The C standard does not allow void pointer arithmetic. However, GNU C is allowed by considering the size of void is 1.

C11 standard §6.2.5

Paragraph - 19

The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

Following program is working fine in GCC compiler.


int main()
    int arr[2] = {1, 2};
    void *ptr = &arr;
    ptr = ptr + sizeof(int);
    printf("%d\n", *(int *)ptr);
    return 0;

May be other compilers generate an error.

Selecting multiple columns in a Pandas dataframe

You can use the pandas.DataFrame.filter method to either filter or reorder columns like this:

df1 = df.filter(['a', 'b'])

This is also very useful when you are chaining methods.

Python regex findall

Try this :

   for match in re.finditer(r"\[P[^\]]*\](.*?)\[/P\]", subject):
        # match start: match.start()
        # match end (exclusive): match.end()
        # matched text:

How to extract numbers from a string and get an array of ints?

If you want to exclude numbers that are contained within words, such as bar1 or aa1bb, then add word boundaries \b to any of the regex based answers. For example:

Pattern p = Pattern.compile("\\b-?\\d+\\b");
Matcher m = p.matcher("9There 9are more9 th9an -2 and less than 12 numbers here9");
while (m.find()) {



How to getText on an input in protractor

You can use jQuery to get text in textbox (work well for me), check in image detail


$(document.evaluate( "xpath" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()

$(document.evaluate( "//*[@id='mail']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()

Inject this above query to your code. Image detail:

enter image description here

How to create a temporary directory/folder in Java?

Do not use deleteOnExit() even if you explicitly delete it later.

Google 'deleteonexit is evil' for more info, but the gist of the problem is:

  1. deleteOnExit() only deletes for normal JVM shutdowns, not crashes or killing the JVM process.

  2. deleteOnExit() only deletes on JVM shutdown - not good for long running server processes because:

  3. The most evil of all - deleteOnExit() consumes memory for each temp file entry. If your process is running for months, or creates a lot of temp files in a short time, you consume memory and never release it until the JVM shuts down.

What is the command to truncate a SQL Server log file?

Another option altogether is to detach the database via Management Studio. Then simply delete the log file, or rename it and delete later.

Back in Management Studio attach the database again. In the attach window remove the log file from list of files.

The DB attaches and creates a new empty log file. After you check everything is all right, you can delete the renamed log file.

You probably ought not use this for production databases.

How do I create a folder in a GitHub repository?

To add a new directory all you have to do is create a new folder in your local repository. Create a new folder, and add a file in it.

Now go to your terminal and add it like you add the normal files in Git. Push them into the repository, and check the status to make sure you have created a directory.

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;

Wrapping long text without white space inside of a div

white-space: pre-wrap

is what worked for me for <span> and <div>.

Filter items which array contains any of given values

For those looking at this in 2020, you may notice that accepted answer is deprecated in 2020, but there is a similar approach available using terms_set and minimum_should_match_script combination.

Please see the detailed answer here in the SO thread

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

The following commands (modified after those found here) worked for me on my WSL install of Ubuntu after hours of trial and error:

sudo service mysql stop
sudo mysqld --skip-grant-tables &
mysql -u root mysql
UPDATE mysql.user SET authentication_string=null WHERE User='root';
flush privileges;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_new_password_here';
flush privileges;

How to send and receive JSON data from a restful webservice using Jersey API

For me, parameter (JSONObject inputJsonObj) was not working. I am using jersey 2.* Hence I feel this is the

java(Jax-rs) and Angular way

I hope it's helpful to someone using JAVA Rest and AngularJS like me.

public Map<String, String> methodName(String data) throws Exception {
    JSONObject recoData = new JSONObject(data);
    //Do whatever with json object

Client side I used AngularJS

factory.update = function () {
data = {user:'Shreedhar Bhat',address:[{houseNo:105},{city:'Bengaluru'}]};
        data= JSON.stringify(data);//Convert object to string
        var d = $q.defer();
            method: 'POST',
            url: 'REST/webApp/update',
            headers: {'Content-Type': 'text/plain'},
        .success(function (response) {
        .error(function (response) {

        return d.promise;

How do I print the full value of a long string in gdb?

There is a third option: the x command, which allows you to set a different limit for the specific command instead of changing a global setting. To print the first 300 characters of a string you can use x/300s your_string. The output might be a bit harder to read. For example printing a SQL query results in:

(gdb) x/300sb stmt.c_str()
0x9cd948:    "SELECT article.r"...
0x9cd958:    "owid FROM articl"...

How to get IP address of running docker container

Use --format option to get only the IP address instead whole container info:

sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}' <CONTAINER ID>

"use database_name" command in PostgreSQL

Use this commad when first connect to psql

=# psql <databaseName> <usernamePostgresql>

Temporary tables in stored procedures

Not really and I am talking about SQL Server. The temp table (with single #) exists and is visible within the scope it is created (scope-bound). Each time you call your stored procedure it creates a new scope and therefore that temp table exists only in that scope. I believe the temp tables are also visible to stored procedures and udfs that're called within that scope as well. If you however use double pound (##) then they become global within your session and therefore visible to other executing processes as part of the session that the temp table is created in and you will have to think if the possibility of temp table being accessed concurrently is desirable or not.

How to commit my current changes to a different branch in Git

You can just create a new branch and switch onto it. Commit your changes then:

git branch dirty
git checkout dirty
// And your commit follows ...

Alternatively, you can also checkout an existing branch (just git checkout <name>). But only, if there are no collisions (the base of all edited files is the same as in your current branch). Otherwise you will get a message.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I also experienced this error.

I add into header Content-Type: application/json. Following the change, my submissions succeed!

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

How to check empty DataTable

As from MSDN for GetChanges

A filtered copy of the DataTable that can have actions performed on it, and later be merged back in the DataTable using Merge. If no rows of the desired DataRowState are found, the method returns Nothing (null).

dataTable1 is null so just check before you iterate over it.

Why do I get "warning longer object length is not a multiple of shorter object length"?

You don't give a reproducible example but your warning message tells you exactly what the problem is.

memb only has a length of 10. I'm guessing the length of dih_y2$MemberID isn't a multiple of 10. When using ==, R spits out a warning if it isn't a multiple to let you know that it's probably not doing what you're expecting it to do. == does element-wise checking for equality. I suspect what you want to do is find which of the elements of dih_y2$MemberID are also in the vector memb. To do this you would want to use the %in% operator.

dih_col <- which(dih_y2$MemeberID %in% memb)

How to use KeyListener

In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):

public void setFocusable(boolean b) {

And by adding this to your constructor:


Or, if you are calling the function from a parent class/container:

JComponent childComponent = new JComponent();

And then doing all the KeyListener stuff mentioned by others.

How to view the roles and permissions granted to any database user in Azure SQL server instance?

Building on @tmullaney 's answer, you can also left join in the sys.objects view to get insight when explicit permissions have been granted on objects. Make sure to use the LEFT join:

SELECT DISTINCT pr.principal_id, AS [UserName], pr.type_desc AS [User_or_Role], pr.authentication_type_desc AS [Auth_Type], pe.state_desc,
    pe.permission_name, pe.class_desc, o.[name] AS 'Object' 
    FROM sys.database_principals AS pr 
    JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
    LEFT JOIN sys.objects AS o on (o.object_id = pe.major_id)

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

Maximum length for MD5 input/output

MD5 processes an arbitrary-length message into a fixed-length output of 128 bits, typically represented as a sequence of 32 hexadecimal digits.

Display HTML snippets in HTML

You could use a server side language like PHP to insert raw text:

  $str = <<<EOD
  <html lang="en">
    <meta charset="utf-8">
    <meta name="description" content="Minimal HTML5">
    <meta name="keywords" content="HTML5,Minimal">
    <title>This is the title</title>
    <link rel='stylesheet.css' href='style.css'>

then dump out the value of $str htmlencoded:

<div style="white-space: pre">
  <?php echo htmlentities($str); ?>

How to get an absolute file path in Python

You could use the new Python 3.4 library pathlib. (You can also get it for Python 2.6 or 2.7 using pip install pathlib.) The authors wrote: "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them."

To get an absolute path in Windows:

>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
>>> str(p)

Or on UNIX:

>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
>>> str(p)

Docs are here:

How to solve static declaration follows non-static declaration in GCC C code?

While gcc 3.2.3 was more forgiving of the issue, gcc 4.1.2 is highlighting a potentially serious issue for the linking of your program later. Rather then trying to suppress the error you should make the forward declaration match the function declaration.

If you intended for the function to be globally available (as per the forward declaration) then don't subsequently declare it as static. Likewise if it's indented to be locally scoped then make the forward declaration static to match.

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
        //scroll down

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

'import' and 'export' may only appear at the top level

I do not know how to solve this problem differently, but this is solved simply. The loader babel should be placed at the beginning of the array and everything works.

JSON forEach get Key and Value

Try something like this:

var prop;
for(prop in obj) {
    if(!obj.hasOwnProperty(prop)) continue;

    console.log(prop + " - "+ obj[prop]);

How to pass a type as a method parameter in Java

You should pass a Class...

private void foo(Class<?> t){
    if(t == String.class){ ... }
    else if(t == int.class){ ... }

private void bar()

ComboBox.SelectedText doesn't give me the SelectedText

I think you want to use

String status = "The status of my combobox is " + comboBoxTest.Text

SelectedText property from MSDN

Gets or sets the text that is selected in the editable portion of a ComboBox.

while Text property from MSDN

Gets or sets the text associated with this control.

String was not recognized as a valid DateTime " format dd/MM/yyyy"

Change Manually :

string s = date.Substring(3, 2) +"/" + date.Substring(0, 2) + "/" + date.Substring(6, 4);

From 11/22/2015 it will be converted in 22/11/2015

How do I update a model value in JavaScript in a Razor view?

You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.

It would look something like this:

function updatePostID(val, comment)

    var args = {};
    args.PostID = val;
    args.Comment = comment;

     type: "POST",
     url: controllerActionMethodUrlHere,
     contentType: "application/json; charset=utf-8",
     data: args,
     dataType: "json",
     success: function(msg) 
        // Something afterwards here



What is the worst programming language you ever worked with?


I had to learn it at the university. Hated every aspect of the language. Maybe our professors just made a dumb choice on the language implementation, but basically it worked like this:

  • There was no sourcecode you could browse. There was just a class-tree where you could create and edit the method implementations. No way to save the code other than to cut'n'paste them to a notepad. You could save sessions, but these are binary dumps.

  • The entire environment has been written in Smalltalk, and boy - was it slow. You could see the entire screen repaint every time you hit a key. The editor (that you had to use due to lack of load/save sourcecode) lacked basic edit-features like insert/override mode.

  • The language was pure in a way that it wasn't possible to terminate a loop early. All things that made programming easy and efficient are forbidden in the language.

  • Everything was an object. Override the comparison operator of a boolean and the entire system crashed.

The name 'model' does not exist in current context in MVC3

I was facing the same issue and then I find a solution. The solution is:

  1. Close Visual Studio
  2. Delete the SUO file
  3. Restart Visual Studio

The .suo file is a hidden file in the same folder where the .svn solution file exists. Hope, it'll work!

How to log a method's execution time exactly in milliseconds?

Here's a Swift 3 solution for bisecting code anywhere to find a long running process.

var increment: Int = 0

var incrementTime = NSDate()

struct Instrumentation {
    var title: String
    var point: Int
    var elapsedTime: Double

    init(_ title: String, _ point: Int, _ elapsedTime: Double) {
        self.title = title
        self.point = point
        self.elapsedTime = elapsedTime

var elapsedTimes = [Instrumentation]()

func instrument(_ title: String) {
    increment += 1
    let incrementedTime = -incrementTime.timeIntervalSinceNow
    let newPoint = Instrumentation(title, increment, incrementedTime)
    incrementTime = NSDate()

Usage: -

instrument("View Did Appear")

print("ELAPSED TIMES \(elapsedTimes)")

Sample output:-

ELAPSED TIMES [MyApp.SomeViewController.Instrumentation(title: "Start View Did Load", point: 1, elapsedTime: 0.040504038333892822), MyApp.SomeViewController.Instrumentation(title: "Finished Adding SubViews", point: 2, elapsedTime: 0.010585010051727295), MyApp.SomeViewController.Instrumentation(title: "View Did Appear", point: 3, elapsedTime: 0.56564098596572876)]

Why boolean in Java takes only true or false? Why not 1 or 0 also?

In c and C++ there is no data type called BOOLEAN Thats why it uses 1 and 0 as true false value. and in JAVA 1 and 0 are count as an INTEGER type so it produces error in java. And java have its own boolean values true and false with boolean data type.

happy programming..

Repeat string to certain length

This is one way to do it using a list comprehension, though it's increasingly wasteful as the length of the rpt string increases.

def repeat(rpt, length):
    return ''.join([rpt for x in range(0, (len(rpt) % length))])[:length]

Escaping Double Quotes in Batch Script

The escape character in batch scripts is ^. But for double-quoted strings, double up the quotes:

"string with an embedded "" character"

Array inside a JavaScript Object?

// define
var foo = {
  bar: ['foo', 'bar', 'baz']

// access[2]; // will give you 'baz'

Getting the array length of a 2D array in Java

If you have this array:

String [][] example = {{{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"}},
                       {{"Why?", "Where?", "When?", "Who?"}, {"Yes!"}}};

You can do this:


= 2


= 2


= 2


= 3


= 4

Getting checkbox values on submit

Just for printing you can use as below :




HTTP client timeout and server timeout

According to, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.

Getting Raw XML From SOAPMessage in Java

If you have a SOAPMessage or SOAPMessageContext, you can use a Transformer, by converting it to a Source via DOMSource:

            final SOAPMessage message = messageContext.getMessage();
            final StringWriter sw = new StringWriter();

            try {
                    new DOMSource(message.getSOAPPart()),
                    new StreamResult(sw));
            } catch (TransformerException e) {
                throw new RuntimeException(e);

            // Now you have the XML as a String:

This will take the encoding into account, so your "special characters" won't get mangled.

How to update Xcode from command line

I am now running OS Big Sur. xcode-select --install, and sudo xcode-select --reset did not resolve my issue, neither did the recommended subsequent softwareupdate --install -a command. For good measure, I tried the recommended download from Apple Downloads, but the Command Line Tools downloads available there are not compatible with my OS.

I upvoted the fix that resolved for me, sudo xcode-select --switch /Library/Developer/CommandLineTools/ and added this post for environment context.

Split string into array of characters?

Here's another way to do it in VBA.

Function ConvertToArray(ByVal value As String)
    value = StrConv(value, vbUnicode)
    ConvertToArray = Split(Left(value, Len(value) - 1), vbNullChar)
End Function
Sub example()
    Dim originalString As String
    originalString = "hi there"
    Dim myArray() As String
    myArray = ConvertToArray(originalString)
End Sub

Pass data to layout that are common to all pages

what i did is very simple and it's works

Declare Static property in any controller or you can make a data-class with static values if you want like this:

public static username = "Admin";
public static UserType = "Administrator";

These values can be updated by the controllers based on operations. later you can use them in your _Layout

In _layout.cshtml


Writelines writes lines without newline, Just fills the file

As we want to only separate lines, and the writelines function in python does not support adding separator between lines, I have written the simple code below which best suits this problem:

sep = "\n" # defining the separator
new_lines = sep.join(lines) # lines as an iterator containing line strings

and finally:

with open("file_name", 'w') as file:

and you are done.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

This means the remote vm is not listening to current port i solved this by adding the port in the vm server

Breaking/exit nested for in

I've experimented with typing "exit for" a few times and noticed it worked and VB didn't yell at me. It's an option I guess but it just looked bad.

I think the best option is similar to that shared by Tobias. Just put your code in a function and have it return when you want to break out of your loops. Looks cleaner too.

For Each item In itemlist
    For Each item1 In itemlist1
        If item1 = item Then
            Return item1
        End If

@RequestParam in Spring MVC handling optional parameters

As part of Spring 4.1.1 onwards you now have full support of Java 8 Optional (original ticket) therefore in your example both requests will go via your single mapping endpoint as long as you replace required=false with Optional for your 3 params logout, name, password:

@RequestMapping (value = "/submit/id/{id}", method = RequestMethod.GET,   
public String showLoginWindow(@PathVariable("id") String id,
                              @RequestParam(value = "logout") Optional<String> logout,
                              @RequestParam("name") Optional<String> username,
                              @RequestParam("password") Optional<String> password,
                              @ModelAttribute("submitModel") SubmitModel model,
                              BindingResult errors) throws LoginException {...}

RegEx to exclude a specific string constant

This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:

$var !~ /^foo$/
    or die "too much foo";

If not, you have to do something evil:

$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
    or die "too much foo";

That one basically says "if it starts with non-f, the rest can be anything; if it starts with f, non-o, the rest can be anything; otherwise, if it starts fo, the next character had better not be another o".

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The error you have is because -credential without -computername can't exist.

You can try this way:

Invoke-Command -Credential $migratorCreds  -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME

No String-argument constructor/factory method to deserialize from String value ('')

Use below code snippet This worked for me

ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"symbol\":\"ABCD\}";
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Trade trade = objectMapper.readValue(jsonString, new TypeReference<Symbol>() {});

Model Class

@JsonIgnoreProperties    public class Symbol {
    private String symbol;

Appending values to dictionary in Python

To append entries to the table:

for row in data:
    name = ???     # figure out the name of the drug
    number = ???   # figure out the number you want to append

To loop through the data:

for name, numbers in drug_dictionary.items():
    print name, numbers

What does "all" stand for in a makefile?

The manual for GNU Make gives a clear definition for all in its list of standard targets.

If the author of the Makefile is following that convention then the target all should:

  1. Compile the entire program, but not build documentation.
  2. Be the the default target. As in running just make should do the same as make all.

To achieve 1 all is typically defined as a .PHONY target that depends on the executable(s) that form the entire program:

.PHONY : all
all : executable

To achieve 2 all should either be the first target defined in the make file or be assigned as the default goal:


LINQ Join with Multiple Conditions in On Clause

You can't do it like that. The join clause (and the Join() extension method) supports only equijoins. That's also the reason, why it uses equals and not ==. And even if you could do something like that, it wouldn't work, because join is an inner join, not outer join.

How can I create a "Please Wait, Loading..." animation using jQuery?

With all due respect to other posts, you have here a very simple solution, using CSS3 and jQuery, without using any further external resources nor files.

    $('#submit').prop('disabled', true);_x000D_
  }, 3000);_x000D_
  outline-offset: none;_x000D_
.button {_x000D_
    display: inline-block;_x000D_
    padding: 6px 12px;_x000D_
    margin: 20px 8px;_x000D_
    font-size: 14px;_x000D_
    font-weight: 400;_x000D_
    line-height: 1.42857143;_x000D_
    text-align: center;_x000D_
    white-space: nowrap;_x000D_
    vertical-align: middle;_x000D_
    -ms-touch-action: manipulation;_x000D_
    cursor: pointer;_x000D_
    -webkit-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    background-image: none;_x000D_
    border: 2px solid transparent;_x000D_
    border-radius: 5px;_x000D_
    color: #000;_x000D_
    background-color: #b2b2b2;_x000D_
    border-color: #969696;_x000D_
.button_loader {_x000D_
  background-color: transparent;_x000D_
  border: 4px solid #f3f3f3;_x000D_
  border-radius: 50%;_x000D_
  border-top: 4px solid #969696;_x000D_
  border-bottom: 4px solid #969696;_x000D_
  width: 35px;_x000D_
  height: 35px;_x000D_
  -webkit-animation: spin 0.8s linear infinite;_x000D_
  animation: spin 0.8s linear infinite;_x000D_
@-webkit-keyframes spin {_x000D_
  0% { -webkit-transform: rotate(0deg); }_x000D_
  99% { -webkit-transform: rotate(360deg); }_x000D_
@keyframes spin {_x000D_
  0% { transform: rotate(0deg); }_x000D_
  99% { transform: rotate(360deg); }_x000D_
<script src=""></script>_x000D_
<input id="submit" class="button" type="submit" value="Submit" />

How to use table variable in a dynamic sql statement?

Using Temp table solves the problem but I ran into issues using Exec so I went with the following solution of using sp_executesql:

Create TABLE #tempJoin ( Old_ID int, New_ID int);

declare @table_name varchar(128);

declare @strSQL nvarchar(3072);

set @table_name = 'Object';

--build sql sting to execute
set @strSQL='INSERT INTO '+@table_name+' SELECT '+@columns+' FROM #tempJoin CJ
                        Inner Join '+@table_name+' sourceTbl On CJ.Old_ID = sourceTbl.Object_ID'

**exec sp_executesql @strSQL;**

Posting a File and Associated Data to a RESTful WebService preferably as JSON

You could try using library. You can set the request body to multipart and then add the file and json objects separately like so:

MultipartBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("uploadFile", uploadFile.getName(), okhttp3.RequestBody.create(uploadFile, MediaType.parse("image/png")))
                .addFormDataPart("file metadata", json)

        Request request = new Request.Builder()

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);


Jquery select this + class

What you are looking for is this:

$(".subclass", this).css("visibility","visible");

Add the this after the class $(".subclass", this)

Regular expression for first and last name

var name = document.getElementById('login_name').value; 
if ( name.length < 4  && name.length > 30 )
    alert ( 'Name length is mismatch ' ) ;

var pattern = new RegExp("^[a-z\.0-9 ]+$");
var return_value = var pattern.exec(name);
if ( return_value == null )
    alert ( "Please give valid Name");
    return false; 

Vue.js - How to properly watch for nested data

How if you want to watch a property for a while and then to un-watch it?

Or to watch a library child component property?

You can use the "dynamic watcher":

 '', //what you want to watch
 (newVal, oldVal) => {
    //execute your code here

The $watch returns an unwatch function which will stop watching if it is called.

var unwatch = vm.$watch('a', cb)
// later, teardown the watcher

Also you can use the deep option:

'someObject', () => {
    //execute your code here
{ deep: true }

Please make sure to take a look to docs

Encoding conversion in java

UTF-8 and UCS-2/UTF-16 can be distinguished reasonably easily via a byte order mark at the start of the file. If this exists then it's a pretty good bet that the file is in that encoding - but it's not a dead certainty. You may well also find that the file is in one of those encodings, but doesn't have a byte order mark.

I don't know much about ISO-8859-2, but I wouldn't be surprised if almost every file is a valid text file in that encoding. The best you'll be able to do is check it heuristically. Indeed, the Wikipedia page talking about it would suggest that only byte 0x7f is invalid.

There's no idea of reading a file "as it is" and yet getting text out - a file is a sequence of bytes, so you have to apply a character encoding in order to decode those bytes into characters.

Source by stackoverflow

How to add additional libraries to Visual Studio project?

Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:

  1. Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)

  2. Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.

  3. Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.

  4. Mash the build button.

Icons missing in jQuery UI

They arent missing, the path is wrong. Its looking in non-existent dir 'img' for a file that is in dir 'images'.

To fix either edit the file that declares the wrong path or as I did just make a softlink like

ln -s images img

jQuery serialize does not register checkboxes

One reason for using non-standard checkbox serialization that isn't addressed in the question or in of the current answers is to only deserialize (change) fields that were explicitly specified in the serialized data - e.g. when you are using jquery serialization and deserialization to/from a cookie to save and load prefererences.

Thomas Danemar implemented a modification to the standard serialize() method to optionally take a checkboxesAsBools option: - this is similar to the implementation listed above by @mydoghasworms, but also integrated into the standard serialize.

I've copied it to Github in case anyone has improvements to make at any point:

Additionally, the "jquery.deserialize" plugin will now correctly deserialize checkbox values serialized with checkboxesAsBools, and ignore checkboxes that are not mentioned in the serialized data:

Using routes in Express-js

Seems that only index.js get loaded when you require("./routes") . I used the following code in index.js to load the rest of the routes:

var fs = require('fs')
  , path = require('path');

  var route_fname = __dirname + '/' + file;
  var route_name = path.basename(route_fname, '.js');
  if(route_name !== 'index' && route_name[0] !== "."){ 
    exports[route_name] = require(route_fname)[route_name];

find all unchecked checkbox in jquery

$("input:checkbox:not(:checked)") Will get you the unchecked boxes.

How to detect pressing Enter on keyboard using jQuery?

The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');

How to stop VBA code running?

I do this a lot. A lot. :-)

I have got used to using "DoEvents" more often, but still tend to set things running without really double checking a sure stop method.

Then, today, having done it again, I thought, "Well just wait for the end in 3 hours", and started paddling around in the ribbon. Earlier, I had noticed in the "View" section of the Ribbon a "Macros" pull down, and thought I have a look to see if I could see my interminable Macro running....

I now realise you can also get this up using Alt-F8.

Then I thought, well what if I "Step into" a different Macro, would that rescue me? It did :-) It also works if you step into your running Macro (but you still lose where you're upto), unless you are a very lazy programmer like me and declare lots of "Global" variables, in which case the Global data is retained :-)


TextView bold via xml file?

I have a project in which I have the following TextView :


So, I'm guessing you need to use android:textStyle

How to draw a custom UIView that is just a circle - iPhone app

My contribution with a Swift extension:

extension UIView {
    func asCircle() {
        self.layer.cornerRadius = self.frame.width / 2;
        self.layer.masksToBounds = true

Just call myView.asCircle()

How to unzip a file using the command line?

If you already have Java Development Kit on your PC and the bin directory is in your path (in most cases), you can use the command line:

jar xf

or if not in your path:

C:\Java\jdk1.6.0_03\bin>jar xf

Complete set of options for the jar tool available here.


Extract jar file
    jar x[v]f jarfile [inputfiles] [-Joption] 
    jar x[v] [inputfiles] [-Joption]

Regex for allowing alphanumeric,-,_ and space


\w matches letters, digits, and underscores

\s matches spaces, tabs, and line breaks

- matches the hyphen (if you have hyphen in your character set example [a-z], be sure to place the hyphen at the beginning like so [-a-z])

How to get the current date and time of your timezone in Java?

Date in 24 hrs format

Output:14/02/2020 19:56:49 PM

 Date date = new Date();
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aa");
 System.out.println("date is: "+dateFormat.format(date));

Date in 12 hrs format

Output:14/02/2020 07:57:11 PM

 Date date = new Date();`enter code here`
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
 System.out.println("date is: "+dateFormat.format(date));

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

About the version of Android SDK Build-tools, the answer is

By default, the Android SDK uses the most recent downloaded version of the Build Tools.


In Eclipse, you can choose a specific version by using the sdk.buildtools property in the file.

There seems to be no official page explaining all the build tools. Here is what the Android team says about this.

The [build] tools, such as aidl, aapt, dexdump, and dx, are typically called by the Android build tools or Android Development Tools (ADT), so you rarely need to invoke these tools directly. As a general rule, you should rely on the build tools or the ADT plugin to call them as needed.


Anyway, here is a synthesis of the differences between tools, platform-tools and build-tools:

  • Android SDK Tools
    • Location: $ANDROID_HOME/tools
    • Main tools: ant scripts (to build your APKs) and ddms (for debugging)
  • Android SDK Platform-tools
    • Location: $ANDROID_HOME/platform-tools
    • Main tool: adb (to manage the state of an emulator or an Android device)
  • Android SDK Build-tools
    • Location: $ANDROID_HOME/build-tools/$VERSION/
    • Documentation
    • Main tools: aapt (to generate and unaligned, unsigned APKs), dx (to convert Java bytecode to Dalvik bytecode), and zipalign (to optimize your APKs)

How to convert timestamps to dates in Bash?

date -r <number>

works for me on Mac OS X.

Simplest way to throw an error/exception with a custom message in Swift 2?

Swift 4:

As per:

if you don't want to define a custom exception, you could use a standard NSError object as follows:

import Foundation

do {
  throw NSError(domain: "my error domain", code: 42, userInfo: ["ui1":12, "ui2":"val2"] ) 
catch let error as NSError {
  print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")
  let uis = error.userInfo 
  print("\tUser info:")
  for (key,value) in uis {
    print("\t\tkey=\(key), value=\(value)")


Caught NSError: The operation could not be completed, my error domain, 42
    User info:
        key=ui1, value=12
        key=ui2, value=val2

This allows you to provide a custom string (the error domain), plus a numeric code and a dictionary with all the additional data you need, of any type.

N.B.: this was tested on OS=Linux (Ubuntu 16.04 LTS).

Hibernate: How to set NULL query-parameter value with HQL?

Here is the solution I found on Hibernate 4.1.9. I had to pass a parameter to my query that can have value NULL sometimes. So I passed the using:

setParameter("orderItemId", orderItemId, new LongType())

After that, I use the following where clause in my query:

where ((:orderItemId is null) OR ( != :orderItemId))

As you can see, I am using the Query.setParameter(String, Object, Type) method, where I couldn't use the Hibernate.LONG that I found in the documentation (probably that was on older versions). For a full set of options of type parameter, check the list of implementation class of org.hibernate.type.Type interface.

Hope this helps!

How to handle AccessViolationException

In .NET 4.0, the runtime handles certain exceptions raised as Windows Structured Error Handling (SEH) errors as indicators of Corrupted State. These Corrupted State Exceptions (CSE) are not allowed to be caught by your standard managed code. I won't get into the why's or how's here. Read this article about CSE's in the .NET 4.0 Framework:

But there is hope. There are a few ways to get around this:

  1. Recompile as a .NET 3.5 assembly and run it in .NET 4.0.

  2. Add a line to your application's config file under the configuration/runtime element: <legacyCorruptedStateExceptionsPolicy enabled="true|false"/>

  3. Decorate the methods you want to catch these exceptions in with the HandleProcessCorruptedStateExceptions attribute. See for details.


Previously, I referenced a forum post for additional details. But since Microsoft Connect has been retired, here are the additional details in case you're interested:

From Gaurav Khanna, a developer from the Microsoft CLR Team

This behaviour is by design due to a feature of CLR 4.0 called Corrupted State Exceptions. Simply put, managed code shouldnt make an attempt to catch exceptions that indicate corrupted process state and AV is one of them.

He then goes on to reference the documentation on the HandleProcessCorruptedStateExceptionsAttribute and the above article. Suffice to say, it's definitely worth a read if you're considering catching these types of exceptions.

Best way to find os name and version in Unix/Linux platform

Following command worked out for me nicely. It gives you the OS name and version.

lsb_release -a

process.waitFor() never returns

I think I observed a similar problem: some processes started, seemed to run successfully but never completed. The function waitFor() was waiting forever except if I killed the process in Task Manager.
However, everything worked well in cases the length of the command line was 127 characters or shorter. If long file names are inevitable you may want to use environmental variables, which may allow you keeping the command line string short. You can generate a batch file (using FileWriter) in which you set your environmental variables before calling the program you actually want to run. The content of such a batch could look like:

    set INPUTFILE="C:\Directory 0\Subdirectory 1\AnyFileName"
    set OUTPUTFILE="C:\Directory 2\Subdirectory 3\AnotherFileName"
    set MYPROG="C:\Directory 4\Subdirectory 5\ExecutableFileName.exe"

Last step is running this batch file using Runtime.

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Note that when using nested conditional operators, you may want to use parenthesis to avoid possible issues!

It looks like PHP doesn't work the same way as at least Javascript or C#.

$score = 15;
$age = 5;

// The following will return "Exceptional"
echo 'Your score is: ' . ($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average'));

// The following will return "Horrible"
echo 'Your score is: ' . ($score > 10 ? $age > 10 ? 'Average' : 'Exceptional' : $age > 10 ? 'Horrible' : 'Average');

The same code in Javascript and C# return "Exceptional" in both cases.

In the 2nd case, what PHP does is (or at least that's what I understand):

  1. is $score > 10? yes
  2. is $age > 10? no, so the current $age > 10 ? 'Average' : 'Exceptional' returns 'Exceptional'
  3. then, instead of just stopping the whole statement and returning 'Exceptional', it continues evaluating the next statement
  4. the next statement becomes 'Exceptional' ? 'Horrible' : 'Average' which returns 'Horrible', as 'Exceptional' is truthy

From the documentation:

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.

How to Use Sockets in JavaScript\HTML?

I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.

How do I use Apache tomcat 7 built in Host Manager gui?

Host Manager is a web application inside of Tomcat that creates/removes Virtual Hosts within Tomcat.

A Virtual Host allows you to define multiple hostnames on a single server, so you can use the same server to handles requests to, for example, and

Unfortunately documentation on the GUI side of the Host Manager doesn't appear to exist, but documentation on configuring the virtual hosts manually in context.xml is here:

The full explanation of the Host parameters you can find here:

Adding a virtual host

Once you have access to the host-manager (see other answers on setting up the permissions, the GUI will let you add a (temporary - see edit at the end of this post) virtual host.

Tomcat Host Manager - Add Virtual Host Panel

At a minimum you need the Name and App Base fields defined. Tomcat will then create the following directories:

  • App Base will be where web applications will be deployed to the virtual host. Can be relative or absolute.
  • Name is usually the fully-qualified domain name (e.g.
  • Alias can be used to extend the Name also where two addresses should resolve to the same host (e.g. Note that this needs to be reflected in DNS records.

The checkboxes are as follows:

  • Auto Deploy: Automatically redeploy applications placed into App Base. Dangerous for Production environments!
  • Deploy On Startup: Automatically boot up applications under App Base when Tomcat starts
  • Deploy XML: Determines whether to parse the application's /META-INF/context.xml
  • Unpack WARs: Unpack WAR files placed or uploaded to the App Base, as opposed to running them directly from the WAR.
  • Tomcat 8 Copy XML: Copy an application's META-INF/context.xml to the App Base/XML Base on deployment, and use that exclusively, regardless of whether the application is updated. Irrelevant if Deploy XML is false.
  • Manager App: Add the manager application to the Virtual Host (Useful for controlling the applications you might have underneath

Update: After playing around with this same process on Tomcat8, the behaviour I'm seeing is that adding a virtual host via the GUI isn't persistent - it doesn't get written to server.xml, even on shutdown. Therefore (unless I'm doing something terribly wrong), you can create it in the GUI, but you'll need to edit server.xml anyway, as per the first link above, to make it stick.

How to save a list as numpy array in python?

I suppose, you mean converting a list into a numpy array? Then,

import numpy as np

# b is some list, then ...    
a = np.array(b).reshape(lengthDim0, lengthDim1);

gives you a as an array of list b in the shape given in reshape.

How do I update the password for Git?

If your credentials are stored in the credential helper, the portable way to remove a password persisted for a specific host is to call git credential reject:

$ git credential reject


$ git credential reject

After that, to enter your new password, type git fetch.

How do I define global variables in CoffeeScript?

To add to Ivo Wetzel's answer

There seems to be a shorthand syntax for exports ? this that I can only find documented/mentioned on a Google group posting.

I.e. in a web page to make a function available globally you declare the function again with an @ prefix:

<script type="text/coffeescript">
    @aglobalfunction = aglobalfunction = () ->
         alert "Hello!"

<a href="javascript:aglobalfunction()" >Click me!</a>

Facebook OAuth "The domain of this URL isn't included in the app's domain"

This usually happens if you have entered the wrong details when you created the App in Facebook. Or have you changed a URL's of an existing App?

Can you please recheck the settings of your APP in this page?

  1. Select the correct App and click in the edit button;

  2. Check the URLs & paths are correctly entered and are pointing to the site where you have installed Ultimate Facebook plugin.

Should each and every table have a primary key?

Will you ever need to join this table to other tables? Do you need a way to uniquely identify a record? If the answer is yes, you need a primary key. Assume your data is something like a customer table that has the names of the people who are customers. There may be no natural key because you need the addresses, emails, phone numbers, etc. to determine if this Sally Smith is different from that Sally Smith and you will be storing that information in related tables as the person can have mulitple phones, addesses, emails, etc. Suppose Sally Smith marries John Jones and becomes Sally Jones. If you don't have an artifical key onthe table, when you update the name, you just changed 7 Sally Smiths to Sally Jones even though only one of them got married and changed her name. And of course in this case withouth an artificial key how do you know which Sally Smith lives in Chicago and which one lives in LA?

You say you have no natural key, therefore you don't have any combinations of field to make unique either, this makes the artficial key critical.

I have found anytime I don't have a natural key, an artifical key is an absolute must for maintaining data integrity. If you do have a natural key, you can use that as the key field instead. But personally unless the natural key is one field, I still prefer an artifical key and unique index on the natural key. You will regret it later if you don't put one in.

Readably print out a python dict() sorted by key

The Python pprint module actually already sorts dictionaries by key. In versions prior to Python 2.5, the sorting was only triggered on dictionaries whose pretty-printed representation spanned multiple lines, but in 2.5.X and 2.6.X, all dictionaries are sorted.

Generally, though, if you're writing data structures to a file and want them human-readable and writable, you might want to consider using an alternate format like YAML or JSON. Unless your users are themselves programmers, having them maintain configuration or application state dumped via pprint and loaded via eval can be a frustrating and error-prone task.

how to add json library

AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

Create a button programmatically and set a background image

To set background we can no longer use forState, so we have to use for to set the UIControlState:

let zoomInImage = UIImage(named: "Icon - plus") as UIImage?
let zoomInButton = UIButton(frame: CGRect(x: 10), y: 10, width: 45, height: 45))
zoomInButton.setBackgroundImage(zoomInImage, for: UIControlState.normal)
zoomInButton.addTarget(self, action: #selector(self.mapZoomInAction), for: .touchUpInside)

How can I compile a Java program in Eclipse without running it?

You will need to go to Project->Clean...,then build your project. This will work, even when your source code does not contain any main method to run as an executable program. The .class files will appear in the bin folder of your project, in your workspace.

How can I convert a string to boolean in JavaScript?

Simplest solution

with ES6+

use the logical NOT twice [ !! ] to get the string converted

Just paste this expression...

const stringToBoolean = (string) => string === 'false' ? false : !!string

And pass your string to it!

stringToBoolean('')                 // false
stringToBoolean('false')            // false
stringToBoolean('true')             // true
stringToBoolean('hello my friend!') // true
const betterStringToBoolean = (string) => 
  string === 'false' || string === 'undefined' || string === 'null' || string === '0' ?
  false : !!string

You can include other strings at will to easily extend the usage of this expression...:

betterStringToBoolean('undefined')     // false
betterStringToBoolean('null')          // false
betterStringToBoolean('0')             // false
betterStringToBoolean('false')         // false
betterStringToBoolean('')              // false
betterStringToBoolean('true')          // true
betterStringToBoolean('anything else') // true

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response ="",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file = open("resp_content.txt", "w")