Programs & Examples On #Stacked area chart

A stacked area chart is a type of chart (or graph) that is used to display graphically quantitive data.

How to split csv whose columns may contain ,

Use the Microsoft.VisualBasic.FileIO.TextFieldParser class. This will handle parsing a delimited file, TextReader or Stream where some fields are enclosed in quotes and some are not.

For example:

using Microsoft.VisualBasic.FileIO;

string csv = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

TextFieldParser parser = new TextFieldParser(new StringReader(csv));

// You can also read from a file
// TextFieldParser parser = new TextFieldParser("mycsvfile.csv");

parser.HasFieldsEnclosedInQuotes = true;

string[] fields;

while (!parser.EndOfData)
    fields = parser.ReadFields();
    foreach (string field in fields)


This should result in the following output:

7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
Corvallis, OR

See Microsoft.VisualBasic.FileIO.TextFieldParser for more information.

You need to add a reference to Microsoft.VisualBasic in the Add References .NET tab.

How to make ConstraintLayout work with percentage values?

As of "ConstraintLayout1.1.0-beta1" you can use percent to define widths & heights.


This will define the width to be 40% of the width of the screen. A combination of this and guidelines in percent allows you to create any percent-based layout you want.

Android, Java: HTTP POST Request

You can reuse the implementation I added to ACRA:

(See the doPost(Map, Url) method, working over http and https even with self signed certs)

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

... or if you really want to use NOT IN you can use


How do I force "git pull" to overwrite local files?

Try this:

git reset --hard HEAD
git pull

It should do what you want.

How to filter an array from all elements of another array

The best description to filter function is

You should simply condition function:

function conditionFun(element, index, array) {
   return element >= 10;
filtered = [12, 5, 8, 130, 44].filter(conditionFun);

And you can't access the variable value before it is assigned

Eloquent: find() and where() usage laravel

To add to craig_h's comment above (I currently don't have enough rep to add this as a comment to his answer, sorry), if your primary key is not an integer, you'll also want to tell your model what data type it is, by setting keyType at the top of the model definition.

public $keyType = 'string'

Eloquent understands any of the types defined in the castAttribute() function, which as of Laravel 5.4 are: int, float, string, bool, object, array, collection, date and timestamp.

This will ensure that your primary key is correctly cast into the equivalent PHP data type.

Null pointer Exception on .setOnClickListener

I too got similar error when i misplaced the code

text=(TextView)findViewById(;// this line has to be below setcontentview
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

I got it working on placing the code in right order as shown below

 text.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

I've incurred in a weird behaviour using [].

We have Model "classes" with fields initialised to some value. E.g.:

], function(declare, parser, ready, _WidgetBase){

   declare("MyWidget", [_WidgetBase], {
     field1: [],
     field2: "",
     function1: function(),
     function2: function()

I found that when the fields are initialised with [] then it would be shared by all Model objects. Making changes to one affects all others.

This doesn't happen initialising them with new Array(). Same for the initialisation of Objects ({} vs new Object())

TBH I am not sure if its a problem with the framework we were using (Dojo)

What are and

DEVELOPER runs autoconf and automake:

  1. autoconf -- creates shippable configure script
    (which the installer will later run to make the Makefile)
  1. automake - creates shippable data file
    (which configure will later read to make the Makefile)

INSTALLER runs configure, make and sudo make install:

./configure       # Creates  Makefile        (from  
make              # Creates  the application (from the Makefile just created).  

sudo make install # Installs the application 
                  #   Often, by default its files are installed into /usr/local


Notation below is roughly: inputs --> programs --> outputs

DEVELOPER runs these: -> autoconf -> configure (script) --- (*.ac = autoconf) --> autoconf -> configure (script) --- ( depreciated. Use -> automake -> ----------- (*.am = automake)

INSTALLER runs these: -> configure -> Makefile (*.in = input file)

Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)

"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."

"automake is a tool for automatically generating files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."


Free online tutorials:


The main used to build LibreOffice is over 12k lines of code, (but there are also 57 other files in subfolders.)

From this my generated configure is over 41k lines of code.

And while the and Makefile are both only 493 lines of code. (But, there are also 768 more's in subfolders.)

Current date without time

Try this:

   var mydtn = DateTime.Today;
   var myDt = mydtn.Date;return myDt.ToString("d", CultureInfo.GetCultureInfo("en-US"));

sending mail from Batch file


blat -to [email protected] -server -f [email protected] -subject "subject" -body "body"

What does Docker add to lxc-tools (the userspace LXC tools)?

The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.

LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.

LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.

Key features of LXD are:

  • Secure by design (unprivileged containers, resource restrictions and much more)
  • Scalable (from containers on your laptop to thousand of compute nodes)
  • Intuitive (simple, clear API and crisp command line experience)
  • Image based (no more distribution templates, only good, trusted images) Live migration

There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.

However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.

The OpenStack nclxd plugin a list of features supported include:

stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support

By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.

What is the C# equivalent of NaN or IsNumeric?

VB has the IsNumeric function. You could reference Microsoft.VisualBasic.dll and use it.

Get time in milliseconds using C#

long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

This is actually how the various Unix conversion methods are implemented in the DateTimeOffset class (.NET Framework 4.6+, .NET Standard 1.3+):

long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();

Why are primes important in cryptography?

There are some good resources for ramping up on crypto. Here's one:

From that page:

In the most commonly used public-key cryptography system, invented by Ron Rivest, Adi Shamir, and Len Adleman in 1977, both the public and the private keys are derived from a pair of large prime numbers according to a relatively simple mathematical formula. In theory, it might be possible to derive the private key from the public key by working the formula backwards. But only the product of the large prime numbers is public, and factoring numbers of that size into primes is so hard that even the most powerful supercomputers in the world cant break an ordinary public key.

Bruce Schneier's book Applied Cryptography is another. I highly recommend that book; it's fun reading.

Use latest version of Internet Explorer in the webbrowser control

I saw Veer's answer. I think it's right, but it did not I work for me. Maybe I am using .NET 4 and am using 64x OS so kindly check this.

You may put in setup or check it in start-up of your application:

private void Form1_Load(object sender, EventArgs e)
    var appName = Process.GetCurrentProcess().ProcessName + ".exe";

private void SetIE8KeyforWebBrowserControl(string appName)
    RegistryKey Regkey = null;
        // For 64 bit machine
        if (Environment.Is64BitOperatingSystem)
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
        else  //For 32 bit machine
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);

        // If the path is not correct or
        // if the user haven't priviledges to access the registry
        if (Regkey == null)
            MessageBox.Show("Application Settings Failed - Address Not found");

        string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

        // Check if key is already present
        if (FindAppkey == "8000")
            MessageBox.Show("Required Application Settings Present");

        // If a key is not present add the key, Key value 8000 (decimal)
        if (string.IsNullOrEmpty(FindAppkey))
            Regkey.SetValue(appName, unchecked((int)0x1F40), RegistryValueKind.DWord);

        // Check for the key after adding
        FindAppkey = Convert.ToString(Regkey.GetValue(appName));

        if (FindAppkey == "8000")
            MessageBox.Show("Application Settings Applied Successfully");
            MessageBox.Show("Application Settings Failed, Ref: " + FindAppkey);
    catch (Exception ex)
        MessageBox.Show("Application Settings Failed");
        // Close the Registry
        if (Regkey != null)

You may find, just for testing.

Keys are as the following:

  • 11001 (0x2AF9) - Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.

  • 11000 (0x2AF8) - Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.

  • 10001 (0x2711)- Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.

  • 10000 (0x2710)- Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.

  • 9999 (0x270F) - Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.

  • 9000 (0x2328) - Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

  • 8888 (0x22B8) - Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.

  • 8000 (0x1F40) - Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.

  • 7000 (0x1B58) - Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.

Reference: MSDN: Internet Feature Controls

I saw applications like Skype use 10001. I do not know.


The setup application will change the registry. You may need to add a line in the Manifest File to avoid errors due to permissions of change in registry:

<requestedExecutionLevel level="highestAvailable" uiAccess="false" />


This is a class will get the latest version of IE on windows and make changes as should be;

public class WebBrowserHelper

    public static int GetEmbVersion()
        int ieVer = GetBrowserVersion();

        if (ieVer > 9)
            return ieVer * 1000 + 1;

        if (ieVer > 7)
            return ieVer * 1111;

        return 7000;
    } // End Function GetEmbVersion

    public static void FixBrowserVersion()
        string appName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);

    public static void FixBrowserVersion(string appName)
        FixBrowserVersion(appName, GetEmbVersion());
    } // End Sub FixBrowserVersion

    // FixBrowserVersion("<YourAppName>", 9000);
    public static void FixBrowserVersion(string appName, int ieVer)
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".vshost.exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".vshost.exe", ieVer);
    } // End Sub FixBrowserVersion 

    private static void FixBrowserVersion_Internal(string root, string appName, int ieVer)
            //For 64 bit Machine 
            if (Environment.Is64BitOperatingSystem)
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);
            else  //For 32 bit Machine 
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);

        catch (Exception)
            // some config will hit access rights exceptions
            // this is why we try with both LOCAL_MACHINE and CURRENT_USER
    } // End Sub FixBrowserVersion_Internal 

    public static int GetBrowserVersion()
        // string strKeyPath = @"HKLM\SOFTWARE\Microsoft\Internet Explorer";
        string strKeyPath = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer";
        string[] ls = new string[] { "svcVersion", "svcUpdateVersion", "Version", "W2kVersion" };

        int maxVer = 0;
        for (int i = 0; i < ls.Length; ++i)
            object objVal = Microsoft.Win32.Registry.GetValue(strKeyPath, ls[i], "0");
            string strVal = System.Convert.ToString(objVal);
            if (strVal != null)
                int iPos = strVal.IndexOf('.');
                if (iPos > 0)
                    strVal = strVal.Substring(0, iPos);

                int res = 0;
                if (int.TryParse(strVal, out res))
                    maxVer = Math.Max(maxVer, res);
            } // End if (strVal != null)

        } // Next i

        return maxVer;
    } // End Function GetBrowserVersion 


using of class as followed


you may face a problem for in comparability of windows 10, may due to your website itself you may need to add this meta tag

<meta http-equiv="X-UA-Compatible" content="IE=11" >

Enjoy :)

How to retrieve a single file from a specific revision in Git?

In addition to all the options listed by other answers, you can use git reset with the Git object (hash, branch, HEAD~x, tag, ...) of interest and the path of your file:

git reset <hash> /path/to/file

In your example:

git reset 27cf8e8 my_file.txt

What this does is that it will revert my_file.txt to its version at the commit 27cf8e8 in the index while leaving it untouched (so in its current version) in the working directory.

From there, things are very easy:

  • you can compare the two versions of your file with git diff --cached my_file.txt
  • you can get rid of the old version of the file with git restore --staged file.txt (or, prior to Git v2.23, git reset file.txt) if you decide that you don't like it
  • you can restore the old version with git commit -m "Restore version of file.txt from 27cf8e8" and git restore file.txt (or, prior to Git v2.23, git checkout -- file.txt)
  • you can add updates from the old to the new version only for some hunks by running git add -p file.txt (then git commit and git restore file.txt).

Lastly, you can even interactively pick and choose which hunk(s) to reset in the very first step if you run:

git reset -p 27cf8e8 my_file.txt

So git reset with a path gives you lots of flexibility to retrieve a specific version of a file to compare with its currently checked-out version and, if you choose to do so, to revert fully or only for some hunks to that version.

Edit: I just realized that I am not answering your question since what you wanted wasn't a diff or an easy way to retrieve part or all of the old version but simply to cat that version.

Of course, you can still do that after resetting the file with:

git show :file.txt

to output to standard output or

git show :file.txt > file_at_27cf8e8.txt

But if this was all you wanted, running git show directly with git show 27cf8e8:file.txt as others suggested is of course much more direct.

I am going to leave this answer though because running git show directly allows you to get that old version instantly, but if you want to do something with it, it isn't nearly as convenient to do so from there as it is if you reset that version in the index.

Set variable value to array of strings

You're trying to assign three separate string literals to a single string variable. A valid string variable would be 'John, Sarah, George'. If you want embedded single quotes between the double quotes, you have to escape them.

Also, your actual SELECT won't work, because SQL databases won't parse the string variable out into individual literal values. You need to use dynamic SQL instead, and then execute that dynamic SQL statement. (Search this site for dynamic SQL, with the database engine you're using as the topic (as in [sqlserver] dynamic SQL), and you should get several examples.)

How do you beta test an iphone app?

In year 2011, there's a new service out called "Test Flight", and it addresses this issue directly.

Apple has since bought TestFlight in 2014 and has integrated it into iTunes Connect and App Store Connect.

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

execute immediate 
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

execute immediate 
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'

and then run as sqlplus -s username/password @vijay.sql '20100101'

What is the meaning of the word logits in TensorFlow?

Logit is a function that maps probabilities [0, 1] to [-inf, +inf].

Softmax is a function that maps [-inf, +inf] to [0, 1] similar as Sigmoid. But Softmax also normalizes the sum of the values(output vector) to be 1.

Tensorflow "with logit": It means that you are applying a softmax function to logit numbers to normalize it. The input_vector/logit is not normalized and can scale from [-inf, inf].

This normalization is used for multiclass classification problems. And for multilabel classification problems sigmoid normalization is used i.e. tf.nn.sigmoid_cross_entropy_with_logits

Angular2 - Http POST request parameters

These answers are all outdated for those utilizing the HttpClient rather than Http. I was starting to go crazy thinking, "I have done the import of URLSearchParams but it still doesn't work without .toString() and the explicit header!"

With HttpClient, use HttpParams instead of URLSearchParams and note the body = body.append() syntax to achieve multiple params in the body since we are working with an immutable object:

login(userName: string, password: string): Promise<boolean> {
    if (!userName || !password) {
      return Promise.resolve(false);

    let body: HttpParams = new HttpParams();
    body = body.append('grant_type', 'password');
    body = body.append('username', userName);
    body = body.append('password', password);

    return, body)
      .map(res => {
        if (res) {          
          return true;
        return false;

Throwing exceptions in a PHP Try Catch block

Just remove the throw from the catch block — change it to an echo or otherwise handle the error.

It's not telling you that objects can only be thrown in the catch block, it's telling you that only objects can be thrown, and the location of the error is in the catch block — there is a difference.

In the catch block you are trying to throw something you just caught — which in this context makes little sense anyway — and the thing you are trying to throw is a string.

A real-world analogy of what you are doing is catching a ball, then trying to throw just the manufacturer's logo somewhere else. You can only throw a whole object, not a property of the object.

How to install a previous exact version of a NPM package?

I have a general way to solve this type of problems, which could be helpful too, especially when cloning repositories to run them locally, but requires a little more analysis of the versions.

With the package npm-check-updates I verify the versions of the packages (according to the package.json file) that are not declared in their latest available versions, as shown in the figure (

enter image description here

With this information we can verify the update status of the different packages and make decisions as to which packages to upgrade / degrade and which ones do not.

Assuming that we decided to update all the packages as they are listed, we can use the ncu -u command which only modifies your package.json file. Run npm install to update your installed packages and package-lock.json.

Then, depending on the requirements of the repository, we can refine what is needed, installing the specific versions with npm view <package> versions and npm install <package>@<version>

Not equal to != and !== in PHP

== and != do not take into account the data type of the variables you compare. So these would all return true:

'0'   == 0
false == 0
NULL  == false

=== and !== do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:

'0'   === 0
false === 0
NULL  === false

You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos():

// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false);  // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned

JavaScript get window X/Y position for scroll

function FastScrollUp()

function FastScrollDown()
     $i = document.documentElement.scrollHeight ; 
 var step = 20;
 var h,t;
 var y = 0;
function SmoothScrollUp()
     h = document.documentElement.scrollHeight;
     y += step;
     window.scrollBy(0, -step)
     if(y >= h )
       {clearTimeout(t); y = 0; return;}
     t = setTimeout(function(){SmoothScrollUp()},20);


function SmoothScrollDown()
     h = document.documentElement.scrollHeight;
     y += step;
     window.scrollBy(0, step)
     if(y >= h )
       {clearTimeout(t); y = 0; return;}
     t = setTimeout(function(){SmoothScrollDown()},20);


What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

In my case I have a kubernetes cluster with nginx ingress controller and nginx+php-fpm to handle drupal instance.

I notice this issue on one of my page, where my pictures was not loaded in chrome. After investigation I discovered that modsecurity module enabled in my nginx ingress somehow produce this issue. Not fully know why, but after disabling it, all pages are loaded fine.

Best Regards.

How can I create database tables from XSD files?

hyperjaxb (versions 2 and 3) actually generates hibernate mapping files and related entity objects and also does a round trip test for a given XSD and sample XML file. You can capture the log output and see the DDL statements for yourself. I had to tweak them a little bit, but it gives you a basic blue print to start with.

Maximum length of HTTP GET request

Browser limits are:

Browser           Address bar    document.location
                                 or anchor tag
Chrome                32779           >64k
Android                8192           >64k
Firefox                >64k           >64k
Safari                 >64k           >64k
Internet Explorer 11   2047           5120
Edge 16                2047          10240

Want more? See this question on Stack Overflow.

How do I create a circle or square with just CSS - with a hollow center?

If you want your div to keep it's circular shape even if you change its width/height (using js for instance) set the radius to 50%. Example: css:

.circle {
    border-radius: 50%/50%; 
    width: 50px;
    height: 50px;
    background: black;


<div class="circle"></div>

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

same happened to me today as described by Vidar.

I have a Build error in a Helper Library (which is referenced by other projects) and instead of telling me that there's an error in Helper Library, the compiler comes up with list of MetaFile-not-found type errors. After correcting the Build error in Helper Library, the MetaFile errors gone.

Is there any setting in VS to improve this?

Get current NSDate in timestamp format

// The following method would return you timestamp after converting to milliseconds. [RETURNS STRING]

- (NSString *) timeInMiliSeconds
    NSDate *date = [NSDate date];
    NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
    return timeInMS;

One DbContext per web request... why?

There are two contradicting recommendations by microsoft and many people use DbContexts in a completely divergent manner.

  1. One recommendation is to "Dispose DbContexts as soon as posible" because having a DbContext Alive occupies valuable resources like db connections etc....
  2. The other states that One DbContext per request is highly reccomended

Those contradict to each other because if your Request is doing a lot of unrelated to the Db stuff , then your DbContext is kept for no reason. Thus it is waste to keep your DbContext alive while your request is just waiting for random stuff to get done...

So many people who follow rule 1 have their DbContexts inside their "Repository pattern" and create a new Instance per Database Query so X*DbContext per Request

They just get their data and dispose the context ASAP. This is considered by MANY people an acceptable practice. While this has the benefits of occupying your db resources for the minimum time it clearly sacrifices all the UnitOfWork and Caching candy EF has to offer.

Keeping alive a single multipurpose instance of DbContext maximizes the benefits of Caching but since DbContext is not thread safe and each Web request runs on it's own thread, a DbContext per Request is the longest you can keep it.

So EF's team recommendation about using 1 Db Context per request it's clearly based on the fact that in a Web Application a UnitOfWork most likely is going to be within one request and that request has one thread. So one DbContext per request is like the ideal benefit of UnitOfWork and Caching.

But in many cases this is not true. I consider Logging a separate UnitOfWork thus having a new DbContext for Post-Request Logging in async threads is completely acceptable

So Finally it turns down that a DbContext's lifetime is restricted to these two parameters. UnitOfWork and Thread

JOptionPane Input to int

String String_firstNumber = JOptionPane.showInputDialog("Input  Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);

Now your Int_firstnumber contains integer value of String_fristNumber.

hope it helped

What does DIM stand for in Visual Basic and BASIC?

It's short for Dimension, as it was originally used in BASIC to specify the size of arrays.

DIM — (short for dimension) define the size of arrays


A part of the original BASIC compiler source code, where it would jump when finding a DIM command, in which you can clearly see the original intention for the keyword:

       SUB N3
       STA RX01
       STA 3
       LDA S        3
       CAB N36              CHECK FOR $ ARRAY
       BRU *+7              NOT $


Later on it came to be used to declare all kinds of variables, when the possibility to specify the type for variables was added in more recent implementations.

Correct Way to Load Assembly, Find Class and Call Run() Method

You will need to use reflection to get the type "TestRunner". Use the Assembly.GetType method.

class Program
    static void Main(string[] args)
        Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
        Type type = assembly.GetType("TestRunner");
        var obj = (TestRunner)Activator.CreateInstance(type);

No connection string named 'MyEntities' could be found in the application config file

I had this error when attempting to use EF within an AutoCAD plugin. CAD plugins get the connection string from the acad.exe.config file. Add the connect string as mentioned above to the acad config file and it works.

Credit goes to Norman.Yuan from ADN.Network.

Get Android API level of phone currently running my application


Values are:

Platform Version   API Level
Android 9.0        28
Android 8.1        27
Android 8.0        26
Android 7.1        25
Android 7.0        24
Android 6.0        23
Android 5.1        22
Android 5.0        21
Android 4.4W       20
Android 4.4        19
Android 4.3        18
Android 4.2        17
Android 4.1        16
Android 4.0.3      15
Android 4.0        14
Android 3.2        13
Android 3.1        12
Android 3.0        11
Android 2.3.3      10
Android 2.3        9
Android 2.2        8
Android 2.1        7
Android 2.0.1      6
Android 2.0        5
Android 1.6        4
Android 1.5        3
Android 1.1        2
Android 1.0        1

CAUTION: don't use android.os.Build.VERSION.SDK_INT if <uses-sdk android:minSdkVersion="3" />.

You will get exception on all devices with Android 1.5 and lower because Build.VERSION.SDK_INT is since SDK 4 (Donut 1.6).

Component is part of the declaration of 2 modules

Had same problem. Just make sure to remove every occurrence of module in "declarations" but AppModule.

Worked for me.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

You can also fix this problem by adding to model (Entity Framework version >= 5)

public DateTime CreationDate { get; set; }

Dump Mongo Collection into JSON format

If you want to dump all collections, run this command:

mongodump -d {DB_NAME}   -o /tmp 

It will generate all collections data in json and bson extensions into /tmp/{DB_NAME} directory

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

my answer is for windows 10 users only as I have tried the following on windows 10. Extending some of the answers above I suggest this : If you are using anaconda then you can avoid everything and simply install anaconda-navigator using the command

conda install -c anaconda anaconda-navigator

Then you can launch the navigator from command prompt using the command


On running this command you get a simple gui where you can create an virtual environment, create the environment with python=3.5.2 and install module tensorflow-gpu or tensorflow by searching the module in the search box using gui, it will also take care of installing correct cuda files for you. Using anaconda navigator is the simplest solution.

If you are not using anaconda then take care about the following

tensorflow-gpu 1.3 requires python 3.5.2, cuda development kit 8.0 and cudaDNN 6.0, hence when installing make sure you run the command

pip install tensorflow-gpu==1.3

tensorflow-gpu 1.2.1 or less requires python 3.5.2, cuda development kit 8.0 and cudaDNN 5.1 hence when installing make sure you run the command

pip install tensorflow-gpu==1.2.1

Below are the steps you need to follow for both of the above processes Setting up you path variables You must have the following system variables

CUDA_HOME = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0"
CUDA_PATH = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0"
CUDA_PATH_V8.0 = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0"

You PATHTEXT must include ".DLL" along with other extensions


Also Add the following to you path

C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\lib\x64
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\extras\CUPTI\libx64;

If you are getting errors you can download the run the below code by mrry, this code will check your setup and tell you if something is wrong

References :

The above reference is very useful. Please comment for improvements to this answer. Hope this helps, Thanks.

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

You are returning Observable<Product> and expecting it to be Product[] inside subscribe callback.

The Type returned from http.get() and getProducts() should be Observable<Product[]>

public getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(`api/products/v1/`);

SQL Server: UPDATE a table by using ORDER BY


Following solution could have problems with clustered indexes involved as mentioned here. Thanks to Martin for pointing this out.

The answer is kept to educate those (like me) who don't know all side-effects or ins and outs of SQL Server.

Expanding on the answer gaven by Quassnoi in your link, following works


INSERT INTO @Test VALUES (1, 'A', 1)
INSERT INTO @Test VALUES (2, 'B', 2)
INSERT INTO @Test VALUES (1, 'E', 5)
INSERT INTO @Test VALUES (3, 'C', 3)
INSERT INTO @Test VALUES (2, 'D', 4)

SET @Number = 0

;WITH q AS (
    SELECT  TOP 1000000 *
    FROM    @Test
SET     @Number = Number = @Number + 1

Most Pythonic way to provide global configuration variables in

How about just using the built-in types like this:

config = {
    "mysql": {
        "user": "root",
        "pass": "secret",
        "tables": {
            "users": "tb_users"
        # etc

You'd access the values as follows:


If you are willing to sacrifice the potential to compute expressions inside your config tree, you could use YAML and end up with a more readable config file like this:

  - user: root
  - pass: secret
  - tables:
    - users: tb_users

and use a library like PyYAML to conventiently parse and access the config file

Nginx -- static file serving confusion with root & alias

as say as @treecoder

In case of the root directive, full path is appended to the root including the location part, whereas in case of the alias directive, only the portion of the path NOT including the location part is appended to the alias.

A picture is worth a thousand words

for root:

enter image description here

for alias:

enter image description here

android:layout_height 50% of the screen size

This is my android:layout_height=50% activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:background="#27b" >

        android:background="#ed6d00" >



<style name="loginType">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:layout_weight">0.5</item>
    <item name="android:orientation">vertical</item>

How to write to the Output window in Visual Studio?

If this is for debug output then OutputDebugString is what you want. A useful macro :

#define DBOUT( s )            \
{                             \
   std::ostringstream os_;    \
   os_ << s;                   \
   OutputDebugString( os_.str().c_str() );  \

This allows you to say things like:

DBOUT( "The value of x is " << x );

You can extend this using the __LINE__ and __FILE__ macros to give even more information.

For those in Windows and wide character land:

#include <Windows.h>
#include <iostream>
#include <sstream>

 #define DBOUT( s )            \
{                             \
   std::wostringstream os_;    \
   os_ << s;                   \
   OutputDebugStringW( os_.str().c_str() );  \

How to upload files in core?

You can add a new property of type IFormFile to your view model

public class CreatePost
   public string ImageCaption { set;get; }
   public string ImageDescription { set;get; }
   public IFormFile MyImage { set; get; }

and in your GET action method, we will create an object of this view model and send to the view.

public IActionResult Create()
   return View(new CreatePost());

Now in your Create view which is strongly typed to our view model, have a form tag which has the enctype attribute set to "multipart/form-data"

@model CreatePost
<form asp-action="Create" enctype="multipart/form-data">   

    <input asp-for="ImageCaption"/>
    <input asp-for="ImageDescription"/>
    <input asp-for="MyImage"/>

    <input type="submit"/>

And your HttpPost action to handle the form posting

public IActionResult Create(CreatePost model)
   var img = model.MyImage;
   var imgCaption = model.ImageCaption;

   //Getting file meta data
   var fileName = Path.GetFileName(model.MyImage.FileName);
   var contentType = model.MyImage.ContentType;

   // do something with the above data
   // to do : return something

If you want to upload the file to some directory in your app, you should use IHostingEnvironment to get the webroot path. Here is a working sample.

public class HomeController : Controller
    private readonly IHostingEnvironment hostingEnvironment;
    public HomeController(IHostingEnvironment environment)
        hostingEnvironment = environment;
    public IActionResult Create(CreatePost model)
        // do other validations on your model as needed
        if (model.MyImage != null)
            var uniqueFileName = GetUniqueFileName(model.MyImage.FileName);
            var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
            var filePath = Path.Combine(uploads,uniqueFileName);
            model.MyImage.CopyTo(new FileStream(filePath, FileMode.Create)); 

            //to do : Save uniqueFileName  to your db table   
        // to do  : Return something
        return RedirectToAction("Index","Home");
    private string GetUniqueFileName(string fileName)
        fileName = Path.GetFileName(fileName);
        return  Path.GetFileNameWithoutExtension(fileName)
                  + "_" 
                  + Guid.NewGuid().ToString().Substring(0, 4) 
                  + Path.GetExtension(fileName);

This will save the file to uploads folder inside wwwwroot directory of your app with a random file name generated using Guids ( to prevent overwriting of files with same name)

Here we are using a very simple GetUniqueName method which will add 4 chars from a guid to the end of the file name to make it somewhat unique. You can update the method to make it more sophisticated as needed.

Should you be storing the full url to the uploaded image in the database ?

No. Do not store the full url to the image in the database. What if tomorrow your business decides to change your company/product name from to ? Now you have to fix all the urls in the table!

What should you store ?

You should store the unique filename which you generated above(the uniqueFileName varibale we used above) to store the file name. When you want to display the image back, you can use this value (the filename) and build the url to the image.

For example, you can do this in your view.

    var imgFileName = "cats_46df.png";
<img src="~/uploads/@imgFileName"  alt="my img"/>

I just hardcoded an image name to imgFileName variable and used that. But you may read the stored file name from your database and set to your view model property and use that. Something like

<img src="~/uploads/@Model.FileName"  alt="my img"/>

Storing the image to table

If you want to save the file as bytearray/varbinary to your database, you may convert the IFormFile object to byte array like this

private byte[] GetByteArrayFromImage(IFormFile file)
    using (var target = new MemoryStream())
        return target.ToArray();

Now in your http post action method, you can call this method to generate the byte array from IFormFile and use that to save to your table. the below example is trying to save a Post entity object using entity framework.

public IActionResult Create(CreatePost model)
    //Create an object of your entity class and map property values
    var post=new Post() { ImageCaption = model.ImageCaption };

    if (model.MyImage != null)
       post.Image =  GetByteArrayFromImage(model.MyImage);
    return RedirectToAction("Index","Home");

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?


CREATE FUNCTION dbo.fn_ConvertToDateTime (@Datetime BIGINT)
    DECLARE @LocalTimeOffset BIGINT
           ,@AdjustedLocalDatetime BIGINT;
    SET @LocalTimeOffset = DATEDIFF(second,GETDATE(),GETUTCDATE())
    SET @AdjustedLocalDatetime = @Datetime - @LocalTimeOffset
    RETURN (SELECT DATEADD(second,@AdjustedLocalDatetime, CAST('1970-01-01 00:00:00' AS datetime)))

Validating Phone Numbers Using Javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../Homepage-30-06-2016/Css.css" >

<script type="text/javascript">

        function isChar(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 47 && charCode < 58) {

                document.getElementById("error").innerHTML = "*Please Enter Your Name Only";
                document.getElementById("fullname").style.borderColor = 'red';
                return false;
            else {
                document.getElementById("error").innerHTML = "";
                document.getElementById("fullname").style.borderColor = '';

                return true;


        <h1 style="margin-left:20px;"Registration Form>Registration Form</h1><hr/>

           Name: <input id="fullname" type="text" placeholder="Full Name*"
                 name="fullname" onKeyPress="return isChar(event)" onChange="return isChar(event);"/><label id="error"></label><br /><br />

<button type="submit" id="submit" name="submit" onClick="return valid(event)" class="btn btn-link text-uppercase"> Submit now</button>

Docker command can't connect to Docker daemon

Giving non-root access - from docker

Add the docker group if it doesn't already exist.

$ sudo groupadd docker

Add the connected user "${USER}" to the docker group.

Change the user name to match your preferred user.

You may have to logout and log back in again for this to take effect.

$ sudo gpasswd -a ${USER} docker

Restart the Docker daemon.

$ sudo service docker restart

Is there a MySQL option/feature to track history of changes to records?

Here is how we solved it

a Users table looked like this

id | name | address | phone | email | created_on | updated_on

And the business requirement changed and we were in a need to check all previous addresses and phone numbers a user ever had. new schema looks like this

Users (the data that won't change over time)
id | name

UserData (the data that can change over time and needs to be tracked)
id | id_user | revision | city | address | phone | email | created_on
 1 |   1     |    0     | NY   | lake st | 9809  | @long | 2015-10-24 10:24:20
 2 |   1     |    2     | Tokyo| lake st | 9809  | @long | 2015-10-24 10:24:20
 3 |   1     |    3     | Sdny | lake st | 9809  | @long | 2015-10-24 10:24:20
 4 |   2     |    0     | Ankr | lake st | 9809  | @long | 2015-10-24 10:24:20
 5 |   2     |    1     | Lond | lake st | 9809  | @long | 2015-10-24 10:24:20

To find the current address of any user, we search for UserData with revision DESC and LIMIT 1

To get the address of a user between a certain period of time we can use created_on bewteen (date1 , date 2)

git still shows files as modified after adding to .gitignore

To the people who might be searching for this issue still, are looking at this page only.

This will help you remove cached index files, and then only add the ones you need, including changes to your .gitignore file.

1. git rm -r --cached .  
2. git add .
3. git commit -m 'Removing ignored files'

Here is a little bit more info.

  1. This command will remove all cached files from index.
  2. This command will add all files except those which are mentioned in gitignore.
  3. This command will commit your files again and remove the files you want git to ignore, but keep them in your local directory.

Reset select value to default

Why not use a simple javascript function and call it on onclick event?

function reset(){
document.getElementById("my_select").selectedIndex = 1; //1 = option 2

"Repository does not have a release file" error

If a sudo apt-get update did not do it for you, it might be that some packages have failed to updated to repository-related errors.

For me all of those happened to reside in (Software Updates --> Other Software). You could remove them with "Remove", the cache will be refreshed successfully. Otherwise

sudo apt-get clean
apt-get autoremove 

is something to try.

recyclerview No adapter attached; skipping layout

This issue is because you are not adding any LayoutManager for your RecyclerView.

Another reason is because you are calling this code in a NonUIThread. Make sure to call this call in the UIThread.

The solution is only you have to add a LayoutManager for the RecyclerView before you setAdapter in the UI Thread.

recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

How can I add new keys to a dictionary?

first to check whether the key already exists


then you can add the new key and value

Android basics: running code in the UI thread

There is a fourth way using Handler

new Handler().post(new Runnable() {
    public void run() {
        // Code here will run in UI thread

Why use the params keyword?

Using params allows you to call the function with no arguments. Without params:

static public int addTwoEach(int[] args)
    int sum = 0;

    foreach (var item in args)
        sum += item + 2;

    return sum;

addtwoEach(); // throws an error

Compare with params:

static public int addTwoEach(params int[] args)
    int sum = 0;

    foreach (var item in args)
        sum += item + 2;

    return sum;

addtwoEach(); // returns 0

Generally, you can use params when the number of arguments can vary from 0 to infinity, and use an array when numbers of arguments vary from 1 to infinity.

Installing Oracle Instant Client

The instantclient works only by defining the folder in the windows PATH environment variable. But you can "install" manually to create some keys in the Windows registry. How?

1) Download instantclient (

2) Unzip the ZIP file (eg c:\oracle\instantclient).

3) Include the above path in the PATH. Set PATH in Windows

4) Create the registry key:

  • Windows 64bit: [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE]

5) In the above registry key, create a sub-key starts with "KEY_" followed by the name of the installation you want:


6) Now create at least three string values ??in the above key:

registry keys for Oracle Home

For those who use Quest SQL Navigator or Quest Toad for Oracle will see that it works. Displays the message "Home is valid.":

Displays the message "Home is valid." in Quest Toad (or SQL Navigator)

The registry keys are now displayed for selecting the oracle client:

selecting the oracle client in Quest SQL Navigator

Solve Cross Origin Resource Sharing with Flask

I might be a late on this question but below steps fixed the issue

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

How to find which version of TensorFlow is installed in my system?

Another variation, i guess :P

python3 -c 'print(__import__("tensorflow").__version__)'

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this.

    Set-ExecutionPolicy RemoteSigned
  2. Run this python script on your powershell script

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    p = subprocess.Popen(["powershell.exe", 

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

Hello World

Descending order by date filter in AngularJs

var myApp = angular.module('myApp', []);_x000D_
myApp.filter("toArray", function () {_x000D_
    return function (obj) {_x000D_
        var result = [];_x000D_
        angular.forEach(obj, function (val, key) {_x000D_
        return result;_x000D_
myApp.controller("mainCtrl", function ($scope) {_x000D_
  $scope.logData = [_x000D_
              { event: 'Payment', created_at: '10/10/2019 6:47 PM PST' },_x000D_
              { event: 'Payment', created_at: '20/10/2019 12:47 AM PST' },_x000D_
              { event: 'Payment', created_at: '30/10/2019 1:50 PM PST' }_x000D_
          ]; _x000D_
<script src=""></script>_x000D_
<div ng-app="myApp" ng-controller="mainCtrl">_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':true" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':false" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_

Opening port 80 EC2 Amazon web services

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

How can I edit a .jar file?

A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.

Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.

You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.

Twitter bootstrap collapse: change display of toggle button

try this.


<div class="row-fluid summary">
    <div class="span11">
    <div class="span1">
        <button class="btn btn-success" data-toggle="collapse" data-target="#intro">+</button>
<div class="row-fluid summary">
    <div id="intro" class="collapse"> 
        Here comes the text...


$('button').click(function(){ //you can give id or class name here for $('button')
        return old=='+' ?  '-' : '+';

Update With pure Css, pseudo elements

Supported Browsers

    content:'+' ;
    content:'-' ;

Update 2 With pure Javascript

function handleClick()
    this.value = (this.value == '+' ? '-' : '+');

Why does Git treat this text file as a binary file?

I was having this issue where Git GUI and SourceTree was treating Java/JS files as binary and thus wouldn’t show a diff.

Creating a file named attributes in .git/info with following content solved the problem:

*.java diff
*.js diff
*.pl diff
*.txt diff
*.ts diff
*.html diff
*.sh diff
*.xml diff

If you would like this to apply to all repositories, then you can add the file attributes in $HOME/.config/git/attributes.

How to insert an item into an array at a specific index (JavaScript)?

What you want is the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

arr.splice(2, 0, "Lene");

C# Lambda expressions: Why should I use them?

A lambda expression is like an anonymous method written in place of a delegate instance.

delegate int MyDelagate (int i);
MyDelagate delSquareFunction = x => x * x;

Consider the lambda expression x => x * x;

The input parameter value is x (on the left side of =>)

The function logic is x * x (on the right side of =>)

A lambda expression's code can be a statement block instead of an expression.

x => {return x * x;};


Note: Func is a predefined generic delegate.

    Console.WriteLine(MyMethod(x => "Hi " + x));

    public static string MyMethod(Func<string, string> strategy)
        return strategy("Lijo").ToString();


  1. How can a delegate & interface be used interchangeably?

Error: Unexpected value 'undefined' imported by the module

The issue is that there is at least one import for which source file is missing.

For example I got the same error when I was using

       import { AppRoutingModule } from './app-routing.module';

But the file './app-routing.module' was not there in given path.

I removed this import and error went away.

How to stop process from .BAT file?

To terminate a process you know the name of, try:

taskkill /IM notepad.exe

This will ask it to close, but it may refuse, offer to "save changes", etc. If you want to forcibly kill it, try:

taskkill /F /IM notepad.exe

How is attr_accessible used in Rails 4?

We can use

params.require(:person).permit(:name, :age)

where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method

OkHttp Post Body as JSON

Just use JSONObject.toString(); method. And have a look at OkHttp's tutorial:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json); // new
  // RequestBody body = RequestBody.create(JSON, json); // old
  Request request = new Request.Builder()
  Response response = client.newCall(request).execute();
  return response.body().string();

Binding Combobox Using Dictionary as the Datasource

userListComboBox.DataSource = userCache.ToList();
userListComboBox.DisplayMember = "Key";

Java ArrayList - how can I tell if two lists are equal, order not mattering?

I had this same problem and came up with a different solution. This one also works when duplicates are involved:

public static boolean equalsWithoutOrder(List<?> fst, List<?> snd){
  if(fst != null && snd != null){
    if(fst.size() == snd.size()){
      // create copied lists so the original list is not modified
      List<?> cfst = new ArrayList<Object>(fst);
      List<?> csnd = new ArrayList<Object>(snd);

      Iterator<?> ifst = cfst.iterator();
      boolean foundEqualObject;
      while( ifst.hasNext() ){
        Iterator<?> isnd = csnd.iterator();
        foundEqualObject = false;
        while( isnd.hasNext() ){
          if( ){
            foundEqualObject = true;

        if( !foundEqualObject ){
          // fail early
      if(cfst.isEmpty()){ //both temporary lists have the same size
        return true;
  }else if( fst == null && snd == null ){
    return true;
  return false;

Advantages compared to some other solutions:

  • less than O(N²) complexity (although I have not tested it's real performance comparing to solutions in other answers here);
  • exits early;
  • checks for null;
  • works even when duplicates are involved: if you have an array [1,2,3,3] and another array [1,2,2,3] most solutions here tell you they are the same when not considering the order. This solution avoids this by removing equal elements from the temporary lists;
  • uses semantic equality (equals) and not reference equality (==);
  • does not sort itens, so they don't need to be sortable (by implement Comparable) for this solution to work.

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

To explain the actual problem that tslint is pointing out, a quote from the JavaScript documentation of the statement:

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

So, basically this means you'll get properties you might not expect to get (from the object's prototype chain).

To solve this we need to iterate only over the objects own properties. We can do this in two different ways (as suggested by @Maxxx and @Qwertiy).

First solution

for (const field of Object.keys(this.formErrors)) {

Here we utilize the Object.Keys() method which returns an array of a given object's own enumerable properties, in the same order as that provided by a loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Second solution

for (var field in this.formErrors) {
    if (this.formErrors.hasOwnProperty(field)) {

In this solution we iterate all of the object's properties including those in it's prototype chain but use the Object.prototype.hasOwnProperty() method, which returns a boolean indicating whether the object has the specified property as own (not inherited) property, to filter the inherited properties out.

jQuery Screen Resolution Height Adjustment

To get screen resolution in JS use screen object


Based on that values you can calculate your margin to whatever suits you.

How to do SQL Like % in Linq?

Contains is used in Linq ,Just like Like is used in SQL .

string _search="/12/";

. . .

.Where(s => s.Hierarchy.Contains(_search))

You can write your SQL script in Linq as Following :

 var result= Organizations.Join(OrganizationsHierarchy.Where(s=>s.Hierarchy.Contains("/12/")),s=>s.Id,s=>s.OrganizationsId,(org,orgH)=>new {org,orgH});

Conditional step/stage in Jenkins pipeline

Just use if and env.BRANCH_NAME, example:

    if (env.BRANCH_NAME == "deployment") {                                          
        ... do some build ...
    } else {                                   
        ... do something else ...

What is the difference between dict.items() and dict.iteritems() in Python2?

If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:

DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))

Use it like this:

for key, value in DICT_ITER_ITEMS(myDict):
    # Do something with 'key' and/or 'value'.

Adding custom radio buttons in android

Setting android:background and android:button of the RadioButton like the accepted answer didn't work for me. The drawable image was being displayed as a background(eventhough android:button was being set to transparent ) to the radio button text as enter image description here


so gave radiobutton as the custom drawable radiobuttonstyle.xml


and radiobuttonstyle.xml is as follows

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="">
  <item android:state_checked="true" android:drawable="@drawable/ic_radio_checked"></item>
  <item android:state_checked="false" android:drawable="@drawable/ic_radio_unchecked"></item>

and after this radiobutton with custom button style worked.

enter image description here

No converter found capable of converting from type to type

Turns out, when the table name is different than the model name, you have to change the annotations to:

@Table(name = "table_name")
class WhateverNameYouWant {

Instead of simply using the @Entity annotation.

What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.

image.onload event and browser cache

If the src is already set then the event is firing in the cached case before you even get the event handler bound. So, you should trigger the event based off .complete also.

code sample:

$("img").one("load", function() {
   //do stuff
}).each(function() {
   if(this.complete || /*for IE 10-*/ $(this).height() > 0)

ASP.NET Identity reset password

Best way to Reset Password in Asp.Net Core Identity use for Web API.

Note* : Error() and Result() are created for internal use. You can return you want.

        public async Task<IActionResult> ResetPassword(ResetPasswordModel model)
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
                if (model is null)
                    return Error("No data found!");

                var user = await _userManager.FindByIdAsync(AppCommon.ToString(GetUserId()));
                if (user == null)
                    return Error("No user found!");

                Microsoft.AspNetCore.Identity.SignInResult checkOldPassword =
                    await _signInManager.PasswordSignInAsync(user.UserName, model.OldPassword, false, false);

                if (!checkOldPassword.Succeeded)
                    return Error("Old password does not matched.");

                string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
                if (string.IsNullOrEmpty(resetToken))
                    return Error("Error while generating reset token.");

                var result = await _userManager.ResetPasswordAsync(user, resetToken, model.Password);

                if (result.Succeeded)
                    return Result();
                    return Error();
            catch (Exception ex)
                return Error(ex);

JavaScript checking for null vs. undefined and difference between == and ===

How do I check a variable if it's null or undefined

just check if a variable has a valid value like this :


it will return true if variable does't contain :

  • null
  • undefined
  • 0
  • false
  • "" (an empty string)
  • NaN

Stopping an Android app from console

If you have access to the application package, then you can install with the -r option and it will kill the process if it is currently running as a side effect. Like this:

adb -d install -r MyApp.apk ; adb -d shell am start -a android.intent.action.MAIN -n com.MyCompany.MyApp/.MyActivity

The -r option preserves the data currently associated with the app. However, if you want a clean slate like you mention you might not want to use that option.

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { = name;
    move(meters: number) {
        console.log( + " moved " + meters + "m.");

class Horse extends Animal {
    move() {
        console.log( + " is Galloping...");
        console.log( + " is Galloping...");

var tom: Animal = new Horse("Tommy the Palomino"); = 'horseee'; 

// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.


  1. The first log outputs, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

How to create an HTML button that acts like a link?

If what you need is that it will look like a button, with emphasis on the gradient image, you can do this:

<a href="" class="btn btn-gradient"><i class="fa fa-home"> Button Text</i></a>

How to check compiler log in sql developer?

control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).

if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up

for instance, hit Control-shift-L then execute this

VAR := 2;
end TEST123;

and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "

(You can also see this in "View--Log")

One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)

How to run Unix shell script from Java code?

You should really look at Process Builder. It is really built for this kind of thing.

ProcessBuilder pb = new ProcessBuilder("", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.put("VAR2", env.get("VAR1") + "suffix"); File("myDir"));
 Process p = pb.start();

How do I rename the extension for a bunch of files?

On a Mac...

  1. Install rename if you haven't: brew install rename
  2. rename -S .html .txt *.html

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict

Select element by exact match of its content

An one-liner that works with alternative libraries to jQuery:

$('p').filter((i, p) => $(p).text().trim() === "hello").css('font-weight', 'bold');

And this is the equivalent to a jQuery's a:contains("pattern") selector:

var res = $('a').filter((i, a) => $(a).text().match(/pattern/));

Debugging Stored Procedure in SQL Server 2008

MSDN has provided easy way to debug the stored procedure. Please check this link-
How to: Debug Stored Procedures

Apache: The requested URL / was not found on this server. Apache

Non-trivial reasons:

  • if your .htaccess is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert )
  • if your .htaccess is in UTF8 Without-BOM, make it WITH BOM.

Initializing a list to a known number of elements in Python


 lst = [8 for i in range(9)]

creates a list, elements are initialized 8

but this:

lst = [0] * 7

would create 7 lists which have one element

Change Project Namespace in Visual Studio

"Default Namespace textbox in project properties is disabled" Same with me (VS 2010). I edited the project file ("xxx.csproj") and tweaked the item. That changed the default namespace.

Using sed, Insert a line above or below the pattern?

Insert a new verse after the given verse in your stanza:

sed -i '/^lorem ipsum dolor sit amet$/ s:$:\nconsectetur adipiscing elit:' FILE

Android Completely transparent Status Bar?

You can use this below code.


Include this layout in your main layout.


<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android=""

            android:background="@drawable/main_background2">  //add your color here


                    android:src="@drawable/nav_icon" />

                    tools:text="test Data" />




Note: You can replace SDP and SSP with dp and sp respectively.

PHP regular expression - filter number only

Using is_numeric or intval is likely the best way to validate a number here, but to answer your question you could try using preg_replace instead. This example removes all non-numeric characters:

$output = preg_replace( '/[^0-9]/', '', $string );

How to get all keys with their values in redis

Yes, you can do print all keys using below bash script,

for key in $(redis-cli -p 6379 keys \*);
  do echo "Key : '$key'" 
     redis-cli -p 6379 GET $key;

where, 6379 is a port on which redis is running.

How can I refresh a page with jQuery?

There are multiple unlimited ways to refresh a page with JavaScript:

  1. location.reload()
  2. history.go(0)
  3. location.href = location.href
  4. location.href = location.pathname
  5. location.replace(location.pathname)
  6. location.reload(false)

    If we needed to pull the document from the web-server again (such as where the document contents change dynamically) we would pass the argument as true.

You can continue the list being creative:

  • window.location = window.location
  • window.self.window.self.window.window.location = window.location
  • ...and other 534 ways

var methods = [_x000D_
  "location.href = location.href",_x000D_
  "location.href = location.pathname",_x000D_
var $body = $("body");_x000D_
for (var i = 0; i < methods.length; ++i) {_x000D_
  (function(cMethod) {_x000D_
    $body.append($("<button>", {_x000D_
      text: cMethod_x000D_
    }).on("click", function() {_x000D_
      eval(cMethod); // don't blame me for using eval_x000D_
button {_x000D_
  background: #2ecc71;_x000D_
  border: 0;_x000D_
  color: white;_x000D_
  font-weight: bold;_x000D_
  font-family: "Monaco", monospace;_x000D_
  padding: 10px;_x000D_
  border-radius: 4px;_x000D_
  cursor: pointer;_x000D_
  transition: background-color 0.5s ease;_x000D_
  margin: 2px;_x000D_
button:hover {_x000D_
  background: #27ae60;_x000D_
<script src=""></script>

How to create a custom string representation for a class object?

Implement __str__() or __repr__() in the class's metaclass.

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object):
  __metaclass__ = MC

print C

Use __str__ if you mean a readable stringification, use __repr__ for unambiguous representations.

How to change the background color of Action Bar's Option Menu in Android 4.2?

The Action Bar Style Generator, suggested by Sunny, is very useful, but it generates a lot of files, most of which are irrelevant if you only want to change the background colour.

So, I dug deeper into the zip it generates, and tried to narrow down what are the parts that matter, so I can make the minimum amount of changes to my app. Below is what I found out.

In the style generator, the relevant setting is Popup color, which affects "Overflow menu, submenu and spinner panel background".

enter image description here

Go on and generate the zip, but out of all the files generated, you only really need one image, menu_dropdown_panel_example.9.png, which looks something like this:

enter image description here

So, add the different resolution versions of it to res/drawable-*. (And perhaps rename them to menu_dropdown_panel.9.png.)

Then, as an example, in res/values/themes.xml you would have the following, with android:popupMenuStyle and android:popupBackground being the key settings.


    <style name="MyAppActionBarTheme" parent="android:Theme.Holo.Light">
        <item name="android:popupMenuStyle">@style/MyApp.PopupMenu</item>
        <item name="android:actionBarStyle">@style/MyApp.ActionBar</item>

    <!-- The beef: background color for Action Bar overflow menu -->
    <style name="MyApp.PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/menu_dropdown_panel</item>

    <!-- Bonus: if you want to style whole Action Bar, not just the menu -->
    <style name="MyApp.ActionBar" parent="android:Widget.Holo.Light.ActionBar.Solid">
        <!-- Blue background color & black bottom border -->
        <item name="android:background">@drawable/blue_action_bar_background</item>


And, of course, in AndroidManifest.xml:

    ... >

What you get with this setup:

enter image description here

Note that I'm using Theme.Holo.Light as the base theme. If you use Theme.Holo (Holo Dark), there's an additional step needed as this answer describes!

Also, if you (like me) wanted to style the whole Action Bar, not just the menu, put something like this in res/drawable/blue_action_bar_background.xml:

<!-- Bonus: if you want to style whole Action Bar, not just the menu -->
<layer-list xmlns:android="" >

        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:color="#FF000000" />
            <solid android:color="#FF2070B0" />                   

    <item android:bottom="2dp">
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:color="#FF2070B0" />
            <solid android:color="#00000000" />
            <padding android:bottom="2dp" />


Works great at least on Android 4.0+ (API level 14+).

Definition of a Balanced Tree

  1. The height of a node in a tree is the length of the longest path from that node downward to a leaf, counting both the start and end vertices of the path.
  2. A node in a tree is height-balanced if the heights of its subtrees differ by no more than 1.
  3. A tree is height-balanced if all of its nodes are height-balanced.

Masking password input from the console : Java

Console console = System.console();
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");

What does string::npos mean in this code?

It means not found.

It is usually defined like so:

static const size_t npos = -1;

It is better to compare to npos instead of -1 because the code is more legible.

Count textarea characters

I found that the accepted answer didn't exactly work with textareas for reasons noted in Chrome counts characters wrong in textarea with maxlength attribute because of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the input and propertychange events. The following takes newline characters into account and accurately calculates the length of a textarea.

$(function() {_x000D_
  $("#myTextArea").on("input propertychange", function(event) {_x000D_
    var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;_x000D_
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
<script src=""></script>_x000D_
<textarea id="myTextArea"></textarea><br>_x000D_
Size: <span id="counter" />

Upload file to FTP using C#

public void UploadFtpFile(string folderName, string fileName)

    FtpWebRequest request;

    string folderName; 
    string fileName;
    string absoluteFileName = Path.GetFileName(fileName);

    request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/{2}", "", folderName, absoluteFileName))) as FtpWebRequest;
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UseBinary = 1;
    request.UsePassive = 1;
    request.KeepAlive = 1;
    request.Credentials =  new NetworkCredential(user, pass);
    request.ConnectionGroupName = "group"; 

    using (FileStream fs = File.OpenRead(fileName))
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(buffer, 0, buffer.Length);

How to use

UploadFtpFile("testFolder", "E:\\filesToUpload\\test.img");

use this in your foreach

and you only need to create folder one time

to create a folder

request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/", "", "testFolder"))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse ftpResponse = (FtpWebResponse)request.GetResponse();

How to transfer paid android apps from one google account to another google account

Google has this to say on transferring data between accounts.

It lists certain types of data that CAN be transferred and certain types of data that CAN NOT be transferred. Unfortunately Google Play Apps falls into the NOT category.

It's conveniently titled: "Moving Product Data"

How do I remove repeated elements from ArrayList?

If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:

Set<String> set = new HashSet<>(yourList);

Of course, this destroys the ordering of the elements in the ArrayList.

How do I mock a class without an interface?

The standard mocking frameworks are creating proxy classes. This is the reason why they are technically limited to interfaces and virtual methods.

If you want to mock 'normal' methods as well, you need a tool that works with instrumentation instead of proxy generation. E.g. MS Moles and Typemock can do that. But the former has a horrible 'API', and the latter is commercial.

Generate PDF from Swagger API documentation

You can modify your REST project, so as to produce the needed static documents (html, pdf etc) upon building the project.

If you have a Java Maven project you can use the pom snippet below. It uses a series of plugins to generate a pdf and an html documentation (of the project's REST resources).

  1. rest-api -> swagger.json : swagger-maven-plugin
  2. swagger.json -> Asciidoc : swagger2markup-maven-plugin
  3. Asciidoc -> PDF : asciidoctor-maven-plugin

Please be aware that the order of execution matters, since the output of one plugin, becomes the input to the next:

                    <title>Put your REST service's name here</title>
                    <description>Add some description</description>
            <!-- fx process-classes phase -->
        <!-- specify location to place asciidoc files -->
        <!-- You will need to create an .adoc file. This is the input to this plugin -->
            <!-- this path is referenced in swagger.adoc file. The given file will simply 
                point to the previously create adoc files/assemble them. -->
                <!-- specify location to place html file -->
                <!-- specify location to place pdf file -->

The asciidoctor plugin assumes the existence of an .adoc file to work on. You can create one that simply collects the ones that were created by the swagger2markup plugin:


If you want your generated html document to become part of your war file you have to make sure that it is present on the top level - static files in the WEB-INF folder will not be served. You can do this in the maven-war-plugin:

            <!-- Add swagger.pdf to WAR file, so as to make it available as static content. -->
            <!-- Add swagger.html to WAR file, so as to make it available as static content. -->

The war plugin works on the generated documentation - as such, you must make sure that those plugins have been executed in an earlier phase.

Why can't I duplicate a slice with `copy()`?

The Go Programming Language Specification

Appending to and copying slices

The function copy copies slice elements from a source src to a destination dst and returns the number of elements copied. Both arguments must have identical element type T and must be assignable to a slice of type []T. The number of elements copied is the minimum of len(src) and len(dst). As a special case, copy also accepts a destination argument assignable to type []byte with a source argument of a string type. This form copies the bytes from the string into the byte slice.

copy(dst, src []T) int
copy(dst []byte, src string) int

tmp needs enough room for arr. For example,

package main

import "fmt"

func main() {
    arr := []int{1, 2, 3}
    tmp := make([]int, len(arr))
    copy(tmp, arr)


[1 2 3]
[1 2 3]

how to delete default values in text field using selenium?

And was the code helpful? Because the code you are writing should do the thing:


If it does not help, then try this:

WebElement toClear = driver.findElement("locator");
toClear.sendKeys(Keys.CONTROL + "a");

maybe you will have to do some convert of the Keys.CONTROL + "a" to CharSequence, but the first approach should do the magic

Why is the Java main method static?

From (there's more information on the site) :

The main method is static to give the Java VM interpreter a way to start the class without creating an instance of the control class first. Instances of the control class are created in the main method after the program starts.

My understanding has always been simply that the main method, like any static method, can be called without creating an instance of the associated class, allowing it to run before anything else in the program. If it weren't static, you would have to instantiate an object before calling it-- which creates a 'chicken and egg' problem, since the main method is generally what you use to instantiate objects at the beginning of the program.

Changing :hover to touch/click for mobile devices

You can add onclick="" to hovered element. Hover will work after that.

Edit: But you really shouldn't add anything style related to your markup, just posted it as an alternative.

How can I get the height and width of an uiimage?

UIImage *img = [UIImage imageNamed:@"logo.png"];

CGFloat width = img.size.width;
CGFloat height = img.size.height;

React.js: Identifying different inputs with one onChange handler

You can use a special React attribute called ref and then match the real DOM nodes in the onChange event using React's getDOMNode() function:

handleClick: function(event) {
  if ( === this.refs.prev.getDOMNode()) {

render: function() {
  <button ref="prev" onClick={this.handleClick}>Previous question</button>
  <button ref="next" onClick={this.handleClick}>Next question</button>

How do I determine the dependencies of a .NET application?

Enable assembly binding logging set the registry value EnableLog in HKLM\Software\Microsoft\Fusion to 1. Note that you have to restart your application (use iisreset) for the changes to have any effect.

Tip: Remember to turn off fusion logging when you are done since there is a performance penalty to have it turned on.

JPG vs. JPEG image formats

They are identical. JPG is simply a holdover from the days of DOS when file extensions were required to be 3 characters long. You can find out more information about the JPEG standard here. A question very similar to this one was asked over at SuperUser, where the accepted answer should give you some more detailed information.

Defining lists as global variables in Python

When you assign a variable (x = ...), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:

x = 0
def f():
    x = 1
print x #=>0

and expect 1. Instead, you need do declare that you intend to use the global x:

x = 0
def f():
    global x
    x = 1
print x #=>1

But note that assignment of a variable is very different from method calls. You can always call methods on anything in scope - e.g. on variables that come from an outer (e.g. the global) scope because nothing local shadows them.

Also very important: Member assignment ( = ...), item assignment (collection[key] = ...), slice assignment (sliceable[start:end] = ...) and propably more are all method calls as well! And therefore you don't need global to change a global's members or call it methods (even when they mutate the object).

Change the maximum upload file size

Non of those solutions work for me!! (already set to 32M by default).The problem is in most case max_allowed_packet

I am working on localhost and using MAMP.

Here is solutions;

1. If you don't have my.ini





2. If you have my.ini






How to count the number of occurrences of a character in an Oracle varchar value?

Here you go:

select length('123-345-566') - length(replace('123-345-566','-',null)) 
from dual;

Technically, if the string you want to check contains only the character you want to count, the above query will return NULL; the following query will give the correct answer in all cases:

select coalesce(length('123-345-566') - length(replace('123-345-566','-',null)), length('123-345-566'), 0) 
from dual;

The final 0 in coalesce catches the case where you're counting in an empty string (i.e. NULL, because length(NULL) = NULL in ORACLE).

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

The issue arises when the image is not present on the cluster and k8s engine is going to pull the respective registry. k8s Engine enables 3 types of ImagePullPolicy mentioned :

  1. Always : It always pull the image in container irrespective of changes in the image
  2. Never : It will never pull the new image on the container
  3. IfNotPresent : It will pull the new image in cluster if the image is not present.

Best Practices : It is always recommended to tag the new image in both docker file as well as k8s deployment file. So That it can pull the new image in container.

Sum all the elements java arraylist

Not very hard, just use m.get(i) to get the value from the list.

public double incassoMargherita()
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
        sum += m.get(i);
    return sum;

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

In Python we can use the __str__() method.

We can override it in our class like this:

class User: 

    firstName = ''
    lastName = ''

    def __str__(self):
        return self.firstName + " " + self.lastName

and when running


it will call the function __str__(self) and print the firstName and lastName

scp or sftp copy multiple files with single command

In the specific case where all the files have the same extension but with different suffix (say number of log file) you use the following:

scp [email protected]:/some/log/folder/some_log_file.* ./

This will copy all files named some_log_file from the given folder within the remote, i.e.- some_log_file.1 , some_log_file.2, some_log_file.3 ....

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Additionnally to hotkey's good answer, here is how I choose among the two in practice:

lateinit is for external initialisation: when you need external stuff to initialise your value by calling a method.

e.g. by calling:

private lateinit var value: MyClass

fun init(externalProperties: Any) {
   value = somethingThatDependsOn(externalProperties)

While lazy is when it only uses dependencies internal to your object.

How to install a specific version of Node on Ubuntu?

It is possible to install specific version of nodejs from nodejs official distribution with using dpkg.

For example, currently recent 4.x version is 4.2.4, but you can install previous 4.2.3 version.

curl -s -O
sudo apt-get install rlwrap
sudo dpkg -i nodejs_4.2.3-1nodesource1~trusty1_amd64.deb

Angular 5, HTML, boolean on checkbox is checked

Work with checkboxes using observables

You could even choose to use a behaviourSubject to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$ observable.

In your component.ts:

public isChecked$ = new BehaviorSubject(false);
toggleChecked() {

In your template

<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">

Sorting an array in C?


It depends on various things. But in general algorithms using a Divide-and-Conquer / dichotomic approach will perform well for sorting problems as they present interesting average-case complexities.


To understand which algorithms work best, you will need basic knowledge of algorithms complexity and big-O notation, so you can understand how they rate in terms of average case, best case and worst case scenarios. If required, you'd also have to pay attention to the sorting algorithm's stability.

For instance, usually an efficient algorithm is quicksort. However, if you give quicksort a perfectly inverted list, then it will perform poorly (a simple selection sort will perform better in that case!). Shell-sort would also usually be a good complement to quicksort if you perform a pre-analysis of your list.

Have a look at the following, for "advanced searches" using divide and conquer approaches:

And these more straighforward algorithms for less complex ones:


The above are the usual suspects when getting started, but there are countless others.

As pointed out by R. in the comments and by kriss in his answer, you may want to have a look at HeapSort, which provides a theoretically better sorting complexity than a quicksort (but will won't often fare better in practical settings). There are also variants and hybrid algorithms (e.g. TimSort).

How do I call a dynamically-named method in Javascript?

Try These

Call Functions With Dynamic Names, like this:

let dynamic_func_name = 'alert';
(new Function(dynamic_func_name+'()'))()

with parameters:

let dynamic_func_name = 'alert';
let para_1 = 'HAHAHA';
let para_2 = 'ABCD';
(new Function(`${dynamic_func_name}('${para_1}','${para_2}')`))()

Run Dynamic Code:

let some_code = "alert('hahaha');";
(new Function(some_code))()

How to set an HTTP proxy in Python 2.7?

cd C:\Python34\Scripts



pip.exe install PackageName

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.


|            | shape (10000)  |  shape (1,10000)  |
| np.concat  |    0.18280     |      0.17960      |
|  np.stack  |    0.21501     |      0.16465      |
| np.vstack  |    0.21501     |      0.17181      |
|  np.array  |    0.21656     |      0.16833      |

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.


from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)

start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

Why does foo = filter(...) return a <filter object>, not a list?

From the documentation

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)]

In python3, rather than returning a list; filter, map return an iterable. Your attempt should work on python2 but not in python3

Clearly, you are getting a filter object, make it a list.

shesaid = list(filter(greetings(), ["hello", "goodbye"]))

How to downgrade python from 3.7 to 3.6

If you use anaconda, you can just create a new environment with the specified version. In case you don't want to keep the existing version 3.7, you can just uninstall it and install it from here.

Multiline strings in VB.NET

if it's like C# (I don't have VB.Net installed) you can prefix a string with @

foo = @"Multiline

this is also useful for things like @"C:\Windows\System32\" - it essentially turns off escaping and turns on multiline.

Test a weekly cron job

None of these answers fit my specific situation, which was that I wanted to run one specific cron job, just once, and run it immediately.

I'm on a Ubuntu server, and I use cPanel to setup my cron jobs.

I simply wrote down my current settings, and then edited them to be one minute from now. When I fixed another bug, I just edited it again to one minute from now. And when I was all done, I just reset the settings back to how they were before.

Example: It's 4:34pm right now, so I put 35 16 * * *, for it to run at 16:35.

It worked like a charm, and the most I ever had to wait was a little less than one minute.

I thought this was a better option than some of the other answers because I didn't want to run all of my weekly crons, and I didn't want the job to run every minute. It takes me a few minutes to fix whatever the issues were before I'm ready to test it again. Hopefully this helps someone.

How do you test that a Python function throws an exception?

You can use context manager to run the faulty function and assert it raises the exception with a certain message using assertRaisesMessage

with self.assertRaisesMessage(SomeException,'Some error message e.g 404 Not Found'):

Python match a string with regex

As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:

line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
     i in line

>> True
>> True

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
    item.SingleLineString = "a single-line string";
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
    function Getinfo(text) {

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

Setting Short Value Java

In Java, integer literals are of type int by default. For some other types, you may suffix the literal with a case-insensitive letter like L, D, F to specify a long, double, or float, respectively. Note it is common practice to use uppercase letters for better readability.

The Java Language Specification does not provide the same syntactic sugar for byte or short types. Instead, you may declare it as such using explicit casting:

byte foo = (byte)0;
short bar = (short)0;

In your setLongValue(100L) method call, you don't have to necessarily include the L suffix because in this case the int literal is automatically widened to a long. This is called widening primitive conversion in the Java Language Specification.

What is the purpose of a plus symbol before a variable?

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

How to make node.js require absolute? (instead of relative)

i created a node module called "rekiure"

it allows you to require without the use of relative paths

it is super easy to use

Why is 1/1/1970 the "epoch time"?


The earliest versions of Unix time had a 32-bit integer incrementing at a rate of 60 Hz, which was the rate of the system clock on the hardware of the early Unix systems. The value 60 Hz still appears in some software interfaces as a result. The epoch also differed from the current value. The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".

Create an empty list in python with certain size

Make it more reusable as a function.

def createEmptyList(length,fill=None):
    return a (empty) list of a given length
        print createEmptyList(3,-1)
        >> [-1, -1, -1]
        print createEmptyList(4)
        >> [None, None, None, None]
    return [fill] * length

Save the console.log in Chrome to a file

For better log file (without the Chrome-debug nonsense) use:

--enable-logging --log-level=0

instead of --v=1 which is just too much info.

It will still provide the errors and warnings like you would typically see in the Chrome console.

update May 18, 2020: Actually, I think this is no longer true. I couldn't find the console messages within whatever this logging level is.

maven "cannot find symbol" message unhelpful

Even I am using Java 7, maven 2.2.1 and was getting the same error, I removed <scope>tests</scope> from my pom and used

mvn clean -DskipTests=true install to successfully build my projects, without upgrading my maven version.

SSIS cannot convert because a potential loss of data

I had the same issue, multiple data type values in single column, package load only numeric values. Remains all it updated as null.


To fix this changing the excel data type is one of the solution. In Excel Copy the column data and paste in different file. Delete that column and insert new column as Text datatype and paste that copied data in new column.

Now in ssis package delete and recreate the Excel source and destination table change the column data type as varchar.

This will work.

Function that creates a timestamp in c#

You can also use


How to clear the entire array?

ReDim aFirstArray(0)

This will resize the array to zero and erase all data.

Updating GUI (WPF) using a different thread


I am also developing a serial port testing tool using WPF, and I'd like to share some experience of mine.

I think you should refactor your source code according to MVVM design pattern.

At the beginning, I met the same problem as you met, and I solved it using this code:

new Thread(() => 
    while (...)
        SomeTextBox.Dispatcher.BeginInvoke((Action)(() => SomeTextBox.Text = ...));

This works, but is too ugly. I have no idea how to refactor it, until I saw this:

This is a very kindly step-by-step MVVM tutorial for beginners. No shiny UI, no complex logic, only the basic of MVVM.

CSS-moving text from left to right

If I understand you question correctly, you could create a wrapper around your marquee and then assign a width (or max-width) to the wrapping element. For example:

<div id="marquee-wrapper">
    <div class="marquee">This is a marquee!</div>   

And then #marquee-wrapper { width: x }.

websocket closing connection automatically

Just found the solution to this for myself. What you want to set is the maxIdleTime of WebSocketServlet, in millis. How to do that depends on how you config your servlet. With Guice ServletModule you can do something like this for timeout of 10 hours:

new HashMap<String, Sring>(){{ put("maxIdleTime", TimeUnit.HOURS.toMillis(10) + ""); }});

Anything <0 is infinite idle time I believe.

What is the difference between an int and an Integer in Java and C#?

In C#, int is just an alias for System.Int32, string for System.String, double for System.Double etc...

Personally I prefer int, string, double, etc. because they don't require a using System; statement :) A silly reason, I know...

Cannot connect to the Docker daemon on macOS

i simply had to run spotlight search and execute the Docker application under /Applications folder which brew cask install created. Once this was run it asked to complete installation. I was then able to run docker ps

How to change the color of progressbar in C# .NET 3.5?

All these methods fail to work for me but this method allows you to change it to a color string.

Please note that i found this code from somewhere else on StackOverflow and changed it a little. I have since forgot where i found this code and i can't link it because of that so sorry for that.

But anyway i hope this code helps someone it really did help me.

private void ProgressBar_MouseDown(object sender, MouseButtonEventArgs e)
        var converter = new System.Windows.Media.BrushConverter();
        var brush = (Brush)converter.ConvertFromString("#FFB6D301");
        ProgressBar.Foreground = brush;

Where the name "ProgressBar" is used replace with your own progress bar name. You can also trigger this event with other arguments just make sure its inside brackets somewhere.

How to give a pandas/matplotlib bar graph custom colors

For a more detailed answer on creating your own colormaps, I highly suggest visiting this page

If that answer is too much work, you can quickly make your own list of colors and pass them to the color parameter. All the colormaps are in the cm matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.

from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))

array([[ 0.865006,  0.316822,  0.226055,  1.      ],
       [ 0.851384,  0.30226 ,  0.239636,  1.      ],
       [ 0.832299,  0.283913,  0.257383,  1.      ],
       [ 0.817341,  0.270954,  0.27039 ,  1.      ],
       [ 0.796607,  0.254728,  0.287264,  1.      ],
       [ 0.775059,  0.239667,  0.303526,  1.      ],
       [ 0.758422,  0.229097,  0.315266,  1.      ],
       [ 0.735683,  0.215906,  0.330245,  1.      ],

Then we can use this to plot, using the data from the original post:

import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))

enter image description here

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

Follow these steps:
Right click on designing part > Constraint Layout > Infer Constraints

Run / Open VSCode from Mac Terminal

To set it up, launch VS Code. Then open the Command Palette (??P) and type shell command to find the Shell Command: Install 'code' command in PATH command.enter image description here

Send POST data using XMLHttpRequest

I have faced similar problem, using the same post and and this link I have resolved my issue.

 var http = new XMLHttpRequest();
 var url = "MY_URL.Com/login.aspx";
 var params = 'eid=' +userEmailId+'&amp;pwd='+userPwd"POST", url, true);

 // Send the proper header information along with the request
 //http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 //http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
 //http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"

 // Call a function when the state 
 http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {

This link has completed information.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are synonyms, no difference at all.Decimal and Numeric data types are numeric data types with fixed precision and scale.

-- Initialize a variable, give it a data type and an initial value

declare @myvar as decimal(18,8) or numeric(18,8)----- 9 bytes needed

-- Increse that the vaue by 1

set @myvar = 123456.7

--Retrieve that value

select @myvar as myVariable

How can I create an error 404 in PHP?

Did you remember to die() after sending the header? The 404 header doesn't automatically stop processing, so it may appear not to have done anything if there is further processing happening.

It's not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your "what are you looking for?" page for the human reader.

AngularJs .$setPristine to reset form

DavidLn's answer has worked well for me in the past. But it doesn't capture all of setPristine's functionality, which tripped me up this time. Here is a fuller shim:

var form_set_pristine = function(form){
    // 2013-12-20 DF TODO: remove this function on Angular 1.1.x+ upgrade
    // function is included natively

    } else {
        form.$pristine = true;
        form.$dirty = false;
        angular.forEach(form, function (input, key) {
            if (input.$pristine)
                input.$pristine = true;
            if (input.$dirty) {
                input.$dirty = false;

bash: shortest way to get n-th column of output

If you are ok with manually selecting the column, you could be very fast using pick:

svn st | pick | xargs rm

Just go to any cell of the 2nd column, press c and then hit enter

How to cin to a vector

cin is delimited on space, so if you try to cin "1 2 3 4 5" into a single integer, your only going to be assigning 1 to the integer, a better option is to wrap your input and push_back in a loop, and have it test for a sentinel value, and on that sentinel value, call your write function. such as

int input;
cout << "Enter your numbers to be evaluated, and 10000 to quit: " << endl;
while(input != 10000) {
    cin >> input;

iPhone: Setting Navigation Bar Title

I had a navigation controllers integrated in a TabbarController. This worked


Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

some dynamic situation holder.edit_pin.setInputType(InputType.TYPE_CLASS_NUMBER); will not work so better use both like that


Note : this is suitable for when you are using dynamic controls like using arrayaapter

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

For me Fake Sendmail works.

What to do:

1) Edit C:\wamp\sendmail\sendmail.ini:
[email protected]

2) Edit php.ini and set sendmail_path

sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

That's it. Now you can test a mail.

JQuery Parsing JSON array

Use the parseJSON method:

var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);

Then you have an array with the city names.

How can I delete a user in linux when the system says its currently used in a process

Only solution that worked for me

$ sudo killall -u username && sudo deluser --remove-home -f username

The killall command is used if multiple processes are used by the user you want to delete.

The -f option forces the removal of the user account, even if the user is still logged in. It also forces deluser to remove the user's home directory and mail spool, even if another user uses the same home directory.

Please confirm that it works in the comments.

not:first-child selector

This CSS2 solution ("any ul after another ul") works, too, and is supported by more browsers.

div ul + ul {
  background-color: #900;

Unlike :not and :nth-sibling, the adjacent sibling selector is supported by IE7+.

If you have JavaScript changes these properties after the page loads, you should look at some known bugs in the IE7 and IE8 implementations of this. See this link.

For any static web page, this should work perfectly.

Waiting till the async task finish its work

I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :

Create an Interface :

public interface AsyncResponse {
    void processFinish(String output);

Then in asynctask

protected void onPostExecute(String data) {

Then in yout main activity

public void processFinish(String data) {
     // do things


How to set Spring profile from system variable?

My solution is to set the environment variable as So that all applications running in that machine will refer the variable and start the application. The order in which spring loads a properties as follows
system properties
environment variable

CSS: Fix row height

Simply add style="line-height:0" to each cell. This works in IE because it sets the line-height of both existant and non-existant text to about 19px and that forces the cells to expand vertically in most versions of IE. Regardless of whether or not you have text this needs to be done for IE to correctly display rows less than 20px high.

How do I start Mongo DB from Windows?

I have followed the below steps...May be it will work for you

Create directory like below


mongod --port 27017 --dbpath "C:\data\db"

It worked for me....

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Well I got this Issue too in my few websites and all i need to do is customize the content fetler for HTML entites. before that more i delete them more i got, so just change you html fiter or parsing function for the page and it worked. Its mainly due to HTML editors in most of CMSs. the way they store parse the data caused this issue (In My case). May this would Help in your case too

What is setBounds and how do I use it?

You can use setBounds(x, y, width, height) to specify the position and size of a GUI component if you set the layout to null. Then (x, y) is the coordinate of the upper-left corner of that component.

Activate tabpage of TabControl

You can use the method SelectTab.

There are 3 versions:

public void SelectTab(int index);
public void SelectTab(string tabPageName);
public void SelectTab(TabPage tabPage);

Very simple log4j2 XML configuration file using Console and File appender

log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See for a reference.

Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.

Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
        <Property name="filename">log/CelsiusConverter.log</Property>
        <Appender type="Console" name="Console">
            <Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
        <Appender type="Console" name="FLOW">
            <Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
        <Appender type="File" name="File" fileName="${filename}">
            <Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
        <Root level="debug">
            <AppenderRef ref="File" />
            <AppenderRef ref="Console" />
            <!-- Use FLOW to trace down exact method sending the msg -->
            <!-- <AppenderRef ref="FLOW" /> -->

In c# what does 'where T : class' mean?

That restricts T to reference types. You won't be able to put value types (structs and primitive types except string) there.

Why are you not able to declare a class as static in Java?

public class Outer {
   public static class Inner {}

... it can be declared static - as long as it is a member class.

From the JLS:

Member classes may be static, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes (§8.1.3).

and here:

The static keyword may modify the declaration of a member type C within the body of a non-inner class T. Its effect is to declare that C is not an inner class. Just as a static method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances.

A static keyword wouldn't make any sense for a top level class, just because a top level class has no enclosing type.

Use of var keyword in C#

I had the same concern when I started to use var keyword.
However I got used to it over time and not going to go back to explicit variable types. Visual Studio's compiler\intellisense are doing a very good job on making work with implicitly typed variables much easier.

I think that following proper naming conventions can help you to understand code much better then explicit typing.

It seems to be same sort of questions like "shoud I use prefixes in variable names?".
Stick with good variable names and let the compiler think on variable types.

Conditional HTML Attributes using Razor MVC3

You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...

<input type="text" id="@strElementID" class="@strCSSClass" />

If strCSSClass is null then the class attribute won't render at all.

SSSHHH...don't tell. :)

How to check if current thread is not main thread

You can try Thread.currentThread().isDaemon()

Test if a string contains a word in PHP?

//  Use this function and Pass Mixed string and what you want to search in mixed string.
//  For Example :
    $mixedStr = "hello world. This is john duvey";
    $searchStr= "john";

    if(strpos($mixedStr,$searchStr)) {
      echo "Your string here";
    }else {
      echo "String not here";

PHP: How to check if a date is today, yesterday or tomorrow

 $current = strtotime(date("Y-m-d"));
 $date    = strtotime("2014-09-05");

 $datediff = $date - $current;
 $difference = floor($datediff/(60*60*24));
    echo 'today';
 else if($difference > 1)
    echo 'Future Date';
 else if($difference > 0)
    echo 'tomorrow';
 else if($difference < -1)
    echo 'Long Back';
    echo 'yesterday';

Hibernate-sequence doesn't exist

This might be caused by HHH-10876 which got fixed so make sure you update to:

  • Hibernate ORM 5.2.1,
  • Hibernate ORM 5.1.1,
  • Hibernate ORM 5.0.11

Capture screenshot of active window?

KvanTTT's code worked great. I extended it a bit to allow a little more flexibility on save format, as well as the ability to save by hWnd, .NET Control/Form. You can get a bitmap or save to file, with a few options.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MosaiqPerformanceMonitor {
     public enum CaptureMode {
          Screen, Window

     public static class ScreenCapturer {
          private static extern IntPtr GetForegroundWindow();

          private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

          private struct Rect {
                public int Left;
                public int Top;
                public int Right;
                public int Bottom;

          [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
          public static extern IntPtr GetDesktopWindow();

          /// <summary> Capture Active Window, Desktop, Window or Control by hWnd or .NET Contro/Form and save it to a specified file.  </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          public static void CaptureAndSave(string filename, CaptureMode mode = CaptureMode.Window, ImageFormat format = null) {
                ImageSave(filename, format, Capture(mode));

          /// <summary> Capture a specific window (or control) and save it to a specified file.  </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="handle">hWnd (handle) of the window to capture</param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          public static void CaptureAndSave(string filename, IntPtr handle, ImageFormat format = null) {
                ImageSave(filename, format, Capture(handle));

          /// <summary> Capture a specific window (or control) and save it to a specified file.  </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="c">Object to capture</param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          public static void CaptureAndSave(string filename, Control c, ImageFormat format = null) {
                ImageSave(filename, format, Capture(c));
          /// <summary> Capture the active window (default) or the desktop and return it as a bitmap </summary>
          /// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
          public static Bitmap Capture(CaptureMode mode = CaptureMode.Window) {
                return Capture(mode == CaptureMode.Screen ? GetDesktopWindow() : GetForegroundWindow());

          /// <summary> Capture a .NET Control, Form, UserControl, etc. </summary>
          /// <param name="c">Object to capture</param>
          /// <returns> Bitmap of control's area </returns>
          public static Bitmap Capture(Control c) {
                return Capture(c.Handle);

          /// <summary> Capture a specific window and return it as a bitmap </summary>
          /// <param name="handle">hWnd (handle) of the window to capture</param>
          public static Bitmap Capture(IntPtr handle) {
                Rectangle bounds;
                var rect = new Rect();
                GetWindowRect(handle, ref rect);
                bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
                CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top);

                var result = new Bitmap(bounds.Width, bounds.Height);
                using (var g = Graphics.FromImage(result))
                     g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);

                return result;

          /// <summary> Position of the cursor relative to the start of the capture </summary>
          public static Point CursorPosition;

          /// <summary> Save an image to a specific file </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          /// <param name="image">Image to save.  Usually a BitMap, but can be any
          /// Image.</param>
          static void ImageSave(string filename, ImageFormat format, Image image) {
                format = format ?? ImageFormat.Png;
                if (!filename.Contains("."))
                     filename = filename.Trim() + "." + format.ToString().ToLower();

                if (!filename.Contains(@"\"))
                     filename = Path.Combine(Environment.GetEnvironmentVariable("TEMP") ?? @"C:\Temp", filename);

                filename = filename.Replace("%NOW%", DateTime.Now.ToString("[email protected]"));
                image.Save(filename, format);

Use dynamic (variable) string as regex pattern in JavaScript

I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:

    str = "1x";
    var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
    inv=inv.replace(regex, "");

Greyscale Background Css Images

Here you go:

<html xmlns="">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
     .grayscale {
         background: url(yourimagehere.jpg);
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");

    .nongrayscale {
        background: url(yourimagehere.jpg);
    <div class="nongrayscale">
        this is a non-grayscale of the bg image
    <div class="grayscale">
        this is a grayscale of the bg image

Tested it in FireFox, Chrome and IE. I've also attached an image to show my results of my implementation of this.Grayscale Background Image in DIV Sample

EDIT: Also, if you want the image to just toggle back and forth with jQuery, here's the page source for that...I've included the web link to jQuery and and image that's online so you should just be able to copy/paste to test it out:

<html xmlns="">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<script src=""></script>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
     .grayscale {
         background: url(;
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");

    .nongrayscale {
        background: url(;
    <script type="text/javascript">
        $(document).ready(function () {
            $("#image").mouseover(function () {
                $(".nongrayscale").removeClass().fadeTo(400,0.8).addClass("grayscale").fadeTo(400, 1);
            $("#image").mouseout(function () {
                $(".grayscale").removeClass().fadeTo(400, 0.8).addClass("nongrayscale").fadeTo(400, 1);
    <div id="image" class="nongrayscale">
        rollover this image to toggle grayscale

EDIT 2 (For IE10-11 Users): The solution above will not work with the changes Microsoft has made to the browser as of late, so here's an updated solution that will allow you to grayscale (or desaturate) your images.

    <filter xmlns="" id="desaturate">_x000D_
      <feColorMatrix type="saturate" values="0" />_x000D_
  <image xlink:href="" width="600" height="600" filter="url(#desaturate)" />_x000D_

CSS class for pointer cursor

You can assign "button" to role attribute of any html tag/element to make pointer over it. i.e

<html-element role="button" />