Programs & Examples On #Nvelocity

NVelocity is a port of the Apache Jakarta Velocity project. It is a simple, easy to learn and extensible template engine.

How do I compare two columns for equality in SQL Server?

I'd go with the CASE WHEN also.

Depending on what you actually want to do, there may be other options though, like using an outer join or whatever, but that doesn't seem to be what you need in this case.

What is a NullReferenceException, and how do I fix it?

Interestingly, none of the answers on this page mention the two edge cases, hope no one minds if I add them:

Edge case #1: concurrent access to a Dictionary

Generic dictionaries in .NET are not thread-safe and they sometimes might throw a NullReference or even (more frequent) a KeyNotFoundException when you try to access a key from two concurrent threads. The exception is quite misleading in this case.

Edge case #2: unsafe code

If a NullReferenceException is thrown by unsafe code, you might look at your pointer variables, and check them for IntPtr.Zero or something. Which is the same thing ("null pointer exception"), but in unsafe code, variables are often cast to value-types/arrays, etc., and you bang your head against the wall, wondering how a value-type can throw this exception.

(Another reason for non-using unsafe code unless you need it, by the way)

Edge case #3: Visual Studio multi monitor setup with secondary monitor(s) that has different DPI setting than the primary monitor

This edge case is software-specific and pertains to Visual Studio 2019 IDE (and possibly earlier versions).

Method to reproduce the problem: drag any component from the Toolbox to a Windows form on a non-primary monitor with different DPI setting than the primary monitor, and you get a pop-up with “Object reference not set to an instance of an object.” According to this thread this issue has been known for quite some time and at the time of writing it still hasn't been fixed.

XAMPP on Windows - Apache not starting

I was able to fix this!

Had the same problems as stated above, made sure nothing was using port 80 and still not working and getting the message that Apache and Mysql were detected with the wrong path.

I did install XAMPP once before, uninstalled and reinstalled. I even manually uninstalled but still had issues.

The fix. Make sure you backup your system first!

  1. Start Services via Control Panel>Admin Tools (also with Ctrl+R and services.msc)

  2. Look for Apache and MySQL services. Look at the patch indicated in the description (right click on service then click on properties). Chances are that you have Apache listed twice, one from your correct install and one from a previous install. Even if you only see one, look at the path, chances are it's from a previous install and causing your install not to work. In either case, you need to delete those incorrect services.

    a. Got to command prompt (run as administrator): Start > all programs > Accessories > right click on Command Prompt > Select 'run as administrator'

    b. on command prompt type sc delete service, where service is the service you're wanting to delete, such as apache2.1 (or sc delete Apache2.4). It should be exactly as it appears in your services. If the service has spaces such as Apache 2.1 then enter it in quotes, i.e. sc delete "Apache 2.1"

    c. press enter. Now refresh or close/open your services window and you'll see it`s gone.

DO THIS for all services that XAMPP finds as running with an incorrect path.

Once you do this, go ahead and restart the XAMPP control panel (as administrator) and voila! all works. No conflicts

Get length of array?

If the variant is empty then an error will be thrown. The bullet-proof code is the following:

Public Function GetLength(a As Variant) As Integer
   If IsEmpty(a) Then
      GetLength = 0
      GetLength = UBound(a) - LBound(a) + 1
   End If
End Function

SSIS Convert Between Unicode and Non-Unicode Error

I experienced this condition when I had installed Oracle version 12 client 32 bit client connected to an Oracle 12 Server running on windows. Although both of Oracle-source and SqlServer-destination are NOT Unicode, I kept getting this message, as if the oracle columns were Unicode. I solved the problem inserting a data conversion box, and selecting type DT-STR (not unicode) for varchar2 fields and DT-WSTR (unicode) for numeric fields, then I've dropped the 'COPY OF' from the output field name. Note that I kept getting the error because I had connected the source box arrow with the conversion box BEFORE setting the convertion types. So I had to switch source box and this cleaned all the errors in the destination box.

Java Returning method which returns arraylist?

Your method can be called and the arraylist can be stored like this

YourClassName class = new YourClassName();
Arraylist<Integer> numbers = class.numbers(); 

This also allows the arraylist to be manipulated further in this class

jQuery's is triggering a 404 (Not Found)

I was presented with the same issue. The cause for me was Grunt concatenating my JavaScript file.

I was using a ;\n as a separator which caused the path to the source map to 404.

So dev tools was looking for; instead of

I know that isn't the answer to the original question, but I am sure there are others out there with a similar Grunt configuration.

Encrypt and decrypt a String in java

Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.

I advice you to read more about cryptography on Wikipedia, Bruce Schneier and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of library.

If you are interested in cryptography the there is CrypTool: CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.

How to place object files in separate subdirectory

Since you're using GNUmake, use a pattern rule for compiling object files:

$(OBJDIR)/%.o: %.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<

How can I check a C# variable is an empty string "" or null?

if the variable is a string

bool result = string.IsNullOrEmpty(variableToTest);

if you only have an object which may or may not contain a string then

bool result = string.IsNullOrEmpty(variableToTest as string);

Node.js Port 3000 already in use but it actually isn't?

I have solved this problem because the MongoDB or there is another app u had run it before on this port, so to solve it kill the process from task manager, or just change the number of the port from 3000 to any other one.

How do you completely remove the button border in wpf?

You may already know that putting your Button inside of a ToolBar gives you this behavior, but if you want something that will work across ALL current themes with any sort of predictability, you'll need to create a new ControlTemplate.

Prashant's solution does not work with a Button not in a toolbar when the Button has focus. It also doesn't work 100% with the default theme in XP -- you can still see faint gray borders when your container Background is white.

Div 100% height works on Firefox but not in IE

I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).

Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:

#container {
    /* for IE */

How can I measure the similarity between two images?

How to measure similarity between two images entirely depends on what you would like to measure, for example: contrast, brightness, modality, noise... and then choose the best suitable similarity measure there is for you. You can choose from MAD (mean absolute difference), MSD (mean squared difference) which are good for measuring brightness...there is also available CR (correlation coefficient) which is good in representing correlation between two images. You could also choose from histogram based similarity measures like SDH (standard deviation of difference image histogram) or multimodality similarity measures like MI (mutual information) or NMI (normalized mutual information).

Because this similarity measures cost much in time, it is advised to scale images down before applying these measures on them.

How to easily resize/optimize an image size with iOS?

I ended up using Brads technique to create a scaleToFitWidth method in UIImage+Extensions if that's useful to anyone...

-(UIImage *)scaleToFitWidth:(CGFloat)width
    CGFloat ratio = width / self.size.width;
    CGFloat height = self.size.height * ratio;

    NSLog(@"W:%f H:%f",width,height);

    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [self drawInRect:CGRectMake(0.0f,0.0f,width,height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    return newImage;

then wherever you like

#import "UIImage+Extensions.h"

UIImage *newImage = [image scaleToFitWidth:100.0f];

Also worth noting you could move this further down into a UIView+Extensions class if you want to render images from a UIView

Changing datagridview cell color dynamically

If you want every cell in the grid to have the same background color, you can just do this:

dataGridView1.DefaultCellStyle.BackColor = Color.Green;

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

ngOnInit() is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

ngAfterViewInit() is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.

JavaScript: Object Rename Key

You can try lodash _.mapKeys.

var user = {_x000D_
  name: "Andrew",_x000D_
  id: 25,_x000D_
  reported: false_x000D_
var renamed = _.mapKeys(user, function(value, key) {_x000D_
  return key + "_" +;_x000D_
<script src=""></script>

Moment Js UTC to Local Time

Here is what I do using Intl api:

let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney

this will return a time zone name. Pass this parameter to the following function to get the time

let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});

let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});

you can also format the time with moment like this:

moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here:

Invert colors of an image in CSS or JavaScript

For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.

How to change a nullable column to not nullable in a Rails migration?

Rails 4 (other Rails 4 answers have problems):

def change
  change_column_null(:users, :admin, false, <put a default value here> )
  # change_column(:users, :admin, :string, :default => "")

Changing a column with NULL values in it to not allow NULL will cause problems. This is exactly the type of code that will work fine in your development setup and then crash when you try to deploy it to your LIVE production. You should first change NULL values to something valid and then disallow NULLs. The 4th value in change_column_null does exactly that. See documentation for more details.

Also, I generally prefer to set a default value for the field so I won't need to specify the field's value every time I create a new object. I included the commented out code to do that as well.

Remove a file from the list that will be committed

Maybe you could also use stash to store temporaly your modifications in a patch file and then reapply it (after a checkout to come back to the old version). This could be related to this other topic : How would I extract a single file (or changes to a file) from a git stash?.

What are some good Python ORM solutions?

Storm has arguably the simplest API:

from storm.locals import *

class Foo:
    __storm_table__ = 'foos'
    id = Int(primary=True)

class Thing:
    __storm_table__ = 'things'
    id = Int(primary=True)
    name = Unicode()
    description = Unicode()
    foo_id = Int()
    foo = Reference(foo_id,

db = create_database('sqlite:')
store = Store(db)

foo = Foo()
thing = Thing() = foo

And it makes it painless to drop down into raw SQL when you need to:

store.execute('UPDATE bars SET bar_name=? WHERE bar_id like ?', []) 

Declaring variables inside or outside of a loop

I think the best resource to answer your question would be the following post:

Difference between declaring variables before or in loop?

According to my understanding this thing would be language dependent. IIRC Java optimises this, so there isn't any difference, but JavaScript (for example) will do the whole memory allocation each time in the loop.In Java particularly I think the second would run faster when done profiling.

Nginx 403 forbidden for all files

Old question, but I had the same issue. I tried every answer above, nothing worked. What fixed it for me though was removing the domain, and adding it again. I'm using Plesk, and I installed Nginx AFTER the domain was already there.

Did a local backup to /var/www/backups first though. So I could easily copy back the files.

Strange problem....

How can I get npm start at a different directory?

This one-liner should work too:

(cd /path/to/your/app && npm start)

Note that the current directory will be changed to /path/to/your/app after executing this command. To preserve the working directory:

(cd /path/to/your/app && npm start && cd -)

I used this solution because a program configuration file I was editing back then didn't support specifying command line arguments.

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

function converToLocalTime(serverDate) {

    var dt = new Date(Date.parse(serverDate));
    var localDate = dt;
    var gmt = localDate;
        var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
        var localNow = new Date().getTimezoneOffset(); // get the timezone
        // offset in minutes
        var localTime = min - localNow; // get the local time

    var dateStr = new Date(localTime * 1000 * 60);
    // dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
    dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    return dateStr;

How to change the color of the axis, ticks and labels for a plot in matplotlib

As a quick example (using a slightly cleaner method than the potentially duplicate question):

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)


ax.tick_params(axis='x', colors='red')

alt text


[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]

How to write into a file in PHP?

In order to write to a file in PHP you need to go through the following steps:

  1. Open the file

  2. Write to the file

  3. Close the file

    $select = "data what we trying to store in a file";
    $file = fopen("/var/www/htdocs/folder/test.txt", "a");
    fwrite($file  , $select->__toString());
         fclose($file );

How can I run PowerShell with the .NET 4 runtime?

The other answers are from before 2012, and they focus on "hacking" PowerShell 1.0 or PowerShell 2.0 into targeting newer versions of the .NET Framework and Common Language Runtime (CLR).

However, as has been written in many comments, since 2012 (when PowerShell 3.0 came) a much better solution is to install the newest version of PowerShell. It will automatically target CLR v4.0.30319. This means .NET 4.0, 4.5, 4.5.1, 4.5.2, or 4.6 (expected in 2015) since all of these versions are in-place replacements of each other. Use $PSVersionTable or see the Determine installed PowerShell version thread if you are unsure of your PowerShell version.

At the time of writing, the newest version of PowerShell is 4.0, and it can be downloaded with the Windows Management Framework (Google search link).

Write a file on iOS

May be this is useful to you.

//Method writes a string to a text file
-(void) writeToTextFile{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 


//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
                        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
        NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
        //use simple alert from my library (see previous post for details)
        [ASFunctions alert:content];
        [content release];


c# how to add byte to byte array

Although internally it creates a new array and copies values into it, you can use Array.Resize<byte>() for more readable code. Also you might want to consider checking the MemoryStream class depending on what you're trying to achieve.

How to find all the tables in MySQL with specific column names in them?

To get all tables with columns columnA or ColumnB in the database YourDatabase:

    WHERE COLUMN_NAME IN ('columnA','ColumnB')
        AND TABLE_SCHEMA='YourDatabase';

Utils to read resource text file to String (Java)

For java 7:

new String(Files.readAllBytes(Paths.get(getClass().getResource("foo.txt").toURI())));

Responsive Google Map?

My Responsive [Solution] Google Map in Foundation 4 Modal


Create an external JavaScript file (i.e. mymap.js) with the following code

google.maps.visualRefresh = true; //Optional

var respMap;

function mymapini() {
    var mapPos = new google.maps.LatLng(-0.172175,1.5); //Set the coordinates
    var mapOpts = {
    zoom: 10, //You can change this according your needs
    disableDefaultUI: true, //Disabling UI Controls (Optional)
    center: mapPos, //Center the map according coordinates
    mapTypeId: google.maps.MapTypeId.ROADMAP

    respMap = new google.maps.Map(document.getElementById('mymap'),

    var mapMarker = new google.maps.Marker({
          position: mapPos,
          map: respMap,
          title: 'You can put any title'

    //This centers automatically to the marker even if you resize your window
    google.maps.event.addListener(respMap, 'idle', function() {
    window.setTimeout(function() {
    }, 250);    

google.maps.event.addDomListener(window, 'load', mymapini);

$("#modalOpen").click(function(){ //Use it like <a href="#" id="modalOpen"...
    $("#myModal").show(); //ID from the Modal <div id="myModal">...
    google.maps.event.trigger(respMap, 'resize');


Add the following code before the tag:

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

Add this to the modal code:

<div id="mymap"></div>


Add this to your stylesheet:

#mymap { margin: 0; padding: 0; width:100%; height: 400px;}

How can I use a batch file to write to a text file?

You can use echo, and redirect the output to a text file (see notes below):

rem Saved in D:\Temp\WriteText.bat
@echo off
echo This is a test> test.txt
echo 123>> test.txt
echo 245.67>> test.txt



D:\Temp>type test.txt
This is a test



  • @echo off turns off printing of each command to the console
  • Unless you give it a specific path name, redirection with > or >> will write to the current directory (the directory the code is being run in).
  • The echo This is a test > test.txt uses one > to overwrite any file that already exists with new content.
  • The remaining echo statements use two >> characters to append to the text file (add to), instead of overwriting it.
  • The type test.txt simply types the file output to the command window.

Setting up a websocket on Apache?

The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.

What is @RenderSection in MVC

Suppose if I have GetAllEmployees.cshtml


    <a asp-action="Create">Create New</a>
<table class="table">
         // do something ...
       // do something ...

   //Added my custom scripts in the scripts sections

@section Scripts
    <script src="~/js/customScripts.js"></script>

And another view "GetEmployeeDetails.cshtml" with no scripts


    <a asp-action="Create">Create New</a>
<table class="table">
       // do something ... 
       // do something ...

And my layout page "_layout.cshtml"

@RenderSection("Scripts", required: true)

So, when I navigate to GetEmployeeDetails.cshtml. I get the error that there is no section scripts to be rendered in GetEmployeeDetails.cshtml. If I change the flag in @RenderSection() from required : true to ``required : false`. It means render the scripts defined in the @section scripts of the views if present.Else, do nothing. And the refined approach would be in _layout.cshtml

@if (IsSectionDefined("Scripts"))
        @RenderSection("Scripts", required: true)

How can I display a messagebox in ASP.NET?

I use this and it works

public void Messagebox(string xMessage)
    Response.Write("<script>alert('" + xMessage + "')</script>");

And I call like this

    Messagebox("je suis la!");

How to update Git clone

If you want to fetch + merge, run

git pull

if you want simply to fetch :

git fetch

How to include external Python code to use in other files?

If you use:

import Math

then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.

If you want to import a module's functions without having to prefix them, you must explicitly name them, like:

from Math import Calculate, Add, Subtract

Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:

from Math import *

However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.

Remove rows not .isin('X')

You can use numpy.logical_not to invert the boolean array returned by isin:

In [63]: s = pd.Series(np.arange(10.0))

In [64]: x = range(4, 8)

In [65]: mask = np.logical_not(s.isin(x))

In [66]: s[mask]
0    0
1    1
2    2
3    3
8    8
9    9

As given in the comment by Wes McKinney you can also use


Non greedy (reluctant) regex matching in sed?

sed 's|\(http:\/\/www\.[a-z.0-9]*\/\).*|\1| works too

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

What is the value you're passing to the primary key (presumably "pk_OrderID")? You can set it up to auto increment, and then there should never be a problem with duplicating the value - the DB will take care of that. If you need to specify a value yourself, you'll need to write code to determine what the max value for that field is, and then increment that.

If you have a column named "ID" or such that is not shown in the query, that's fine as long as it is set up to autoincrement - but it's probably not, or you shouldn't get that err msg. Also, you would be better off writing an easier-on-the-eye query and using params. As the lad of nine years hence inferred, you're leaving your database open to SQL injection attacks if you simply plop in user-entered values. For example, you could have a method like this:

internal static int GetItemIDForUnitAndItemCode(string qry, string unit, string itemCode)
    int itemId;
    using (SqlConnection sqlConn = new SqlConnection(ReportRunnerConstsAndUtils.CPSConnStr))
        using (SqlCommand cmd = new SqlCommand(qry, sqlConn))
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@Unit", SqlDbType.VarChar, 25).Value = unit;
            cmd.Parameters.Add("@ItemCode", SqlDbType.VarChar, 25).Value = itemCode;
            itemId = Convert.ToInt32(cmd.ExecuteScalar());
    return itemId;

...that is called like so:

int itemId = SQLDBHelper.GetItemIDForUnitAndItemCode(GetItemIDForUnitAndItemCodeQuery, _unit, itemCode);

You don't have to, but I store the query separately:

public static readonly String GetItemIDForUnitAndItemCodeQuery = "SELECT PoisonToe FROM Platypi WHERE Unit = @Unit AND ItemCode = @ItemCode";

You can verify that you're not about to insert an already-existing value by (pseudocode):

bool alreadyExists = IDAlreadyExists(query, value) > 0;

The query is something like "SELECT COUNT FROM TABLE WHERE BLA = @CANDIDATEIDVAL" and the value is the ID you're potentially about to insert:

if (alreadyExists) // keep inc'ing and checking until false, then use that id value

Justin wants to know if this will work:

string exists = "SELECT 1 from AC_Shipping_Addresses where pk_OrderID = " _Order.OrderNumber; if (exists > 0)...

What seems would work to me is:

string existsQuery = string.format("SELECT 1 from AC_Shipping_Addresses where pk_OrderID = {0}", _Order.OrderNumber); 
// Or, better yet:
string existsQuery = "SELECT COUNT(*) from AC_Shipping_Addresses where pk_OrderID = @OrderNumber"; 
// Now run that query after applying a value to the OrderNumber query param (use code similar to that above); then, if the result is > 0, there is such a record.

Python: 'break' outside loop

Because the break statement is intended to break out of loops. You don't need to break out of an if statement - it just ends at the end.

Set Locale programmatically

Hope this help(in onResume):

Locale locale = new Locale("ru");
Configuration config = getBaseContext().getResources().getConfiguration();
config.locale = locale;

Can I write or modify data on an RFID tag?

It depends on the type of chip you are using, but nowerdays most chips you can write. It also depends on how much power you give your RFID device. To read you dont need allot of power and very little line of sight. To right you need them full insight and longer insight

Pass Arraylist as argument to function

Define it as

<return type> AnalyzeArray(ArrayList<Integer> list) {

How to set background color in jquery

You actually got it. Just forgot some quotes.

$(this).css({backgroundColor: 'red'});


$(this).css('background-color', 'red');

You don't need to pass over a map/object to set only one property. You can just put pass it as string. Note that if passing an object you cannot use a -. All CSS properties which have such a character are mapped with capital letters.

Reference: .css()

ASP.Net MVC 4 Form with 2 submit buttons/actions

With HTML5 you can use button[formaction]:

<form action="Edit">
  <button type="submit">Submit</button> <!-- Will post to default action "Edit" -->
  <button type="submit" formaction="Validate">Validate</button> <!-- Will override default action and post to "Validate -->

Difference between "char" and "String" in Java

char have any but one character (letters, numbers,...)

char example = 'x';

string can have zero characters or as many as you want

String example = "Here you can have anything";

Javascript Array inside Array - how can I call the child array name?

You've made an array of arrays (multidimensional), so options[0] in this case is the size array. you need to reference the first element of the child, which for you is: options[0][0].

If you wanted to loop through all entries you can use the for .. in ... syntax which is described here.

var a = [1,2,4,5,120,12];
for (var val in t) {

var b = ['S','M','L'];
var both = [a,b];

for (var val in both) {
     for(val2 in both[val]){console.log(both[val][val2])}

Python strftime - date without leading 0?

For %d you can convert to integer using int() then it'll automatically remove leading 0 and becomes integer. You can then convert back to string using str().

How to check if a string contains only numbers?

You can pass nothing if you don't need the returned integer like so

if integer.TryParse(number,nothing) then

Convert floats to ints in Pandas?

>>> import pandas as pd
>>> right = pd.DataFrame({'C': [1.002, 2.003], 'D': [1.009, 4.55], 'key': ['K0', 'K1']})
>>> print(right)
           C      D key
    0  1.002  1.009  K0
    1  2.003  4.550  K1
>>> right['C'] = right.C.astype(int)
>>> print(right)
       C      D key
    0  1  1.009  K0
    1  2  4.550  K1

How to get the input from the Tkinter Text Widget?

Here is how I did it with python 3.5.2:

from tkinter import *
def retrieve_input():

textBox=Text(root, height=2, width=10)
buttonCommit=Button(root, height=1, width=10, text="Commit", 
                    command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button


with that, when i typed "blah blah" in the text widget and pressed the button, whatever i typed got printed out. So i think that is the answer for storing user input from Text widget to variable.

How to move git repository with all branches from bitbucket to github?

It's very simple.

  1. Create a new empty repository in GitHub (without readme or license, you can add them later) and the following screen will show.

  2. In the import code option, paste your Bitbucket repo's URL and voilà!!

Click Import code

Add new value to an existing array in JavaScript

You don't need jQuery for that. Use regular javascript

var arr = new Array();
// or var arr = [];

Note: In javascript, you can also use Objects as Arrays, but still have access to the Array prototypes. This makes the object behave like an array:

var obj = new Object();, 'value');

will create an object that looks like:

    0: 'value',
    length: 1

You can access the vaules just like a normal array f.ex obj[0].

JSON Naming Convention (snake_case, camelCase or PascalCase)


There is no standard naming of keys in JSON. According to the Objects section of the spec:

The JSON syntax does not impose any restrictions on the strings used as names,...

Which means camelCase or snake_case should work fine.

Driving factors

Imposing a JSON naming convention is very confusing. However, this can easily be figured out if you break it down into components.

  1. Programming language for generating JSON

    • Python - snake_case
    • PHP - snake_case
    • Java - camelCase
    • JavaScript - camelCase
  2. JSON itself has no standard naming of keys

  3. Programming language for parsing JSON

    • Python - snake_case
    • PHP - snake_case
    • Java - camelCase
    • JavaScript - camelCase

Mix-match the components

  1. Python » JSON » Python - snake_case - unanimous
  2. Python » JSON » PHP - snake_case - unanimous
  3. Python » JSON » Java - snake_case - please see the Java problem below
  4. Python » JSON » JavaScript - snake_case will make sense; screw the front-end anyways
  5. Python » JSON » you do not know - snake_case will make sense; screw the parser anyways
  6. PHP » JSON » Python - snake_case - unanimous
  7. PHP » JSON » PHP - snake_case - unanimous
  8. PHP » JSON » Java - snake_case - please see the Java problem below
  9. PHP » JSON » JavaScript - snake_case will make sense; screw the front-end anyways
  10. PHP » JSON » you do not know - snake_case will make sense; screw the parser anyways
  11. Java » JSON » Python - snake_case - please see the Java problem below
  12. Java » JSON » PHP - snake_case - please see the Java problem below
  13. Java » JSON » Java - camelCase - unanimous
  14. Java » JSON » JavaScript - camelCase - unanimous
  15. Java » JSON » you do not know - camelCase will make sense; screw the parser anyways
  16. JavaScript » JSON » Python - snake_case will make sense; screw the front-end anyways
  17. JavaScript » JSON » PHP - snake_case will make sense; screw the front-end anyways
  18. JavaScript » JSON » Java - camelCase - unanimous
  19. JavaScript » JSON » JavaScript - camelCase - Original

Java problem

snake_case will still make sense for those with Java entries because the existing JSON libraries for Java are using only methods to access the keys instead of using the standard dot.syntax. This means that it wouldn't hurt that much for Java to access the snake_cased keys in comparison to the other programming language which can do the dot.syntax.

Example for Java's org.json package


Example for Java's package


Some actual implementations


Choosing the right JSON naming convention for your JSON implementation depends on your technology stack. There are cases where one can use snake_case, camelCase, or any other naming convention.

Another thing to consider is the weight to be put on the JSON-generator vs the JSON-parser and/or the front-end JavaScript. In general, more weight should be put on the JSON-generator side rather than the JSON-parser side. This is because business logic usually resides on the JSON-generator side.

Also, if the JSON-parser side is unknown then you can declare what ever can work for you.

Jquery Date picker Default Date

$( ".selector" ).datepicker({ defaultDate: null });

and return empty string from backend

Is there a "null coalescing" operator in JavaScript?

Logical nullish assignment, 2020+ solution

A new operator is currently being added to the browsers, ??=. This combines the null coalescing operator ?? with the assignment operator =.

NOTE: This is not common in public browser versions yet. Will update as availability changes.

??= checks if the variable is undefined or null, short-circuiting if already defined. If not, the right-side value is assigned to the variable.

Basic Examples

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

Object/Array Examples

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar" ??= "buzz"  // "fizz" ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

Browser Support Sept 2020 - 3.7%

Mozilla Documentation

Field 'browser' doesn't contain a valid alias configuration

In my case, it was due to a broken symlink when trying to npm link a custom angular library to consuming app. After running npm link @authoring/canvas

"@authoring/canvas": "path/to/ui-authoring-canvas/dist"

It appear everything was OK but the module still couldn't be found:

Error from npm link

When I corrected the import statement to something that the editor could find Link:

import {CirclePackComponent} from '@authoring/canvas/lib/circle-pack/circle-pack.component';

I received this which is mention in the overflow thread:

Field Browser doesn't contain a valid alias configuration

To fix this I had to:

  1. cd /usr/local/lib/node_modules/packageName
  2. cd ..
  3. rm -rf packageName
  4. In the root directory of the library, run:
a) rm -rf dist
b) npm run build
c) cd dist 
d) npm link
  1. In the consuming app, update the package.json with:
"packageName": "file:/path/to/local/node_module/packageName""
  1. In the root directory of the consuming app run npm link packageName

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

  1. Go to Sql Server Management Studio >
  2. Object Explorer >
  3. Databases >
  4. Choose and expand your Database.
  5. Under your database right click on "Database Diagrams" and select "New Database Diagram".
  6. It will a open a new window. Choose tables to include in ER-Diagram (to select multiple tables press "ctrl" or "shift" button and select tables).
  7. Click add.
  8. Wait for it to complete. Done!

You can save generated diagram for future use.


Find a file in python

SARose's answer worked for me until I updated from Ubuntu 20.04 LTS. The slight change I made to his code makes it work on the latest Ubuntu release.

import subprocess

def find_files(file_name):
    command = ['locate'+ ' ' + file_name]
    output = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
    output = output.decode()
    search_results = output.split('\n')
    return search_results

'Framework not found' in Xcode

If you are developing one module using cocoapods, try to comment the line

s.vendored_frameworks = "YOURMODULE.framework"

on YOURMODULE.podspec

The error will disappear after you generate and copy your YOURMODULE.framework to your project folder.

Relative imports in Python 3

I had a similar problem and solved it by creating a symbolic link to the package in the working directory:

ln -s ../../../my_package my_package

and then import it as usual:

import my_package

I know this is more like a "Linux" solution rather than a "Python" solution. but it's a valid approach nonetheless.

Django request get parameters

You can use [] to extract values from a QueryDict object like you would any ordinary dictionary.

# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]

# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]

# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]

Change the location of the ~ directory in a Windows install of Git Bash

In my case, all I had to do was add the following User variable on Windows:

Variable name: HOME
Variable value: %USERPROFILE%

How to set a Environment Variable (You can use the User variables for username section if you are not a system administrator)

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

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

root_url(:only_path => false)

Duplicate and rename Xcode project & associated folders

I am using this script after I rename my iOS Project. It helps to change the directories name and make the names in sync.

NOTE: you will need to manually change the scheme's name.

How can I compare two ordered lists in python?

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.

In case you want to compare elements, you can use numpy for comparison

c = (numpy.array(a) == numpy.array(b))

Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.

What is the proper way to test if a parameter is empty in a batch file?

You can use

if defined (variable) echo That's defined!
if not defined (variable) echo Nope. Undefined.

Prevent double submission of forms in jQuery

Change submit button:

<input id="submitButtonId" type="submit" value="Delete" />

With normal button:

<input id="submitButtonId" type="button" value="Delete" />

Then use click function:

$("#submitButtonId").click(function () {
        $('#submitButtonId').prop('disabled', true);

And remember re-enable button when is necesary:

$('#submitButtonId').prop('disabled', false);

How to add items to array in nodejs

var array = [];

//length array now = 0
array[array.length] = 'hello';
//length array now = 1
//            0
//array = ['hello'];//length = 1

How to save and load cookies using Python + Selenium WebDriver

This is code I used in Windows. It works.

for item in COOKIES.split(';'):
    name,value = item.split('=', 1)
    name=name.replace(' ', '').replace('\r', '').replace('\n', '')
    value = value.replace(' ', '').replace('\r', '').replace('\n', '')
            "domain": "",  # Google Chrome
            "expires": "",
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False

What does %s and %d mean in printf in the C language?

%s is for string %d is for decimal (or int) %c is for character

It appears to be chewing through an array of characters, and printing out whatever string exists starting at each subsequent position. The strings will stop at the first null in each case.

The commas are just separating the arguments to a function that takes a variable number of args; this number corresponds to the number of % args in the format descriptor at the front.

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

Well, I guess the other posters have provided you with a means to directly include an @section within your partial (by using 3rd party html helpers).

But, I reckon that, if your script is tightly coupled to your partial, just put your javascript directly inside an inline <script> tag within your partial and be done with it (just be careful of script duplication if you intend on using the partial more than once in a single view);

Bootstrap full responsive navbar with logo or brand name text

Just set the height and width where you are adding that logo. I tried and its working fine

How can I clear the input text after clicking

          $('#myinput').attr('value', '');_x000D_
<script src=""></script>_x000D_
  <button class="mybtn">CLEAR</button>_x000D_
  <input type="text" id="myinput" name="myinput" value="?????????">

How to add 'libs' folder in Android Studio?

also you should click right button on mouse at your projectname and choose "open module settings" or press F4 button. Then on "dependencies" tab add your lib.jar to declare needed lib

PHP remove all characters before specific string

You can use substring and strpos to accomplish this goal.

You could also use a regular expression to pattern match only what you want. Your mileage may vary on which of these approaches makes more sense.

pyplot axes labels for subplots

Wen-wei Liao's answer is good if you are not trying to export vector graphics or that you have set up your matplotlib backends to ignore colorless axes; otherwise the hidden axes would show up in the exported graphic.

My answer suplabel here is similar to the fig.suptitle which uses the fig.text function. Therefore there is no axes artist being created and made colorless. However, if you try to call it multiple times you will get text added on top of each other (as fig.suptitle does too). Wen-wei Liao's answer doesn't, because fig.add_subplot(111) will return the same Axes object if it is already created.

My function can also be called after the plots have been created.

def suplabel(axis,label,label_prop=None,
    ''' Add super ylabel or xlabel to the figure
    Similar to matplotlib.suptitle
    axis       - string: "x" or "y"
    label      - string
    label_prop - keyword dictionary for Text
    labelpad   - padding from the axis (default: 5)
    ha         - horizontal alignment (default: "center")
    va         - vertical alignment (default: "center")
    fig = pylab.gcf()
    xmin = []
    ymin = []
    for ax in fig.axes:
    xmin,ymin = min(xmin),min(ymin)
    dpi = fig.dpi
    if axis.lower() == "y":
        x = xmin-float(labelpad)/dpi
        y = 0.5
    elif axis.lower() == 'x':
        rotation = 0.
        x = 0.5
        y = ymin - float(labelpad)/dpi
        raise Exception("Unexpected axis: x or y")
    if label_prop is None: 
        label_prop = dict()

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

Before you apply the suggested solution, you can check what is the Unicode character that appeared in your file (and in the error log), in this case 0x90: (or directly at Unicode Consortium site by searching 0x0090)

and then consider removing it from the file.

How to format column to number format in Excel sheet?

If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe

Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value

But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version

Sub CommandClick()

    Dim rCell As Range
    Dim rNext As Range

    For Each rCell In Sheet2.Range("C1:C30000").Cells
        If rCell.Value >= 100 And rCell.Value < 1000 Then
            Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
            rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
        End If
    Next rCell

End Sub

How to Check byte array empty or not?

Your check should be:

if (Attachment != null  && Attachment.Length > 0)

First check if the Attachment is null and then lenght, since you are using && that will cause short-circut evaluation

&& Operator (C# Reference)

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

Previously you had the condition like: (Attachment.Length > 0 && Attachment != null), since the first condition is accessing the property Length and if Attachment is null, you end up with the exception, With the modified condition (Attachment != null && Attachment.Length > 0), it will check for null first and only moves further if Attachment is not null.

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        this.handleClick = this.handleClick.bind(this);
    handleClick() {
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

    render() {
        return (
               profileCollapsed={this.state.profileCollapsed} />

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Docker Error bind: address already in use

I was getting the below error when i was trying to launch a new conatier- listen tcp bind: address already in use.

Solution: netstat -tulnp | grep 8080

[[email protected] (aws_main) ~]# netstat -tulnp | grep 8080 tcp 0 0* LISTEN 12749/java [[email protected] (aws_main) ~]#

kill -9 12749

Then try to relaunch the container it should work

How to find out which package version is loaded in R?

You can use sessionInfo() to accomplish that.

> sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: x86_64-pc-linux-gnu (64-bit)

 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=C                 LC_NAME=C                 

attached base packages:
[1] graphics  grDevices utils     datasets  stats     grid      methods   base     

other attached packages:
[1] ggplot2_0.9.0  reshape2_1.2.1 plyr_1.7.1    

loaded via a namespace (and not attached):
 [1] colorspace_1.1-1   dichromat_1.2-4    digest_0.5.2       MASS_7.3-18        memoise_0.1        munsell_0.3       
 [7] proto_0.3-9.2      RColorBrewer_1.0-5 scales_0.2.0       stringr_0.6       

However, as per comments and the answer below, there are better options

> packageVersion("snow")

[1] ‘0.3.9’


"Rmpi" %in% loadedNamespaces()

Microsoft Excel ActiveX Controls Disabled?

I did finally find this answer on the official Microsoft KB:

No new information here than what we have in previous answers, but at least it acknowledges that Microsoft is aware of the issue.

Bash integer comparison

I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)

case "$1" in
    0|1) xinput set-prop 12 "Device Enabled" $1 ;;
      *) echo "This script requires a 1 or 0 as first parameter." ;;

OSError - Errno 13 Permission denied

supplementing @falsetru's answer : run id in the terminal to get your user_id and group_id

Go the directory/partition where you are facing the challenge. Open terminal, type id then press enter. This will show you your user_id and group_id

then type

chown -R user-id:group-id .

Replace user-id and group-id

. at the end indicates current partition / repository

// chown -R 1001:1001 . (that was my case)

PHP 7 simpleXML

Had the same problem on AWS Linux 2, phpinfo() shows SimpleXML installed but not working, below cmd solved my issue

sudo yum install php-xml

Android ListView Text Color

I cloned the simple_list_item_1(Alt + Click) and placed the copy on my res/layout folder, renamed it to list_white_text.xml with this contents:

<?xml version="1.0" encoding="utf-8"?>    
<TextView xmlns:android=""
    android:minHeight="?android:attr/listPreferredItemHeightSmall" />

The android:textColor="@color/abc_primary_text_material_dark" translates to white on my device.

then in the java code:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_white_text, myList);

How to make a JSONP request from Javascript without JQuery?

Please find below JavaScript example to make a JSONP call without JQuery:

Also, you can refer my GitHub repository for reference.

window.onload = function(){_x000D_
    var callbackMethod = 'callback_' + new Date().getTime();_x000D_
    var script = document.createElement('script');_x000D_
    script.src = ''+callbackMethod;_x000D_
    window[callbackMethod] = function(data){_x000D_
        delete window[callbackMethod];_x000D_

Automatically create an Enum based on values in a database lookup table?

I don't think there is a good way of doing what you want. And if you think about it I don't think this is what you really want.

If you would have a dynamic enum, it also means you have to feed it with a dynamic value when you reference it. Maybe with a lot of magic you could achieve some sort of IntelliSense that would take care of this and generate an enum for you in a DLL file. But consider the amount of work it would take, how uneffective it would be to access the database to fetch IntelliSense information as well as the nightmare of version controlling the generated DLL file.

If you really don't want to manually add the enum values (you'll have to add them to the database anyway) use a code generation tool instead, for example T4 templates. Right click+run and you got your enum statically defined in code and you get all the benefits of using enums.

Using multiprocessing.Process with a maximum number of simultaneous processes

It might be most sensible to use multiprocessing.Pool which produces a pool of worker processes based on the max number of cores available on your system, and then basically feeds tasks in as the cores become available.

The example from the standard docs ( shows that you can also manually set the number of cores:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes
    result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
    print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
    print, range(10))          # prints "[0, 1, 4,..., 81]"

And it's also handy to know that there is the multiprocessing.cpu_count() method to count the number of cores on a given system, if needed in your code.

Edit: Here's some draft code that seems to work for your specific case:

import multiprocessing

def f(name):
    print 'hello', name

if __name__ == '__main__':
    pool = multiprocessing.Pool() #use all available cores, otherwise specify the number you want as an argument
    for i in xrange(0, 512):
        pool.apply_async(f, args=(i,))

How to give color to each class in scatter plot in R?

Assuming the class variable is z, you can use:

with(df, plot(x, y, col = z))

however, it's important that z is a factor variable, as R internally stores factors as integers.

This way, 1 is 'black', 2 is 'red', 3 is 'green, ....

Allow multi-line in EditText view in Android?

Just add this android:inputType="textMultiLine" in XML file on relevant field.

How to get WordPress post featured image URL

This is the simplest answer:

    $img = get_the_post_thumbnail_url($postID, 'post-thumbnail');

wget can't download - 404 error

You need to add the referer field in the headers of the HTTP request. With wget, you just need the --header arg :

wget --header "Referer:"

And the result :

--2011-10-02 02:00:18--
Résolution de (
Connexion vers (||:80...connecté.
requête HTTP transmise, en attente de la réponse...200 OK
Longueur: 6102 (6,0K) [image/jpeg]
Sauvegarde en : «logo.jpg»

Datatables warning(table id = 'example'): cannot reinitialise data table

Add "bDestroy": true in your dataTable Like:-

    stateSave: true,
    "bDestroy": true

It Will Work.

Create numpy matrix filled with NaNs

Are you familiar with numpy.nan?

You can create your own method such as:

def nans(shape, dtype=float):
    a = numpy.empty(shape, dtype)
    return a



would output

array([[ NaN,  NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN,  NaN]])

I found this code in a mailing list thread.

Convert column classes in data.table

Here is the same way as @Nera suggested to check the class first but instead of using .SD is to use the fast loop of data.table with set as @Matt Dowle solution with added class check.

for (j in seq_len(ncol(DT))){
  if(class(DT[[j]]) == 'factor')
    set(DT, j = j, value = as.character(DT[[j]]))

Use Font Awesome icon as CSS content

You should have font-weight set to 900 for Font Awesome 5 Free font-family to work.

This is the working one:

.css-selector::before {
   font-family: 'Font Awesome 5 Free';
   content: "\f101";
   font-weight: 900;

Sublime 3 - Set Key map for function Goto Definition

To set go to definition to alt + d. From the Menu Preferences > Key Bindings-User. And then add the following JSON.

    { "keys": ["alt+d"], "command": "goto_definition" }

How do you display a Toast from a background thread on Android?

You can do it by calling an Activity's runOnUiThread method from your thread:

activity.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();

How to add an extra source directory for maven to compile and include in the build jar?

NOTE: This solution will just move the java source files to the target/classes directory and will not compile the sources.

Update the pom.xml as -


How do I uninstall a package installed using npm link?

"npm install" replaces all dependencies in your node_modules installed with "npm link" with versions from npmjs (specified in your package.json)

Android Button Onclick

You need to make the same method name both in layout XML and java code.

If you use android:onClick="setLogin" then you need to make a method with the same name, setLogin:

// Please be noted that you need to add the "View v" parameter
public void setLogin(View v) {


Do not mix layout with code by using android:onClick tag in your XML. Instead, move the click method to your class with OnClickListener method like:

Button button = (Button) findViewById(;
button.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    // TODO Auto-generated method stub

Make a layout just for layout and no more. It will save your precious time when you need to refactoring for Supporting Multiple Screens.

Hash function that produces short hashes?

It is now 2019 and there are better options. Namely, xxhash.

~ echo test | xxhsum                                                           
2d7f1808da1fa63c  stdin

Python: Get the first character of the first string in a list?

You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list


mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

Matplotlib scatter plot legend

Here's an easier way of doing this (source: here):

import matplotlib.pyplot as plt
from numpy.random import rand

fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
    n = 750
    x, y = rand(2, n)
    scale = 200.0 * rand(n)
    ax.scatter(x, y, c=color, s=scale, label=color,
               alpha=0.3, edgecolors='none')


And you'll get this:

enter image description here

Take a look at here for legend properties

How to get the Enum Index value in C#

Another way to convert an Enum-Type to an int:

enum E
    A = 1,   /* index 0 */
    B = 2,   /* index 1 */
    C = 4,   /* index 2 */
    D = 4    /* index 3, duplicate use of 4 */

void Main()
    E e = E.C;
    int index = Array.IndexOf(Enum.GetValues(e.GetType()), e);
    // index is 2

    E f = (E)(Enum.GetValues(e.GetType())).GetValue(index);
    // f is  E.C

More complex but independent from the INT values assigned to the enum values.

Git:nothing added to commit but untracked files present

You have two options here. You can either add the untracked files to your Git repository (as the warning message suggested), or you can add the files to your .gitignore file, if you want Git to ignore them.

To add the files use git add:

git add Optimization/language/languageUpdate.php
git add email_test.php

To ignore the files, add the following lines to your .gitignore:


Either option should allow the git pull to succeed afterwards.

Use URI builder in Android or create URL with variables

Using appendEncodePath() could save you multiple lines than appendPath(), the following code snippet builds up this url:

Uri.Builder urlBuilder = new Uri.Builder();
urlBuilder.appendQueryParameter("zip", "94043,us");
URL url = new URL(;

How to create a blank/empty column with SELECT query in oracle?

I guess you will get ORA-01741: illegal zero-length identifier if you use the following

SELECT "" AS Contact  FROM Customers;

And if you use the following 2 statements, you will be getting the same null value populated in the column.

SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;

How to properly use unit-testing's assertRaises() with NoneType objects?

The usual way to use assertRaises is to call a function:

self.assertRaises(TypeError, test_function, args)

to test that the function call test_function(args) raises a TypeError.

The problem with self.testListNone[:1] is that Python evaluates the expression immediately, before the assertRaises method is called. The whole reason why test_function and args is passed as separate arguments to self.assertRaises is to allow assertRaises to call test_function(args) from within a try...except block, allowing assertRaises to catch the exception.

Since you've defined self.testListNone = None, and you need a function to call, you might use operator.itemgetter like this:

import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))



is a long-winded way of saying self.testListNone[:1], but which separates the function (operator.itemgetter) from the arguments.

jquery getting post action url

Try this ocde;;

var formAction = $("#signup").attr('action');

Getting the current date in visual Basic 2008

You may just want:

Dim regDate As Date = Date.Today()

Angular Material: mat-select not selecting default

You should be binding it as [value] in the mat-option as below,

<mat-select placeholder="Panel color" [(value)]="selected2">
  <mat-option *ngFor="let option of options2" [value]="">
    {{ }}


Get domain name from given url

Here is a short and simple line using InternetDomainName.topPrivateDomain() in Guava: InternetDomainName.from(new URL(url).getHost()).topPrivateDomain().toString()

Given, that will give you Or, given, it will give you

As Sa Qada commented in another answer on this post, this question has been asked earlier: Extract main domain name from a given url. The best answer to that question is from Satya, who suggests Guava's InternetDomainName.topPrivateDomain()

public boolean isTopPrivateDomain()

Indicates whether this domain name is composed of exactly one subdomain component followed by a public suffix. For example, returns true for and, but not for or

Warning: A true result from this method does not imply that the domain is at the highest level which is addressable as a host, as many public suffixes are also addressable hosts. For example, the domain has a public suffix of, so it would return true from this method. But is itself an addressable host.

This method can be used to determine whether a domain is probably the highest level for which cookies may be set, though even that depends on individual browsers' implementations of cookie controls. See RFC 2109 for details.

Putting that together with URL.getHost(), which the original post already contains, gives you:



public class DomainNameMain {

  public static void main(final String... args) throws Exception {
    final String urlString = "";
    final URL url = new URL(urlString);
    final String host = url.getHost();
    final InternetDomainName name = InternetDomainName.from(host).topPrivateDomain();

How do I use Notepad++ (or other) with msysgit?

I am using Windows 10 and notepad++, and I was getting this error message:

line 0: syntax error near unexpected token `(' git windows

So I make the setup in this way:

git config --global core.editor 'C:/Program\ Files\ \(x86\)/Notepad++/notepad++.exe'

and it works

vertical alignment of text element in SVG

According to SVG spec, alignment-baseline only applies to <tspan>, <textPath>, <tref> and <altGlyph>. My understanding is that it is used to offset those from the <text> object above them. I think what you are looking for is dominant-baseline.

Possible values of dominant-baseline are:

auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge | inherit

Check the W3C recommendation for the dominant-baseline property for more information about each possible value.

fatal: bad default revision 'HEAD'

Note: Git 2.6 (Q3/Q4 2015) will finally provide a more meaningful error message.

See commit ce11360 (29 Aug 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 699a0f3, 02 Sep 2015)

log: diagnose empty HEAD more clearly

If you init or clone an empty repository, the initial message from running "git log" is not very friendly:

$ git init
Initialized empty Git repository in /home/peff/foo/.git/
$ git log
fatal: bad default revision 'HEAD'

Let's detect this situation and write a more friendly message:

$ git log
fatal: your current branch 'master' does not have any commits yet

We also detect the case that 'HEAD' points to a broken ref; this should be even less common, but is easy to see.
Note that we do not diagnose all possible cases. We rely on resolve_ref, which means we do not get information about complex cases. E.g., "--default master" would use dwim_ref to find "refs/heads/master", but we notice only that "master" does not exist.
Similarly, a complex sha1 expression like "--default HEAD^2" will not resolve as a ref.

But that's OK. We fall back to a generic error message in those cases, and they are unlikely to be used anyway.
Catching an empty or broken "HEAD" improves the common case, and the other cases are not regressed.

Maven does not find JUnit tests to run

junitArtifactName might also be the case if the JUnit in use isn't the standard (junit:junit) but for instance...


Django - "no module named"

I got the same error and I fixed it in this manner:

I had to activate my virtual environment using the following command

source python2.7/bin/activate

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.


<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />


if($_POST["save"]) {
  //User hit the save button, handle accordingly
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly


If you'd rather not change your PHP setup, try this:
This is the JavaScript method @AliK was reffering to.


Which .NET Dependency Injection frameworks are worth looking into?

Ninject is great. It seems really fast, but I haven't done any comparisons. I know Nate, the author, did some comparisons between Ninject and other DI frameworks and is looking for more ways to improve the speed of Ninject.

I've heard lots of people I respect say good things about StructureMap and CastleWindsor. Those, in my mind, are the big three to look at right now.

How many socket connections possible?

Realistically for an application, more then 4000-5000 open sockets on a single machine becomes impractical. Just checking for activity on all the sockets and managing them starts to become a performance issue - especially in real-time environments.

How to submit a form when the return key is pressed?

I think you should actually have a submit button or a submit image... Do you have a specific reason for using a "submit div"? If you just want custom styles I recommend <input type="image"....

How can I get the MAC and the IP address of a connected client in PHP?

For windows server I think u can use this:

echo exec('getmac');

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

Try wih :

SELECT * FROM sys.dm_exec_requests where command like '%BACKUP%'

SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command like '%BACKUP%'

SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time
  FROM sys.dm_exec_requests

Overwriting txt file in java


My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.

File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");

File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");

String source = textArea.getText();

try {
    FileWriter f2 = new FileWriter(fnew, false);

} catch (IOException e) {

How to Decrease Image Brightness in CSS

-webkit-filter: brightness(0.50);

I've got this cool solution:

How to use goto statement correctly

Java does not support goto, it is reserved as a keyword in case they wanted to add it to a later version

Print line numbers starting at zero using awk

Using awk.

i starts at 0, i++ will increment the value of i, but return the original value that i held before being incremented.

awk '{print i++ "," $0}' file

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

The second question is easier to answer: you basically can use PyPy as a drop-in replacement if all your code is pure Python. However, many widely used libraries (including some of the standard library) are written in C and compiled as Python extensions. Some of these can be made to work with PyPy, some can't. PyPy provides the same "forward-facing" tool as Python --- that is, it is Python --- but its innards are different, so tools that interface with those innards won't work.

As for the first question, I imagine it is sort of a Catch-22 with the first: PyPy has been evolving rapidly in an effort to improve speed and enhance interoperability with other code. This has made it more experimental than official.

I think it's possible that if PyPy gets into a stable state, it may start getting more widely used. I also think it would be great for Python to move away from its C underpinnings. But it won't happen for a while. PyPy hasn't yet reached the critical mass where it is almost useful enough on its own to do everything you'd want, which would motivate people to fill in the gaps.

Select columns based on string match - dplyr::select

No need to use select just use [ instead

data[,grepl("search_string", colnames(data))]

Let's try with iris dataset

>iris[,grepl("Sepal", colnames(iris))]
  Sepal.Length Sepal.Width
1          5.1         3.5
2          4.9         3.0
3          4.7         3.2
4          4.6         3.1
5          5.0         3.6
6          5.4         3.9

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

table align="center" ... this aligns the table center of page.

Using td align="center" centers the content inside that td, useful for centered aligned text but you will have issues with some email clients centering content in sub level tables so using using td align as a top level method of centering your "container" table on the page is not the way to do it. Use table align instead.

Still use your 100% wrapper table too, purely as a wrapper for the body, as some email clients don't display body background colors but it will show it with the 100% table, so add your body color to both body and the 100% table.

I could go on and on for ages about all the quirks of html email dev. All I can say is test test and test again. is a great tool for testing emails.

The more you do the more you will learn about what works in what email clients.

Hope this helps.

Rerender view on browser resize with React

You don't necessarily need to force a re-render.

This might not help OP, but in my case I only needed to update the width and height attributes on my canvas (which you can't do with CSS).

It looks like this:

import React from 'react';
import styled from 'styled-components';
import {throttle} from 'lodash';

class Canvas extends React.Component {

    componentDidMount() {
        window.addEventListener('resize', this.resize);

    componentWillUnmount() {
        window.removeEventListener('resize', this.resize);

    resize = throttle(() => {
        this.canvas.width = this.canvas.parentNode.clientWidth;
        this.canvas.height = this.canvas.parentNode.clientHeight;

    setRef = node => {
        this.canvas = node;

    render() {
        return <canvas className={this.props.className} ref={this.setRef} />;

export default styled(Canvas)`
   cursor: crosshair;

Why use pointers?

The need for pointers in C language is described here

The basic idea is that many limitations in the language (like using arrays, strings and modifying multiple variables in functions) could be removed by manipulating with the memory location of the data. To overcome these limitations, pointers were introduced in C.

Further, it is also seen that using pointers, you can run your code faster and save memory in cases where you are passing big data types (like a structure with many fields) to a function. Making a copy of such data types before passing would take time and would consume memory. This is another reason why programmers prefer pointers for big data types.

PS: Please refer the link provided for detailed explanation with sample code.

Using GSON to parse a JSON array

Problem is caused by comma at the end of (in your case each) JSON object placed in the array:

    "number": "...",
    "title": ".." ,  //<- see that comma?

If you remove them your data will become

        "number": "3",
        "title": "hello_world"
    }, {
        "number": "2",
        "title": "hello_world"


Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

should work fine.

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs


Combining Two Images with OpenCV

The three best way to do it using a single line of code

import cv2
import numpy as np 

img = cv2.imread('Imgs/Saint_Roch_new/data/Point_4_Face.jpg')
dim = (256, 256)
resizedLena = cv2.resize(img, dim, interpolation = cv2.INTER_LINEAR)
X, Y = resizedLena, resizedLena

# Methode 1: Using Numpy (hstack, vstack)
Fusion_Horizontal = np.hstack((resizedLena, Y, X))
Fusion_Vertical   = np.vstack((newIMG, X))

cv2.imshow('Fusion_Vertical using vstack', Fusion_Vertical)

# Methode 2: Using Numpy (contanate)
Fusion_Vertical   = np.concatenate((resizedLena, X, Y), axis=0)
Fusion_Horizontal = np.concatenate((resizedLena, X, Y), axis=1)

cv2.imshow("Fusion_Horizontal usung concatenate", Fusion_Horizontal)

# Methode 3: Using OpenCV (vconcat, hconcat)
Fusion_Vertical   = cv2.vconcat([resizedLena, X, Y])
Fusion_Horizontal = cv2.hconcat([resizedLena, X, Y])

cv2.imshow("Fusion_Horizontal Using hconcat", Fusion_Horizontal)

How to create bitmap from byte array?

Can be as easy as:

var ms = new MemoryStream(imageData);
System.Drawing.Image image = Image.FromStream(ms);


Testing it out:

byte[] imageData;

// Create the byte array.
var originalImage = Image.FromFile(@"C:\original.jpg");
using (var ms = new MemoryStream())
    originalImage.Save(ms, ImageFormat.Jpeg);
    imageData = ms.ToArray();

// Convert back to image.
using (var ms = new MemoryStream(imageData))
    Image image = Image.FromStream(ms);

jQuery load more data on scroll

The accepted answer of this question has some issue with chrome when the window is zoomed in to a value >100%. Here is the code recommended by chrome developers as part of a bug i had raised on the same.

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()){
     //Your code here

For reference:

Related SO question

Chrome Bug

What do the crossed style properties in Google Chrome devtools mean?

If you want to apply the style even after getting struck-trough indication, you can use "!important" to enforce the style. It may not be a right solution but solve the problem.

Insert line after first match using sed

Sed command that works on MacOS (at least, OS 10) and Unix alike (ie. doesn't require gnu sed like Gilles' (currently accepted) one does):

sed -e '/CLIENTSCRIPT="foo"/a\'$'\n''CLIENTSCRIPT2="hello"' file

This works in bash and maybe other shells too that know the $'\n' evaluation quote style. Everything can be on one line and work in older/POSIX sed commands. If there might be multiple lines matching the CLIENTSCRIPT="foo" (or your equivalent) and you wish to only add the extra line the first time, you can rework it as follows:

sed -e '/^ *CLIENTSCRIPT="foo"/b ins' -e b -e ':ins' -e 'a\'$'\n''CLIENTSCRIPT2="hello"' -e ': done' -e 'n;b done' file

(this creates a loop after the line insertion code that just cycles through the rest of the file, never getting back to the first sed command again).

You might notice I added a '^ *' to the matching pattern in case that line shows up in a comment, say, or is indented. Its not 100% perfect but covers some other situations likely to be common. Adjust as required...

These two solutions also get round the problem (for the generic solution to adding a line) that if your new inserted line contains unescaped backslashes or ampersands they will be interpreted by sed and likely not come out the same, just like the \n is - eg. \0 would be the first line matched. Especially handy if you're adding a line that comes from a variable where you'd otherwise have to escape everything first using ${var//} before, or another sed statement etc.

This solution is a little less messy in scripts (that quoting and \n is not easy to read though), when you don't want to put the replacement text for the a command at the start of a line if say, in a function with indented lines. I've taken advantage that $'\n' is evaluated to a newline by the shell, its not in regular '\n' single-quoted values.

Its getting long enough though that I think perl/even awk might win due to being more readable.

Determine file creation date in Java

Java nio has options to access creationTime and other meta-data as long as the filesystem provides it. Check this link out

For example(Provided based on @ydaetskcoR's comment):

Path file = ...;
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);

System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

PowerShell: Store Entire Text File Contents in Variable

On a side note, in PowerShell 3.0 you can use the Get-Content cmdlet with the new Raw switch:

$text = Get-Content .\file.txt -Raw 

How to make PDF file downloadable in HTML link?

Don't loop through every file line. Use readfile instead, its faster. This is off the php site:

$file = $_GET["file"];
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Type: application/force-download");
    header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
    // header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

Make sure to sanitize your get variable as someone could download some php files...

Change background color of R plot

After combining the information in this thread with the R-help ?rect, I came up with this nice graph for circadian rhythm data (24h plot). The script for the background rectangles is this:

root script:

>rect(xleft, ybottom, xright, ytop, col = NA, border = NULL)

My script:

>i <- 24*(0:8)
>rect(8+i, 1, 24+i, 130, col = "lightgrey", border=NA)
>rect(8+i, -10, 24+i, 0.1, col = "black", border=NA)

The idea is to represent days of 24 hours with 8 h light and 16 h dark.



Trigger a keypress/keydown/keyup event in JS/jQuery?

You can achieve this with: EventTarget.dispatchEvent(event) and by passing in a new KeyboardEvent as the event.

For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))

Working example:

// get the element in question_x000D_
const input = document.getElementsByTagName("input")[0];_x000D_
// focus on the input element_x000D_
// add event listeners to the input element_x000D_
input.addEventListener('keypress', (event) => {_x000D_
  console.log("You have pressed key: ", event.key);_x000D_
input.addEventListener('keydown', (event) => {_x000D_
  console.log(`key: ${event.key} has been pressed down`);_x000D_
input.addEventListener('keyup', (event) => {_x000D_
  console.log(`key: ${event.key} has been released`);_x000D_
// dispatch keyboard events_x000D_
input.dispatchEvent(new KeyboardEvent('keypress',  {'key':'h'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keydown',  {'key':'e'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
<input type="text" placeholder="foo" />

MDN dispatchEvent

MDN KeyboardEvent

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

Abstraction VS Information Hiding VS Encapsulation

Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition):

Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object... encapsulation focuses upon the implementation that gives rise to this behavior... encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics.

In other words: abstraction = the object externally; encapsulation (achieved through information hiding) = the object internally,

Example: In the .NET Framework, the System.Text.StringBuilder class provides an abstraction over a string buffer. This buffer abstraction lets you work with the buffer without regard for its implementation. Thus, you're able to append strings to the buffer without regard for how the StringBuilder internally keeps track of things such the pointer to the buffer and managing memory when the buffer gets full (which it does with encapsulation via information hiding).


Android: Storing username and password?

With the new (Android 6.0) fingerprint hardware and API you can do it as in this github sample application.

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Take a look at this WPF metro-styled window with optional glowing borders.

This is a stand-alone application using no other libraries than Microsoft.Windows.Shell (included) to create metro-styled windows with optional glowing borders.

Supports Windows all the way back to XP (.NET4).

python: after installing anaconda, how to import pandas

  1. Another alternative is to use Pycharm IDE. For each project, you can set the Project Interpreter in Settings.

  2. For example, if anaconda is installed in /home/user/anaconda2/bin/python, you can select the Project Interpreter and set to this folder.

  3. Since the whole project is set to Anaconda's path, you can import any module which is packaged within Anaconda.

nginx - client_max_body_size has no effect

If you tried the above options and no success, also you're using IIS (iisnode) to host your node app, putting this code on web.config resolved the problem for me:

Here is the reference:

Also, you can chagne the length allowed because now I think its 2GB. Modify it by your needs.

      <requestLimits maxAllowedContentLength="2147483648" />

How to send value attribute from radio button in PHP

When you select a radio button and click on a submit button, you need to handle the submission of any selected values in your php code using $_POST[]
For example:
if your radio button is:

<input type="radio" name="rdb" value="male"/>

then in your php code you need to use:

$rdb_value = $_POST['rdb'];

Bootstrap 3 dropdown select

The dropdown list appearing like that depends on what your browser is, as it is not possible to style this away for some. It looks like yours is IE9, but would look quite different in Chrome.

You could look to use something like this:

Which will make your selectboxes more consistent cross browser.

Is there an equivalent of lsusb for OS X

system_profiler SPUSBDataType

it your need command on macos

How do I remove the height style from a DIV using jQuery?


Insert array into MySQL database with PHP

Personally I'd json_encode the array (taking into account any escaping etc needed) and bung the entire lot into an appropriately sized text/blob field.

It makes it very easy to store "unstructured" data but a real PITA to search/index on with any grace.

A simple json_decode will "explode" the data back into an array for you.

javascript get x and y coordinates on mouse click

Like this.

function printMousePos(event) {_x000D_
  document.body.textContent =_x000D_
    "clientX: " + event.clientX +_x000D_
    " - clientY: " + event.clientY;_x000D_
document.addEventListener("click", printMousePos);

MouseEvent - MDN

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

Detect whether a Python string is a number or a letter

Check if string is positive digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
>>> 'A'.isalpha()

# For digit
>>> '1'.isdigit()
>>> '1'.isalpha()

Check for strings as positive/negative - integer/float

str.isdigit() returns False if the string is a negative number or a float number. For example:

# returns `False` for float
>>> '123.3'.isdigit()
# returns `False` for negative number
>>> '-123'.isdigit()

If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

def is_number(n):
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

Sample Run:

>>> is_number('123')    # positive integer number

>>> is_number('123.4')  # positive float number
>>> is_number('-123')   # negative integer number

>>> is_number('-123.4') # negative `float` number

>>> is_number('abc')    # `False` for "some random" string

Discard "NaN" (not a number) strings while checking for number

The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

>>> is_number('NaN')

In order to check whether the number is "NaN", you may use math.isnan() as:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)

Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num

Hence, above function is_number can be updated to return False for "NaN" as:

def is_number(n):
    is_number = True
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('Nan')   # not a number "Nan" string

>>> is_number('nan')   # not a number string "nan" with all lower cased

>>> is_number('123')   # positive integer

>>> is_number('-123')  # negative integer

>>> is_number('-1.12') # negative `float`

>>> is_number('abc')   # "some random" string

Allow Complex Number like "1+2j" to be treated as valid number

The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:

def is_number(n):
    is_number = True
        #      v type-casting the number here as `complex`, instead of `float`
        num = complex(n)
        is_number = num == num
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('1+2j')    # Valid 
True                     #      : complex number 

>>> is_number('1+ 2j')   # Invalid 
False                    #      : string with space in complex number represetantion
                         #        is treated as invalid complex number

>>> is_number('123')     # Valid
True                     #      : positive integer

>>> is_number('-123')    # Valid 
True                     #      : negative integer

>>> is_number('abc')     # Invalid 
False                    #      : some random string, not a valid number

>>> is_number('nan')     # Invalid
False                    #      : not a number "nan" string

PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

Bin size in Matplotlib (Histogram)

I use quantiles to do bins uniform and fitted to sample:


plt.hist(df['Generosity'], bins=bins, normed=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')

enter image description here

Pass C# ASP.NET array to Javascript array

Here is another alternative solution. You can use ClientScriptManager Page.ClientScript.RegisterArrayDeclaration. Here is an example for chart data.

var page = HttpContext.Current.CurrentHandler as Page;

_data = "[Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
         ,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
         ,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
         ,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]";
page.ClientScript.RegisterArrayDeclaration("chartdata0", _data);

This code creates an array on the client side

var chartdata0 = new Array([Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
             ,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
             ,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
             ,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]);

See the following article

This solution has an issue with bigger arrays on chrome 64 browser including "Version 78.0.3904.70 (Official Build) (64-bit)". You may get "Uncaught RangeError: Maximum call stack size exceeded". However it is working with IE11, Microsoft Edge, and FireFox.

How to save an HTML5 Canvas as an image on a server?

I played with this two weeks ago, it's very simple. The only problem is that all the tutorials just talk about saving the image locally. This is how I did it:

1) I set up a form so I can use a POST method.

2) When the user is done drawing, he can click the "Save" button.

3) When the button is clicked I take the image data and put it into a hidden field. After that I submit the form.

document.getElementById('my_hidden').value = canvas.toDataURL('image/png');

4) When the form is submited I have this small php script:

$upload_dir = somehow_get_upload_dir();  //implement this function yourself
$img = $_POST['my_hidden'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
header('Location: '.$_POST['return_url']);

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.

So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.

Example with Digest Authentication:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace NUI
    public class DigestAuthFixer
        private static string _host;
        private static string _user;
        private static string _password;
        private static string _realm;
        private static string _nonce;
        private static string _qop;
        private static string _cnonce;
        private static DateTime _cnonceDate;
        private static int _nc;

public DigestAuthFixer(string host, string user, string password)
    // TODO: Complete member initialization
    _host = host;
    _user = user;
    _password = password;

private string CalculateMd5Hash(
    string input)
    var inputBytes = Encoding.ASCII.GetBytes(input);
    var hash = MD5.Create().ComputeHash(inputBytes);
    var sb = new StringBuilder();
    foreach (var b in hash)
    return sb.ToString();

private string GrabHeaderVar(
    string varName,
    string header)
    var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
    var matchHeader = regHeader.Match(header);
    if (matchHeader.Success)
        return matchHeader.Groups[1].Value;
    throw new ApplicationException(string.Format("Header {0} not found", varName));

private string GetDigestHeader(
    string dir)
    _nc = _nc + 1;

    var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
    var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
    var digestResponse =
        CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));

    return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
        "algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
        _user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);

public string GrabResponse(
    string dir)
    var url = _host + dir;
    var uri = new Uri(url);

    var request = (HttpWebRequest)WebRequest.Create(uri);

    // If we've got a recent Auth header, re-use it!
    if (!string.IsNullOrEmpty(_cnonce) &&
        DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
        request.Headers.Add("Authorization", GetDigestHeader(dir));

    HttpWebResponse response;
        response = (HttpWebResponse)request.GetResponse();
    catch (WebException ex)
        // Try to fix a 401 exception by adding a Authorization header
        if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)

        var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
        _realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
        _nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
        _qop = GrabHeaderVar("qop", wwwAuthenticateHeader);

        _nc = 0;
        _cnonce = new Random().Next(123400, 9999999).ToString();
        _cnonceDate = DateTime.Now;

        var request2 = (HttpWebRequest)WebRequest.Create(uri);
        request2.Headers.Add("Authorization", GetDigestHeader(dir));
        response = (HttpWebResponse)request2.GetResponse();
    var reader = new StreamReader(response.GetResponseStream());
    return reader.ReadToEnd();


Then you could call it:

DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);

if Url is: then domain: (domain part) dir: /folder/rss (rest of the url)

you could also return it as stream and use XmlDocument Load() method.

How to generate gcc debug symbol outside the build target?

Compile with debug information:

gcc -g -o main main.c

Separate the debug information:

objcopy --only-keep-debug main main.debug


cp main main.debug
strip --only-keep-debug main.debug

Strip debug information from origin file:

objcopy --strip-debug main


strip --strip-debug --strip-unneeded main

debug by debuglink mode:

objcopy --add-gnu-debuglink main.debug main
gdb main

You can also use exec file and symbol file separatly:

gdb -s main.debug -e main


(gdb) exec-file main
(gdb) symbol-file main.debug

For details:

(gdb) help exec-file
(gdb) help symbol-file


Global variables in Java

In general, Java doesn't have any global variables. Other than local variables, all variables comes under the scope of any class defined in the program. We can have static variables to have the scope of global variables.

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

Run following commands to remove node completely from system in MACOS

sudo rm -rf ~/.npm ~/.nvm ~/node_modules ~/.node-gyp ~/.npmrc ~/.node_repl_history
sudo rm -rf /usr/local/bin/npm /usr/local/bin/node-debug /usr/local/bin/node /usr/local/bin/node-gyp
sudo rm -rf /usr/local/share/man/man1/node* /usr/local/share/man/man1/npm*
sudo rm -rf /usr/local/include/node /usr/local/include/node_modules
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /usr/local/lib/dtrace/node.d
sudo rm -rf /opt/local/include/node /opt/local/bin/node /opt/local/lib/node
sudo rm -rf /usr/local/share/doc/node
sudo rm -rf /usr/local/share/systemtap/tapset/node.stp

brew uninstall node
brew doctor
brew cleanup --prune-prefix

After this i will suggest to use following command to install node using nvm

curl -o- | bash


Reading a string with scanf

I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.

char str[]  
  1. array of values of type char, with its own address in memory
  2. array of values of type char, with its own address in memory as many consecutive addresses as elements in the array
  3. including termination null character '\0' &str, &str[0] and str, all three represent the same location in memory which is address of the first element of the array str

    char *strPtr = &str[0]; //declaration and initialization

alternatively, you can split this in two:

char *strPtr; strPtr = &str[0];
  1. strPtr is a pointer to a char
  2. strPtr points at array str
  3. strPtr is a variable with its own address in memory
  4. strPtr is a variable that stores value of address &str[0]
  5. strPtr own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])
  6. &strPtr represents the address of strPtr itself

I think that you could declare a pointer to a pointer as:

char **vPtr = &strPtr;  

declares and initializes with address of strPtr pointer

Alternatively you could split in two:

char **vPtr;
*vPtr = &strPtr
  1. *vPtr points at strPtr pointer
  2. *vPtr is a variable with its own address in memory
  3. *vPtr is a variable that stores value of address &strPtr
  4. final comment: you can not do str++, str address is a const, but you can do strPtr++

Escape a string in SQL Server so that it is safe to use in LIKE expression

Do you want to look for strings that include an escape character? For instance you want this:

select * from table where myfield like '%10%%'.

Where you want to search for all fields with 10%? If that is the case then you may use the ESCAPE clause to specify an escape character and escape the wildcard character.

select * from table where myfield like '%10!%%' ESCAPE '!' Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Verify what are you attempting to write. I was having the same issue, but I realized i was trying to write a byte array with length of 0.

It doesn't make sense to me, but I get: "Access to the path "

How to add url parameters to Django template url tag?


            {% for ticket in tickets %}
                <td class="ticket_id">{{}}</td>
                <td class="ticket_eam">{{ticket.eam}}</td>
                <td class="ticket_subject">{{ticket.subject}}</td>
                <td><a href="{% url 'ticket_details' %}"><button data-toggle="modal" data-target="#modaldemo3" class="value-modal"><i class="icon ion-edit"></a></i></button> <button><i class="fa fa-eye-slash"></i></button>
            {% endfor %}

The {% url 'ticket_details' %} is the function name in your views


def ticket_details(request, ticket_id):

   return render(request, ticket.html)

ticket_id is the parameter you will get from the


urlpatterns = [
path('ticket_details/?P<int:ticket_id>/', views.ticket_details, name="ticket_details") ]

/?P - where ticket_id is the name of the group and pattern is some pattern to match.

How do I kill background processes / jobs when my shell script exits?

To clean up some mess, trap can be used. It can provide a list of stuff executed when a specific signal arrives:

trap "echo hello" SIGINT

but can also be used to execute something if the shell exits:

trap "killall background" EXIT

It's a builtin, so help trap will give you information (works with bash). If you only want to kill background jobs, you can do

trap 'kill $(jobs -p)' EXIT

Watch out to use single ', to prevent the shell from substituting the $() immediately.

System.Data.SqlClient.SqlException: Login failed for user

I faced the same situation. Create your connection string as follows.


"connectionString": "Data Source=server name;Initial Catalog=DB name;User id=user id;Password=password;Integrated Security=True;MultipleActiveResultSets=True"


"connectionString": "Server=server name; Database=Treat; User Id=user id; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true"

Command line to remove an environment variable from the OS level configuration

To remove the variable from the current environment (not permanently):


To permanently remove the variable from the user environment (which is the default place setx puts it):

REG delete HKCU\Environment /F /V FOOBAR

If the variable is set in the system environment (e.g. if you originally set it with setx /M), as an administrator run:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR

Note: The REG commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.

How do I check (at runtime) if one class is a subclass of another?

You can use isinstance if you have an instance, or issubclass if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.

How to convert a huge list-of-vector to a matrix more efficiently?

you can use as.matrix as below:

output <- as.matrix(z)

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

You state in the comments that the returned JSON is this:

  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 

You're telling Gson that you have an array of Post objects:

List<Post> postsList = Arrays.asList(gson.fromJson(reader,

You don't. The JSON represents exactly one Post object, and Gson is telling you that.

Change your code to be:

Post post = gson.fromJson(reader, Post.class);

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

When is JavaScript synchronous?


The term "asynchronous" can be used in slightly different meanings, resulting in seemingly conflicting answers here, while they are actually not. Wikipedia on Asynchrony has this definition:

Asynchrony, in computer programming, refers to the occurrence of events independent of the main program flow and ways to deal with such events. These may be "outside" events such as the arrival of signals, or actions instigated by a program that take place concurrently with program execution, without the program blocking to wait for results.

non-JavaScript code can queue such "outside" events to some of JavaScript's event queues. But that is as far as it goes.

No Preemption

There is no external interruption of running JavaScript code in order to execute some other JavaScript code in your script. Pieces of JavaScript are executed one after the other, and the order is determined by the order of events in each event queue, and the priority of those queues.

For instance, you can be absolutely sure that no other JavaScript (in the same script) will ever execute while the following piece of code is executing:

let a = [1, 4, 15, 7, 2];
let sum = 0;
for (let i = 0; i < a.length; i++) {
    sum += a[i];

In other words, there is no preemption in JavaScript. Whatever may be in the event queues, the processing of those events will have to wait until such piece of code has ran to completion. The EcmaScript specification says in section 8.4 Jobs and Jobs Queues:

Execution of a Job can be initiated only when there is no running execution context and the execution context stack is empty.

Examples of Asynchrony

As others have already written, there are several situations where asynchrony comes into play in JavaScript, and it always involves an event queue, which can only result in JavaScript execution when there is no other JavaScript code executing:

  • setTimeout(): the agent (e.g. browser) will put an event in an event queue when the timeout has expired. The monitoring of the time and the placing of the event in the queue happens by non-JavaScript code, and so you could imagine this happens in parallel with the potential execution of some JavaScript code. But the callback provided to setTimeout can only execute when the currently executing JavaScript code has ran to completion and the appropriate event queue is being read.

  • fetch(): the agent will use OS functions to perform an HTTP request and monitor for any incoming response. Again, this non-JavaScript task may run in parallel with some JavaScript code that is still executing. But the promise resolution procedure, that will resolve the promise returned by fetch(), can only execute when the currently executing JavaScript has ran to completion.

  • requestAnimationFrame(): the browser's rendering engine (non-JavaScript) will place an event in the JavaScript queue when it is ready to perform a paint operation. When JavaScript event is processed the callback function is executed.

  • queueMicrotask(): immediately places an event in the microtask queue. The callback will be executed when the call stack is empty and that event is consumed.

There are many more examples, but all these functions are provided by the host environment, not by core EcmaScript. With core EcmaScript you can synchronously place an event in a Promise Job Queue with Promise.resolve().

Language Constructs

EcmaScript provides several language constructs to support the asynchrony pattern, such as yield, async, await. But let there be no mistake: no JavaScript code will be interrupted by an external event. The "interruption" that yield and await seem to provide is just a controlled, predefined way of returning from a function call and restoring its execution context later on, either by JS code (in the case of yield), or the event queue (in the case of await).

DOM event handling

When JavaScript code accesses the DOM API, this may in some cases make the DOM API trigger one or more synchronous notifications. And if your code has an event handler listening to that, it will be called.

This may come across as pre-emptive concurrency, but it is not: once your event handler(s) return(s), the DOM API will eventually also return, and the original JavaScript code will continue.

In other cases the DOM API will just dispatch an event in the appropriate event queue, and JavaScript will pick it up once the call stack has been emptied.

See synchronous and asynchronous events

Replace new line/return with space using regex

\s is a shortcut for whitespace characters in regex. It has no meaning in a string. ==> You can't use it in your replacement string. There you need to put exactly the character(s) that you want to insert. If this is a space just use " " as replacement.

The other thing is: Why do you use 3 backslashes as escape sequence? Two are enough in Java. And you don't need a | (alternation operator) in a character class.

L.replaceAll("[\\t\\n\\r]+"," ");


L is not changed. If you want to have a result you need to do

String result =     L.replaceAll("[\\t\\n\\r]+"," ");

Test code:

String in = "This is my text.\n\nAnd here is a new line";

String out = in.replaceAll("[\\t\\n\\r]+"," ");

How to add a new row to datagridview programmatically

If you need to manipulate anything aside from the Cell Value string such as adding a Tag, try this:

DataGridViewRow newRow = (DataGridViewRow)mappingDataGridView.RowTemplate.Clone();

newRow.Cells[0].Value = mapping.Key;
newRow.Cells[1].Value = ((BusinessObject)mapping.Value).Name;
newRow.Cells[1].Tag = mapping.Value;


How to check if a div is visible state or not?

if element is hide by jquery then use


How to change a dataframe column from String type to Double type in PySpark?

Preserve the name of the column and avoid extra column addition by using the same name as input column:

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

Convert.ToDateTime: how to set format

If value is a string in that format and you'd like to convert it into a DateTime object, you can use DateTime.ParseExact static method:

DateTime.ParseExact(value, format, CultureInfo.CurrentCulture);


string value = "12/12";
var myDate = DateTime.ParseExact(value, "MM/yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);




How to disable HTML button using JavaScript?

<button disabled=true>text here</button>

You can still use an attribute. Just use the 'disabled' attribute instead of 'value'.

Is it possible to have a multi-line comments in R?

CTRL+SHIFT+C in Eclipse + StatET and Rstudio.