Programs & Examples On #Nservicebus distributor

HTTP Error 404 when running Tomcat from Eclipse

If you changed the location, using option 'Use custom location (does not modify Tomcat installation)' and the deployed directory is "wtpwebapps" then you'll have to:

  1. Swtich Location from [workspace metadata] to /Servers/Tomcat v...., click Apply, OK.
  2. Retart server and if you find 404 error message than the server is working, it just doesn't have the startup file at the web-server location you have chosen. If you traverse to that location, you'll find a bunch of directories that was created. One of which is wtpwebapps, under which there is ROOT. This is your web-server's directory. You will need to go back to installed Tomcat directory and copy the content of <tomcat's installed dir>/web-apps/ROOT to your wtpwebapps. Restart the webserver and you should see the tomcat default page.
  3. For Server Status, Manager Apps and Host Manager to work, you'll have to copy other subdirectories from <tomcat's installed dir>/webapps (ie. docs, examples, host-manager, manager) to your "webapps" (NOT the wtpwebapps) directory.
  4. Edit the '<your web directory>/conf/tomcat-users.xml' and enter something like:
  5.       <role rolename="manager-gui"/>
          <role rolename="manager-status"/>
          <role rolename="manager-jmx"/>
          <role rolename="manager-script"/>
          <role rolename="admin-gui"/>
          <role rolename="admin"/>
          <user username="admin" password="yourpassword" roles="admin, admin-gui, manager-gui"/>
  6. Then edit the '<your web directory>/conf/server.xml', add the attribute:
    into the <Resource/> key of the <GlobalNamingResources/> group.
  7. Restart the server and try to login with the configured credentials.
NOTE: if you change the server configuration, say if you like to compare the default configuration (use tomcat installation directory) and the 'new directory', when switching back to the 'new directory' this 'tomcat-users.xml' will be overwritten by the default file, so SAVE THE CONTENT OF THIS FILE somewhere before doing that, then copy it back. If you only give the the username "admin" role, you will be prompted of help messages. It says: you should not grant the admin-gui, or manager-gui role the 'manager-jmx' and 'manager-script' roles.

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I encountered the same issue when calling super.onCreate() at the end of my method. The reason: attachActivity() is called in onCreate() of FragmentActivity. When overriding onCreate() and, for example, creating tabs, the Tab manager will try to switch to a fragment while not having the activity attached to the FragmentManager.

Simple solution: Move the call to super.onCreate() to the head of the function body.

In general, it seems there are loads of reasons this issue may occur. This is just another one ...


Sort a list of numerical strings in ascending order

in python sorted works like you want with integers:

>>> sorted([10,3,2])
[2, 3, 10]

it looks like you have a problem because you are using strings:

>>> sorted(['10','3','2'])
['10', '2', '3']

(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int

>>> sorted(['10','3','2'], key=int)
['2', '3', '10']

which converts the values to integers during the sort (it is called as a function - int('10') returns the integer 10)

and as suggested in the comments, you can also sort the list itself, rather than generating a new one:

>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']

but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).

and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ... to the sql command:

select temperature from temperatures order by temperature;

Java Ordered Map


To keep Map< Integer , String > in an order sorted by key, use either of the two classes implementing the SortedMap/NavigableMap interfaces:

  • TreeMap
  • ConcurrentSkipListMap

If manipulating the map within a single thread, use the first, TreeMap. If manipulating across threads, use the second, ConcurrentSkipListMap.

For details, see the table below and the following discussion.


Here is a graphic table I made showing the features of the ten Map implementations bundled with Java 11.

The NavigableMap interface is what SortedMap should have been in the first place. The SortedMap logically should be removed but cannot be as some 3rd-party map implementations may be using interface.

As you can see in this table, only two classes implement the SortedMap/NavigableMap interfaces:

Both of these keep keys in sorted order, either by their natural order (using compareTo method of the Comparable( interface) or by a Comparator implementation you pass. The difference between these two classes is that the second one, ConcurrentSkipListMap, is thread-safe, highly concurrent.

See also the Iteration order column in the table below.

  • The LinkedHashMap class returns its entries by the order in which they were originally inserted.
  • EnumMap returns entries in the order by which the enum class of the key is defined. For example, a map of which employee is covering which day of the week (Map< DayOfWeek , Person >) uses the DayOfWeek enum class built into Java. That enum is defined with Monday first and Sunday last. So entries in an iterator will appear in that order.

The other six implementations make no promise about the order in which they report their entries.

Table of map implementations in Java 11, comparing their features

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);

Then later on in your actions you can simply

store.commit('authenticate', {

Is there any boolean type in Oracle databases?

error_flag  BOOLEAN := false;

error_flag := true;
--error_flag := 13;--expression is of wrong type

  IF error_flag THEN 

UPDATE table_a SET id= 8 WHERE id = 1;


Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

  1. Select columns A:H with A1 as the active cell.
  2. Open Home ? Styles ? Conditional Formatting ? New Rule.
  3. Choose Use a formula to determine which cells to format and supply one of the following formulas¹ in the Format values where this formula is true: text box.
    • To highlight the Account and Store Manager columns when one of the four dates is blank:
              =AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
    • To highlight the Account, Store Manager and blank date columns when one of the four dates is blank:
              =AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
  4. Click [Format] and select a cell Fill.
  5. Click [OK] to accept the formatting and then [OK] again to create the new rule. In both cases, the Applies to: will refer to =$A:$H.

Results should be similar to the following.

  Conditionally formatting if multiple cells are blank

¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. "").

How to add fonts to create-react-app based projects?

I was making mistakes like this.

@import ",300i,400,400i,600,600i,700,700i&amp;subset=cyrillic,cyrillic-ext,latin-ext";
@import "";

It works properly this way

@import url(,300i,400,400i,600,600i,700,700i&amp;subset=cyrillic,cyrillic-ext,latin-ext);
@import url(;

Autocompletion of @author in Intellij

For Intellij IDEA Community 2019.1 you will need to follow these steps :

File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */

JAX-WS client : what's the correct path to access the local WSDL?

Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.

After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.

Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!

YMMV, Andrew

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

I came across this when upgrading from 5.8 to 6.x.

I had str_slug() in config/cache.php and config/session.php.

I have changed it to Str::slug() and the error has disappeared.


AWS S3: how do I see how much disk space is using

The AWS CLI now supports the --query parameter which takes a JMESPath expressions.

This means you can sum the size values given by list-objects using sum(Contents[].Size) and count like length(Contents[]).

This can be be run using the official AWS CLI as below and was introduced in Feb 2014

 aws s3api list-objects --bucket BUCKETNAME --output json --query "[sum(Contents[].Size), length(Contents[])]"

Netbeans how to set command line arguments in Java

For passing arguments to Run Project command either you have to set the arguments in the Project properties Run panel

Android Canvas.drawText

Worked this out, turns out that is not the same as Color.BLACK. Changed the code to:

Paint paint = new Paint(); 

canvas.drawText("Some Text", 10, 25, paint); 

and it all works fine now!!

Count lines in large files

Let us assume:

  • Your file system is distributed
  • Your file system can easily fill the network connection to a single node
  • You access your files like normal files

then you really want to chop the files into parts, count parts in parallel on multiple nodes and sum up the results from there (this is basically @Chris White's idea).

Here is how you do that with GNU Parallel (version > 20161222). You need to list the nodes in ~/.parallel/my_cluster_hosts and you must have ssh access to all of them:

parwc() {
    # Usage:
    #   parwc -l file                                                                

    # Give one chunck per host                                                     
    chunks=$(cat ~/.parallel/my_cluster_hosts|wc -l)
    # Build commands that take a chunk each and do 'wc' on that                    
    # ("map")                                                                      
    parallel -j $chunks --block -1 --pipepart -a "$2" -vv --dryrun wc "$1" |
        # For each command                                                         
        #   log into a cluster host                                                
        #   cd to current working dir                                              
        #   execute the command                                                    
        parallel -j0 --slf my_cluster_hosts --wd . |
        # Sum up the number of lines                                               
        # ("reduce")                                                               
        perl -ne '$sum += $_; END { print $sum,"\n" }'

Use as:

parwc -l myfile
parwc -w myfile
parwc -c myfile

MySQL command line client for Windows

I have similar requirement where I need a MySQL client but not server (running in a virtual machine and don't want any additional overhead) and for me the easiest thing was to install MySQL community server taking typical installation options but NOT configure the server, so it never starts, never runs. Added C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin to system path environment variable and I'm able to use the MySQL command line client mssql.exe and mysqladmin.exe programs. - Add blank item at top of dropdownlist


at last

ddlProducer.Items.Insert(0, "");

how does multiplication differ for NumPy Matrix vs Array classes?

A pertinent quote from PEP 465 - A dedicated infix operator for matrix multiplication , as mentioned by @petr-viktorin, clarifies the problem the OP was getting at:

[...] numpy provides two different types with different __mul__ methods. For numpy.ndarray objects, * performs elementwise multiplication, and matrix multiplication must use a function call ( For numpy.matrix objects, * performs matrix multiplication, and elementwise multiplication requires function syntax. Writing code using numpy.ndarray works fine. Writing code using numpy.matrix also works fine. But trouble begins as soon as we try to integrate these two pieces of code together. Code that expects an ndarray and gets a matrix, or vice-versa, may crash or return incorrect results

The introduction of the @ infix operator should help to unify and simplify python matrix code.

Open a new tab on button click in AngularJS

Proper HTML way: just surround your button with anchor element and add attribute target="_blank". It is as simple as that:

<a ng-href="{{yourDynamicURL}}" target="_blank">
    <h1>Open me in new Tab</h1>

where you can set in the controller:

$scope.yourDynamicURL = '';

Group a list of objects by an attribute

Implement SQL GROUP BY Feature in Java using Comparator, comparator will compare your column data, and sort it. Basically if you keep sorted data that looks as grouped data, for example if you have same repeated column data then sort mechanism sort them keeping same data one side and then look for other data which is dissimilar data. This indirectly viewed as GROUPING of same data.

public class GroupByFeatureInJava {

    public static void main(String[] args) {
        ProductBean p1 = new ProductBean("P1", 20, new Date());
        ProductBean p2 = new ProductBean("P1", 30, new Date());
        ProductBean p3 = new ProductBean("P2", 20, new Date());
        ProductBean p4 = new ProductBean("P1", 20, new Date());
        ProductBean p5 = new ProductBean("P3", 60, new Date());
        ProductBean p6 = new ProductBean("P1", 20, new Date());

        List<ProductBean> list = new ArrayList<ProductBean>();

        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean);
        System.out.println("******** AFTER GROUP BY PRODUCT_ID ******");
        Collections.sort(list, new ProductBean().new CompareByProductID());
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean);

        System.out.println("******** AFTER GROUP BY PRICE ******");
        Collections.sort(list, new ProductBean().new CompareByProductPrice());
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean);

class ProductBean {
    String productId;
    int price;
    Date date;

    public String toString() {
        return "ProductBean [" + productId + " " + price + " " + date + "]";
    ProductBean() {
    ProductBean(String productId, int price, Date date) {
        this.productId = productId;
        this.price = price; = date;
    class CompareByProductID implements Comparator<ProductBean> {
        public int compare(ProductBean p1, ProductBean p2) {
            if (p1.productId.compareTo(p2.productId) > 0) {
                return 1;
            if (p1.productId.compareTo(p2.productId) < 0) {
                return -1;
            // at this point all a.b,c,d are equal... so return "equal"
            return 0;
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);

    class CompareByProductPrice implements Comparator<ProductBean> {
        public int compare(ProductBean p1, ProductBean p2) {
            // this mean the first column is tied in thee two rows
            if (p1.price > p2.price) {
                return 1;
            if (p1.price < p2.price) {
                return -1;
            return 0;
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);

    class CompareByCreateDate implements Comparator<ProductBean> {
        public int compare(ProductBean p1, ProductBean p2) {
            if ( {
                return 1;
            if ( {
                return -1;
            return 0;
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);

Output is here for the above ProductBean list is done GROUP BY criteria, here if you see the input data that is given list of ProductBean to Collections.sort(list, object of Comparator for your required column) This will sort based on your comparator implementation and you will be able to see the GROUPED data in below output. Hope this helps...

    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ******** AFTER GROUP BY PRODUCT_ID ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]

    ******** AFTER GROUP BY PRICE ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]

Flutter - Layout a Grid

A simple example loading images into the tiles.

import 'package:flutter/material.dart';

void main() {
  runApp( MyApp());

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return Container(

      color: Colors.white30,
      child: GridView.count(
          crossAxisCount: 4,
          childAspectRatio: 1.0,
          padding: const EdgeInsets.all(4.0),
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
          children: <String>[
          ].map((String url) {
            return GridTile(
                child:, fit: BoxFit.cover));

The Flutter Gallery app contains a real world example, which can be found here.

enter image description here

how to add script inside a php code?

One way to avoid accidentally including the same script twice is to implement a script management module in your templating system. The typical way to include a script is to use the SCRIPT tag in your HTML page.

  <script type="text/javascript" src="menu_1.0.17.js"></script>

An alternative in PHP would be to create a function called insertScript.

  <?php insertScript("menu.js") ?>

Add property to an array of objects

or use map> ({ ...obj, Active: 'false' }))

Edited to reflect comment by @adrianolsk to not mutate the original and instead return a new object for each.

Read the spec

How to dynamically add elements to String array?

You cant add add items in string array more than its size, i'll suggest you to use ArrayList you can add items dynamically at run time in arrayList if you feel any problem you can freely ask

Python copy files to a new directory and rename if file name already exists

Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.

movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
    for filename in files:
        # I use absolute path, case you want to move several dirs.
        old_name = os.path.join( os.path.abspath(root), filename )

        # Separate base from extension
        base, extension = os.path.splitext(filename)

        # Initial new name
        new_name = os.path.join(basedir, base, filename)

        # If folder basedir/base does not exist... You don't want to create it?
        if not os.path.exists(os.path.join(basedir, base)):
            print os.path.join(basedir,base), "not found" 
            continue    # Next filename
        elif not os.path.exists(new_name):  # folder exists, file does not
            shutil.copy(old_name, new_name)
        else:  # folder exists, file exists as well
            ii = 1
            while True:
                new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
                if not os.path.exists(new_name):
                   shutil.copy(old_name, new_name)
                   print "Copied", old_name, "as", new_name
                ii += 1

adding 1 day to a DATETIME format value

There is a more concise and intuitive way to add days to php date. Don't get me wrong, those php expressions are great, but you always have to google how to treat them. I miss auto-completion facility for that.

Here is how I like to handle those cases:

(new Future(
    new DateTimeFromISO8601String('2014-11-21T06:04:31.321987+00:00'),
    new OneDay()

For me, it's way more intuitive and autocompletion works out of the box. No need to google for the solution each time.

As a nice bonus, you don't have to worry about formatting the resulting value, it's already is ISO8601 format.

This is meringue library, there are more examples here.

How to change sender name (not email address) when using the linux mail command for autosending mail?

You can use the "-r" option to set the sender address:

mail -r [email protected] -s ...

In case you also want to include your real name in the from-field, you can use the following format

mail -r "[email protected] (My Name)" -s "My Subject" ...



Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("")

In C#:

System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("");

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

Sometime your code syntax has error, like you use " in ", it must be " ...'...." For help you quickly detect problems, you click Design button, vs try to render, and it will show the line of error

How can I use modulo operator (%) in JavaScript?

It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:

10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.

Apparently it is not the same as the modulo operator entirely.

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

I had the same problem and for some reason, even a git clean -f -d would not do it. Here is why: For some reason, if your file is ignored by Git (via a .gitignore entry, I assume), it still bothers about overwriting this with a later pull, but a clean will not remove it, unless you add -x.

AngularJS - How to use $routeParams in generating the templateUrl?

I was having a similar issue and used $stateParams instead of routeParam

Make sure that the controller has a parameterless public constructor error

If you are using UnityConfig.cs to resister your type's mappings like below.

public static void RegisterTypes(IUnityContainer container)
     container.RegisterType<IProductRepository, ProductRepository>();

You have to let the know **webApiConfig.cs** about Container

config.DependencyResolver = new Unity.AspNet.WebApi.UnityDependencyResolver(UnityConfig.Container);

PowerShell - Start-Process and Cmdline Switches

Using explicit parameters, it would be:

$msbuild = 'C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe'
start-Process -FilePath $msbuild -ArgumentList '/v:q','/nologo'

EDIT: quotes.

How to "set a breakpoint in malloc_error_break to debug"

In your screenshot, you didn't specify any module: try setting "libsystem_c.dylib"

enter image description here

I did that, and it works : breakpoint stops here (although the stacktrace often rise from some obscure system lib...)

Calculate age given the birth date in the format YYYYMMDD

That's the most elegant way for me:

const getAge = (birthDateString) => {_x000D_
  const today = new Date();_x000D_
  const birthDate = new Date(birthDateString);_x000D_
  const yearsDifference = today.getFullYear() - birthDate.getFullYear();_x000D_
  if (_x000D_
    today.getMonth() < birthDate.getMonth() ||_x000D_
    (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())_x000D_
  ) {_x000D_
    return yearsDifference - 1;_x000D_
  return yearsDifference;_x000D_

Manifest Merger failed with multiple errors in Android Studio

As a newbie to Android Studio, in my case, I had moved an existing project from Eclipse to Android Studio and found that there was a duplicate definition of an activity within my Manifest.xml that hadn't been picked up by Eclipse was shown as a Gradle error.

I found this by going to the Gradle Console (bottom right of the screen).

Python: How to get stdout after running os.system?

I had to use os.system, since subprocess was giving me a memory error for larger tasks. Reference for this problem here. So, in order to get the output of the os.system command I used this workaround:

import os

batcmd = 'dir'
result_code = os.system(batcmd + ' > output.txt')
if os.path.exists('output.txt'):
    fp = open('output.txt', "r")
    output =

What is the difference between MacVim and regular Vim?

unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

CSS: How can I set image size relative to parent height?

Change your code:

a.image_container img {
    width: 100%;

To this:

a.image_container img {
    width: auto; // to maintain aspect ratio. You can use 100% if you don't care about that
    height: 100%;

package javax.mail and javax.mail.internet do not exist

Had the same issue. Obviously these .jars were included with Java <= v8.x out of the box, but are not anymore. Thus one has to separately download them and place them in the appropriate classpath as highlighted by several folks above. I understand that the new Java is modularized and thus potentially more light-weight (which is certainly a good thing, since the old setup was a monster). On the other hand this - as we can see - breaks lots of old build setups. Since the time to fix these isn't chargeable to Oracle I guess this made their decision easy...

What does a question mark represent in SQL queries?

The ? is an unnamed parameter which can be filled in by a program running the query to avoid SQL injection.

Is it safe to store a JWT in localStorage with ReactJS?

I know this is an old question but according what @mikejones1477 said, modern front end libraries and frameworks escape the text giving you protection against XSS. The reason why cookies are not a secure method using credentials is that cookies doesn't prevent CSRF when localStorage does (also remember that cookies are accessible by javascript too, so XSS isn't the big problem here), this answer resume why.

The reason storing an authentication token in local storage and manually adding it to each request protects against CSRF is that key word: manual. Since the browser is not automatically sending that auth token, if I visit and it manages to send a POST, it will not be able to send my authn token, so the request is ignored.

Of course httpOnly is the holy grail but you can't access from reactjs or any js framework beside you still have CSRF vulnerability. My recommendation would be localstorage or if you want to use cookies make sure implemeting some solution to your CSRF problem like django does.

Regarding with the CDN's make sure you're not using some weird CDN, for example CDN like google or bootstrap provide, are maintained by the community and doesn't contain malicious code, if you are not sure, you're free to review.

ASP.NET Bundles how to disable minification

Combine several answers, this works for me in ASP.NET MVC 4.

        bundles.Add(new ScriptBundle("~/Scripts/Common/js")

        bundles.Add(new StyleBundle("~/Content/appLayoutStyles")

        bundles.Add(new StyleBundle("~/Content/css/App/FunGrapherStyles")

        foreach (var bundle in BundleTable.Bundles)

How to check if a String is numeric in Java

If you want to do the check using a regex you should create a final static Pattern object, that way the regex only needs to be compiled once. Compiling the regex takes about as long as performing the match so by taking this precaution you'll cut the execution time of the method in half.

final static Pattern NUMBER_PATTERN = Pattern.compile("[+-]?\\d*\\.?\\d+");

static boolean isNumber(String input) {
    Matcher m = NUMBER_PATTERN.matcher(input);
    return m.matches();

I'm assuming a number is a string with nothing but decimal digits in it, possibly a + or - sign at the start and at most one decimal point (not at the end) and no other characters (including commas, spaces, numbers in other counting systems, Roman numerals, hieroglyphs).

This solution is succinct and pretty fast but you can shave a couple of milliseconds per million invocations by doing it like this

static boolean isNumber(String s) {
    final int len = s.length();
    if (len == 0) {
        return false;
    int dotCount = 0;
    for (int i = 0; i < len; i++) {
        char c = s.charAt(i);
        if (c < '0' || c > '9') {
            if (i == len - 1) {//last character must be digit
                return false;
            } else if (c == '.') {
                if (++dotCount > 1) {
                    return false;
            } else if (i != 0 || c != '+' && c != '-') {//+ or - allowed at start
                return false;

    return true;

How to execute a stored procedure inside a select query

As long as you're not doing any INSERT or UPDATE statements in your stored procedure, you will probably want to make it a function.

Stored procedures are for executing by an outside program, or on a timed interval.

The answers here will explain it better than I can:

Function vs. Stored Procedure in SQL Server

Why is my Spring @Autowired field null?

What hasn't been mentioned here is described in this article in the paragraph "Order of execution".

After "learning" that I had to annotate a class with @Component or the derivatives @Service or @Repository (I guess there are more), to autowire other components inside them, it struck me that these other components still were null inside the constructor of the parent component.

Using @PostConstruct solves that:

public class Application {
    @Autowired MyComponent comp;


public class MyComponent {
    @Autowired ComponentDAO dao;

    public MyComponent() {
        // dao is null here

    public void init() {
        // dao is initialized here

What is the difference between Task.Run() and Task.Factory.StartNew()

According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:

I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :) StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.

Here are the actual reasons:

  1. Does not understand async delegates. This is actually the same as point 1 in the reasons why you would want to use StartNew. The problem is that when you pass an async delegate to StartNew, it’s natural to assume that the returned task represents that delegate. However, since StartNew does not understand async delegates, what that task actually represents is just the beginning of that delegate. This is one of the first pitfalls that coders encounter when using StartNew in async code.
  2. Confusing default scheduler. OK, trick question time: in the code below, what thread does the method “A” run on?

private static void A() { }

Well, you know it’s a trick question, eh? If you answered “a thread pool thread”, I’m sorry, but that’s not correct. “A” will run on whatever TaskScheduler is currently executing!

So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.

In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().

For details, please see

Replace characters from a column of a data frame R

Use gsub:

data1$c <- gsub('_', '-', data1$c)

            a b   c
1  0.34597094 a A-B
2  0.92791908 b A-B
3  0.30168772 c A-B
4  0.46692738 d A-B
5  0.86853784 e A-C
6  0.11447618 f A-C
7  0.36508645 g A-C
8  0.09658292 h A-C
9  0.71661842 i A-C
10 0.20064575 j A-C

How to compare strings

You need to use strcmp.

if (strcmp(string,"add") == 0){

Python Pandas counting and summing specific conditions

I usually use numpy sum over the logical condition column:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)

This seems to me slightly shorter than the solution presented above

Negate if condition in bash script

You can use unequal comparison -ne instead of -eq:

wget -q --tries=10 --timeout=20 --spider
if [[ $? -ne 0 ]]; then
    echo "Sorry you are Offline"
    exit 1

Why does make think the target is up to date?

Maybe you have a file/directory named test in the directory. If this directory exists, and has no dependencies that are more recent, then this target is not rebuild.

To force rebuild on these kind of not-file-related targets, you should make them phony as follows:

.PHONY: all test clean

Note that you can declare all of your phony targets there.

A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request.

Vue v-on:click does not work on component

Native events of components aren't directly accessible from parent elements. Instead you should try v-on:click.native="testFunction", or you can emit an event from Test component as well. Like v-on:click="$emit('click')".

Cannot find Microsoft.Office.Interop Visual Studio

Just doing like @Kjartan.

Steps are as follows:

  1. Right click your C# project name in Visual Studio's "Solution Explorer";

  2. Then, select "add -> Reference -> COM -> Type Libraries " in order;

  3. Find the "Microsoft Office 16.0 Object Library", and add it to reference (Note: the version number may vary with the OFFICE you have installed);

  4. After doing this, you will see "Microsoft.Office.Interop.Word" under the "Reference" item in your project.

what do these symbolic strings mean: %02d %01d?

The article is about the class of printf functions, in several languages, from the 50s to this day.

MongoDB: update every document on one field

Regardless of the version, for your example, the <update> is:

{  $set: { lastLookedAt: / 1000 }  }

However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB client:

$version >= 3.2: {}, <update> )
  • {} is the condition (the empty condition matches any document)

3.2 > $version >= 2.2: {}, <update>, { multi: true } )
  • {} is the condition (the empty condition matches any document)
  • {multi: true} is the "update multiple documents" option

$version < 2.2: {}, <update>, false, true )
  • {} is the condition (the empty condition matches any document)
  • false is for the "upsert" parameter
  • true is for the "multi" parameter (update multiple records)

In Java, how can I determine if a char array contains a particular character?

The following snippets test for the "not contains" condition, as exemplified in the sample pseudocode in the question. For a direct solution with explicit looping, do this:

boolean contains = false;
for (char c : charArray) {
    if (c == 'q') {
        contains = true;
if (!contains) {
    // do something

Another alternative, using the fact that String provides a contains() method:

if (!(new String(charArray).contains("q"))) {
    // do something

Yet another option, this time using indexOf():

if (new String(charArray).indexOf('q') == -1) {
    // do something

How can I make my website's background transparent without making the content (images & text) transparent too?

Just include following in your code

<body background="C:\Users\Desktop\images.jpg"> 

if you want to specify the size and opacity you can use following

<p><img style="opacity:0.9;" src="C:\Users\Desktop\images.jpg" width="300" height="231" alt="Image" /></p> 

Convert an image (selected by path) to base64 string

The following piece of code works for me:

string image_path="physical path of your image";
byte[] byes_array = System.IO.File.ReadAllBytes(Server.MapPath(image_path));
string base64String = Convert.ToBase64String(byes_array);

Create a new txt file using VB.NET

You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:

Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
End If

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

HTML forms support GET and POST. (HTML5 at one point added PUT/DELETE, but those were dropped.)

XMLHttpRequest supports every method, including CHICKEN, though some method names are matched against case-insensitively (methods are case-sensitive per HTTP) and some method names are not supported at all for security reasons (e.g. CONNECT).

Browsers are slowly converging on the rules specified by XMLHttpRequest, but as the other comment pointed out there are still some differences.

JavaScript onclick redirect

Remove 'javascript:' from your code and it should work.

Do you happen to use FireFox? I have learned from someone else that FireFox no longer accepts the 'javascript:' string. However, for the life of me, I cannot find the original source (though I believe it was somewhere in FF update notes).

execute function after complete page load

call a function after complete page load set time out

setTimeout(function() {_x000D_
   var val = $('.GridStyle tr:nth-child(2) td:nth-child(4)').text();_x000D_
 for(var i, j = 0; i = ddl2.options[j]; j++) {_x000D_
  if(i.text == val) {      _x000D_
   ddl2.selectedIndex = i.index;_x000D_
 } _x000D_
}, 1000);

When to encode space to plus (+) or %20?

+ means a space only in application/x-www-form-urlencoded content, such as the query part of a URL:

In this URL, the parameter name is query name with a space and the value is query value with a space, but the folder name in the path is literally foo+bar, not foo bar.

%20 is a valid way to encode a space in either of these contexts. So if you need to URL-encode a string for inclusion in part of a URL, it is always safe to replace spaces with %20 and pluses with %2B. This is what eg. encodeURIComponent() does in JavaScript. Unfortunately it's not what urlencode does in PHP (rawurlencode is safer).

See Also HTML 4.01 Specification application/x-www-form-urlencoded

Why does pycharm propose to change method to static

I can imagine following advantages of having a class method defined as static one:

  • you can call the method just using class name, no need to instantiate it.

remaining advantages are probably marginal if present at all:

  • might run a bit faster
  • save a bit of memory

Insert a new row into DataTable

@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));

dc = new DataColumn("col2", typeof(String));

dc = new DataColumn("col3", typeof(String));

dc = new DataColumn("col4", typeof(String));

DataRow dr = dt.NewRow();

dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";

dt.Rows.Add(dr);//this will add the row at the end of the datatable
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);

How to leave a message for a user

Although GitHub removed the private messaging feature, there's still an alternative.

GitHub host git repositories. If the user you're willing to communicate with has ever committed some code, there are good chances you may reach your goal. Indeed, within each commit is stored some information about the author of the change or the one who accepted it.

Provided you're really dying to exchange with user user_test

  • Display the public activity page of the user:
  • Search for an event stating "user_test pushed to [branch] at [repository]". There are usually good chances, they may have pushed one of his own commits. Ensure this is the case by clicking on the "View comparison..." link and make sure the user is listed as one of the committers.
  • Clone on your local machine the repository they pushed to: git clone
  • Checkout the branch they pushed to: git checkout [branch]
  • Display the latest commits: git log -50

As a committer/author, an email should be displayed along with the commit data.

Note: Every warning related to unsolicited email should apply there. Do not spam.

How do I remove a single breakpoint with GDB?

You can delete all breakpoints using

del <start_breakpoint_num> - <end_breakpoint_num>

To view the start_breakpoint_num and end_breakpoint_num use:

info break

Tool to Unminify / Decompress JavaScript

I'm not sure if you need source code. There is a free online JavaScript formatter at

Label word wrapping

Ironically, turning off AutoSize by setting it to false allowed me to get the label control dimensions to size it both vertically and horizontally which effectively allows word-wrapping to occur.

What is the LD_PRELOAD trick?

it's easy to export to env:

$ export LD_PRELOAD=/path/
$ ./mybin

to disable :

$ export LD_PRELOAD=

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

You can't remove hidden without also removing system.

You want:

cd mydir
attrib -H -S /D /S

That will remove the hidden and system attributes from all the files/folders inside of your current directory.

How can I pretty-print JSON using node.js?

JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces). Node can write to your filesystem with fs. Example:

var fs = require('fs');

fs.writeFile('test.json', JSON.stringify({ a:1, b:2, c:3 }, null, 4));
/* test.json:
     "a": 1,
     "b": 2,
     "c": 3,

See the JSON.stringify() docs at MDN, Node fs docs

How to open a web page from my application?

Microsoft explains it in the KB305703 article on How to start the default Internet browser programmatically by using Visual C#.

Don't forget to check the Troubleshooting section.

Is there a way to cache GitHub credentials for pushing commits?


You can create your own personal API token (OAuth) and use it the same way as you would use your normal credentials (at: /settings/tokens). For example:

git remote add fork https://[email protected]/foo/bar
git push fork


Another method is to configure your user/password in ~/.netrc (_netrc on Windows), e.g.

password PASSWORD

For HTTPS, add the extra line:

protocol https

A credential helper

To cache your GitHub password in Git when using HTTPS, you can use a credential helper to tell Git to remember your GitHub username and password every time it talks to GitHub.

  • Mac: git config --global credential.helper osxkeychain (osxkeychain helper is required),
  • Windows: git config --global credential.helper wincred
  • Linux and other: git config --global credential.helper cache


Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:

with open(filename, "w") as f:

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.

In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:

How to hide action bar before activity is created, and then show it again?

If you use one Activity included a splash screen, then you can do this if you use SherlockActionBar


After the splash screen you can show it again with ...


It should be the same with native ActionBar of Android.

How to disable action bar permanently

With the Android Studio default generated Activity superclass is ActionBarActivity and then, none of solution in other responses works. To solve just change superclass:

public class xxxActivity extends ActionBarActivity{


public class xxxActivity extends Activity {

What is a software framework?

A simple explanation is: A framework is a scaffold that you can you build applications around.

A framework generally provides some base functionality which you can use and extend to make more complex applications from, there are frameworks for all sorts of things. Microsofts MVC framework is a good example of this. It provides everything you need to get off the ground building website using the MVC pattern, it handles web requests, routes and the like. All you have to do is implement "Controllers" and provide "Views" which are two constructs defined by the MVC framework. The MVC framework then handles calling your controllers and rendering your views.

Perhaps not the best wording but I hope it helps

Display special characters when using print statement

Use repr:

a = "Hello\tWorld\nHello World"
# 'Hello\tWorld\nHello World'

Note you do not get \s for a space. I hope that was a typo...?

But if you really do want \s for spaces, you could do this:

print(repr(a).replace(' ',r'\s'))

Get value (String) of ArrayList<ArrayList<String>>(); in Java


You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.

Notice both collection.Add(listOfSomething); save two references to the same arraylist object.

You need to create two different instances for two elements:

ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();

ArrayList<String> listOfSomething1 = new ArrayList<String>();

ArrayList<String> listOfSomething2 = new ArrayList<String>();


Convert date to another timezone in JavaScript

You can try this also for convert date timezone to India:

var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
var indainDateObj = new Date(indianTimeZoneVal);
indainDateObj.setHours(indainDateObj.getHours() + 5);
indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);

How to create war files

I've always just selected Export from Eclipse. It builds the war file and includes all necessary files. Providing you created the project as a web project that's all you'll need to do. Eclipse makes it very simple to do.

Count number of rows within each group

Considering @Ben answer, R would throw an error if df1 does not contain x column. But it can be solved elegantly with paste:

aggregate(paste(Year, Month) ~ Year + Month, data = df1, FUN = NROW)

Similarly, it can be generalized if more than two variables are used in grouping:

aggregate(paste(Year, Month, Day) ~ Year + Month + Day, data = df1, FUN = NROW)

Set date input field's max date to today

JavaScript only simple solution

datePickerId.max = new Date().toISOString().split("T")[0];
<input type="date" id="datePickerId" />

adding a datatable in a dataset

you have to set the tableName you want to your dtimage that is for instance



it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage

Removing rounded corners from a <select> element in Chrome/Webkit

Some good solutions here but this one doesn't need SVG, preserves the border via outline and sets it flush on the button.

select {_x000D_
  height: 20px;_x000D_
  -webkit-border-radius: 0;_x000D_
  border: 0;_x000D_
  outline: 1px solid #ccc;_x000D_
  outline-offset: -1px;_x000D_

calculate the mean for each column of a matrix in R

my.mean <- unlist(lapply(mtcars, mean)); my.mean

   mpg        cyl       disp         hp       drat         wt       qsec         vs 
 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750   0.437500 
        am       gear       carb 
  0.406250   3.687500   2.812500 

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

Check here:

NEW Version of MYSQL does it this way.

In the new my-sql if the password is left empty while installing then it is based on the auth_socket plugin.

The correct way is to login to my-sql with sudo privilege.

$ sudo mysql -u root -p

And then updating the password using:

$ ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new-password';

Once this is done stop and start the mysql server.

$  sudo service mysql stop
$  sudo service mysql start

For complete details you can refer to this link.

Do comment for any doubt.

Execution sequence of Group By, Having and Where clause in SQL Server?

This is the SQL Order of execution of a Query,

enter image description here

You can check order of execution with examples from this article.

For you question below lines might be helpful and directly got from this article.

  1. GROUP BY --> The remaining rows after the WHERE constraints are applied are then grouped based on common values in the column specified in the GROUP BY clause. As a result of the grouping, there will only be as many rows as there are unique values in that column. Implicitly, this means that you should only need to use this when you have aggregate functions in your query.
  1. HAVING --> If the query has a GROUP BY clause, then the constraints in the HAVING clause are then applied to the grouped rows, discard the grouped rows that don't satisfy the constraint. Like the WHERE clause, aliases are also not accessible from this step in most databases.


trying to animate a constraint in swift

It's very important to point out that view.layoutIfNeeded() applies to the view subviews only.

Therefore to animate the view constraint, it is important to call it on the view-to-animate superview as follows:

    topConstraint.constant = heightShift

    UIView.animate(withDuration: 0.3) {

        // request layout on the *superview*

An example for a simple layout as follows:

class MyClass {

    /// Container view
    let container = UIView()
        /// View attached to container
        let view = UIView()

    /// Top constraint to animate
    var topConstraint = NSLayoutConstraint()

    /// Create the UI hierarchy and constraints
    func createUI() {

        // Create the top constraint
        topConstraint = view.topAnchor.constraint(equalTo: container.topAnchor, constant: 0)

        view.translatesAutoresizingMaskIntoConstraints = false

        // Activate constaint(s)

    /// Update view constraint with animation
    func updateConstraint(heightShift: CGFloat) {
        topConstraint.constant = heightShift

        UIView.animate(withDuration: 0.3) {

            // request layout on the *superview*

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

stop service in android

This code works for me: check this link
This is my code when i stop and start service in activity

  Log.d(TAG, "onClick: starting srvice");
  startService(new Intent(this, MyService.class));
  Log.d(TAG, "onClick: stopping srvice");
  stopService(new Intent(this, MyService.class));

And in service class:

public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

    player = MediaPlayer.create(this, R.raw.braincandy);
    player.setLooping(false); // Set looping

public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");


Inserting data into a temporary table

My way of Insert in SQL Server. Also I usually check if a temporary table exists.

IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP Table #MyTable

SELECT b.Val as 'bVals'
  INTO #MyTable
FROM OtherTable as b

How to define partitioning of DataFrame?

In Spark < 1.6 If you create a HiveContext, not the plain old SqlContext you can use the HiveQL DISTRIBUTE BY colX... (ensures each of N reducers gets non-overlapping ranges of x) & CLUSTER BY colX... (shortcut for Distribute By and Sort By) for example;

hiveCtx.sql("select * from partitionMe DISTRIBUTE BY accountId SORT BY accountId, date")

Not sure how this fits in with Spark DF api. These keywords aren't supported in the normal SqlContext (note you dont need to have a hive meta store to use the HiveContext)

EDIT: Spark 1.6+ now has this in the native DataFrame API

Updating Python on Mac

On a mac use the following in the terminal to update python if you have anaconda:

conda update python

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

Inserting multiple rows in a single SQL query?

In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.

For example:

  ( Column1, Column2, Column3 )
  ('John', 123, 'Lloyds Office'), 
  ('Jane', 124, 'Lloyds Office'), 
  ('Billy', 125, 'London Office'),
  ('Miranda', 126, 'Bristol Office');

Eclipse CDT: Symbol 'cout' could not be resolved

You guys are looking under the wrong section. I realized the difference when I installed in Linux after recently getting frustrated with Windows and the difference was immediately apparent.

In the new setup I have an includes folder in a projected that I created out of existing source. I can expand this and see a ton of includes; however, I cannot add to them. This lead me to a hunt for where these files were being listed.

They're listed under the Project Properties > C/C++ General > Preprocessor Includes > GNU C++ CDT GCC Built-in Compiler Settings [Shared] Under that is a ton of includes.

These settings are set by the toolchain you've selected.

Copy values from one column to another in the same table

Short answer for the code in question is:

UPDATE `table` SET test=number

Here table is the table name and it's surrounded by grave accent (aka back-ticks `) as this is MySQL convention to escape keywords (and TABLE is a keyword in that case).

BEWARE, that this is pretty dangerous query which will wipe everything in column test in every row of your table replacing it by the number (regardless of it's value)

It is more common to use WHERE clause to limit your query to only specific set of rows:

UPDATE `products` SET `in_stock` = true WHERE `supplier_id` = 10

How to read html from a url in python 3

import requests

url = requests.get("")
htmltext = url.text

This will work similar to urllib.urlopen.

How do I get the value of text input field using JavaScript?

Just try this ..

function handleValueChange() {
    var y = document.getElementById('textbox_id').value;
    var x = document.getElementById('result');
    x.innerHTML = y;

function changeTextarea() {
  var a = document.getElementById('text-area').value;
  var b = document.getElementById('text-area-result');
  b.innerHTML = a;
input {
  padding: 5px;

p {
  white-space: pre;
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>

<textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea>
<p id="text-area-result"></p>

How do you determine a processing time in Python?

You can implement two tic() and tac() functions, where tic() captures the time which it is called, and tac() prints the time difference since tic() was called. Here is a short implementation:

import time

_start_time = time.time()

def tic():
    global _start_time 
    _start_time = time.time()

def tac():
    t_sec = round(time.time() - _start_time)
    (t_min, t_sec) = divmod(t_sec,60)
    (t_hour,t_min) = divmod(t_min,60) 
    print('Time passed: {}hour:{}min:{}sec'.format(t_hour,t_min,t_sec))

Now in your code you can use it as:


and it will, for example, output:

Time passed: 0hour:7min:26sec

See also:

Understanding ibeacon distancing

The distance estimate provided by iOS is based on the ratio of the beacon signal strength (rssi) over the calibrated transmitter power (txPower). The txPower is the known measured signal strength in rssi at 1 meter away. Each beacon must be calibrated with this txPower value to allow accurate distance estimates.

While the distance estimates are useful, they are not perfect, and require that you control for other variables. Be sure you read up on the complexities and limitations before misusing this.

When we were building the Android iBeacon library, we had to come up with our own independent algorithm because the iOS CoreLocation source code is not available. We measured a bunch of rssi measurements at known distances, then did a best fit curve to match our data points. The algorithm we came up with is shown below as Java code.

Note that the term "accuracy" here is iOS speak for distance in meters. This formula isn't perfect, but it roughly approximates what iOS does.

protected static double calculateAccuracy(int txPower, double rssi) {
  if (rssi == 0) {
    return -1.0; // if we cannot determine accuracy, return -1.

  double ratio = rssi*1.0/txPower;
  if (ratio < 1.0) {
    return Math.pow(ratio,10);
  else {
    double accuracy =  (0.89976)*Math.pow(ratio,7.7095) + 0.111;    
    return accuracy;

Note: The values 0.89976, 7.7095 and 0.111 are the three constants calculated when solving for a best fit curve to our measured data points. YMMV

How to start working with GTest and CMake

You can get the best of both worlds. It is possible to use ExternalProject to download the gtest source and then use add_subdirectory() to add it to your build. This has the following advantages:

  • gtest is built as part of your main build, so it uses the same compiler flags, etc. and hence avoids problems like the ones described in the question.
  • There's no need to add the gtest sources to your own source tree.

Used in the normal way, ExternalProject won't do the download and unpacking at configure time (i.e. when CMake is run), but you can get it to do so with just a little bit of work. I've written a blog post on how to do this which also includes a generalised implementation which works for any external project which uses CMake as its build system, not just gtest. You can find them here:

Update: This approach is now also part of the googletest documentation.

pandas groupby sort within groups

Here's other example of taking top 3 on sorted order, and sorting within the groups:

In [43]: import pandas as pd                                                                                                                                                       

In [44]:  df = pd.DataFrame({"name":["Foo", "Foo", "Baar", "Foo", "Baar", "Foo", "Baar", "Baar"], "count_1":[5,10,12,15,20,25,30,35], "count_2" :[100,150,100,25,250,300,400,500]})

In [45]: df                                                                                                                                                                        
   count_1  count_2  name
0        5      100   Foo
1       10      150   Foo
2       12      100  Baar
3       15       25   Foo
4       20      250  Baar
5       25      300   Foo
6       30      400  Baar
7       35      500  Baar

### Top 3 on sorted order:
In [46]: df.groupby(["name"])["count_1"].nlargest(3)                                                                                                                               
Baar  7    35
      6    30
      4    20
Foo   5    25
      3    15
      1    10
dtype: int64

### Sorting within groups based on column "count_1":
In [48]: df.groupby(["name"]).apply(lambda x: x.sort_values(["count_1"], ascending = False)).reset_index(drop=True)
   count_1  count_2  name
0       35      500  Baar
1       30      400  Baar
2       20      250  Baar
3       12      100  Baar
4       25      300   Foo
5       15       25   Foo
6       10      150   Foo
7        5      100   Foo

How do I edit SSIS package files?

Current for 2016 link is

SQL Server Data Tools in Visual Studio 2015 is a modern development tool that you can download for free to build SQL Server relational databases, Azure SQL databases, Integration Services packages, Analysis Services data models, and Reporting Services reports. With SSDT, you can design and deploy any SQL Server content type with the same ease as you would develop an application in Visual Studio. This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016.

Note that you don't need to have Visual Studio pre-installed. SSDT will install required components of VS, if it is not installed on your machine.

This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016

Previously included in SQL Server standalone Business Intelligence Studio is not available any more and in last years replaced by SQL Server Data Tools (SSDT) for Visual Studio. See answer

How to capitalize the first character of each word in a string

I decided to add one more solution for capitalizing words in a string:

  • words are defined here as adjacent letter-or-digit characters;
  • surrogate pairs are provided as well;
  • the code has been optimized for performance; and
  • it is still compact.


public static String capitalize(String string) {
  final int sl = string.length();
  final StringBuilder sb = new StringBuilder(sl);
  boolean lod = false;
  for(int s = 0; s < sl; s++) {
    final int cp = string.codePointAt(s);
    sb.appendCodePoint(lod ? Character.toLowerCase(cp) : Character.toUpperCase(cp));
    lod = Character.isLetterOrDigit(cp);
    if(!Character.isBmpCodePoint(cp)) s++;
  return sb.toString();

Example call:

System.out.println(capitalize("An à la carte StRiNg. Surrogate pairs: ."));


An À La Carte String. Surrogate Pairs: .

Why should I use var instead of a type?

As the others have said, there is no difference in the compiled code (IL) when you use either of the following:

var x1 = new object();
object x2 = new object;

I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?

Consider the following and you'll get what I mean:

KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

It's way easier to read this instead:

var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

How to change background and text colors in Sublime Text 3

For your own theme package find and edit it.

Path: Preferences -> Browse Packages -> Theme - default


What are the lesser known but useful data structures?

I like treaps - for the simple, yet effective idea of superimposing a heap structure with random priority over a binary search tree in order to balance it.

How to Change color of Button in Android when Clicked?

hai the most easiest way is this:

add this code to

public void start(View view) {


public void stop(View view) {

and then in your activity main

    <button android:id="@+id/start" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="start" android:text="Click">

</button><button android:id="@+id/stop" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="stop" android:text="Click">

or follow along this tutorial

How do I run msbuild from the command line using Windows SDK 7.1?

For Visual Studio 2019 (Preview, at least) it is now in:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\Bin\MSBuild.exe

I imagine the process will be similar for the official 2019 release.

GDB: break if variable equal value

in addition to a watchpoint nested inside a breakpoint you can also set a single breakpoint on the 'filename:line_number' and use a condition. I find it sometimes easier.

(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c

Breakpoint 2, main () at iter.c:6
6           printf("%d\n", i);

If like me you get tired of line numbers changing, you can add a label then set the breakpoint on the label like so:

#include <stdio.h>
     int i = 0;
     for(i=0;i<7;++i) {
        printf("%d\n", i);
     return 0;

(gdb) break main:looping if i == 5

How to Get a Layout Inflater Given a Context?

You can also use this code to get LayoutInflater:

LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)

How to hide underbar in EditText

Set background to null

android:background="@null" in your xml 

How to use Monitor (DDMS) tool to debug application

As far as I know, currently (Android Studio 2.3) there is no way to do this.

As per Android Studio documentation:

"Note: Only one debugger can be connected to your device at a time."

When you attempt to connect Android Device Monitor it disconnects Android Studio's debug session and vice versa, when you attempt to connect Android Studio's debugger, it disconnects Android Device Monitor.

Fortunately the new version of Android Studio (3.0) will feature a Device File Explorer that will allow you to pull files from within Android Studio without the need to open the Android Device Monitor which should resolve the problem.

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

I was facing the same issue.The dtypes of y_test and y_pred were different. Make sure that the dtypes are same for both. The dtypes of y_test and y_pred were different

Implicit function declarations in C

An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.

It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.

Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.

Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.

CSS @media print issues with background-color;

Tested and Working over Chrome, Firefox, Opera and Edge by 2016/10. Should work on any browser and should always look as expected.

Ok, I did a little cross-browser experiment for printing background colors. Just copy, paste & enjoy!

Here it is a full printable HTML page for bootstrap:

<!DOCTYPE html>

<link rel="stylesheet" href="">
<style type="text/css">

    /* Both z-index are resolving recursive element containment */
    [background-color] {
        z-index: 0;
        position: relative;
        -webkit-print-color-adjust: exact !important;

    [background-color] canvas {
        display: block;
        z-index: -1;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;


<!-- CONTENT -->

    <!-- PRINT ROW BLOCK -->
    <div class="container">

    <div class="row">
        <div class="col-xs-6">
            <div background-color="#A400C1">
                Hey... this works !
                <div background-color="#0068C1">
                    Ohh... this works recursive too !!
                    <div background-color="green" style="width: 80px; height: 60px">
                        Any size !!

        <div class="col-xs-6">
            <div background-color="#FFCB83" style="height: 200px">
                Some content...


    var containers = document.querySelectorAll("[background-color]");

    for (i = 0; i < containers.length; i++)
        // Element
        var container = containers[i];
        container.insertAdjacentHTML('beforeend', '<canvas id="canvas-' + i + '"></canvas>');

        // Color
        var color = container.getAttribute("background-color"); = color;

        // Inner Canvas
        var canvas = document.getElementById("canvas-" + i);
        canvas.width = container.offsetWidth;
        canvas.height = container.offsetHeight;
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = color;
        ctx.fillRect(0, 0, canvas.width, canvas.height);




What is phtml, and when should I use a .phtml extension rather than .php?

To give an example to what Alex said, if you're using Magento, for example, .phtml files are only to be found in the /design area as template files, and contain both HTML and PHP lines. Meanwhile the PHP files are pure code and don't have any lines of HTML in them.

How to download python from command-line?

Well if you are getting into a linux machine you can use the package manager of that linux distro.

If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)

You could use yum in fedora and do the same.

if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from and install it

How to include static library in makefile


LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

Exception.Message vs Exception.ToString()

Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.

c# datagridview doubleclick on row with FullRowSelect

you can do this by : CellDoubleClick Event this is code.

private void datagridview1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)

How to serialize Joda DateTime with Jackson JSON processor?

I'm using Java 8 and this worked for me.

Add the dependency on pom.xml


and add JodaModule on your ObjectMapper

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

How to use Git for Unity3D source control?

What is GIT?

Git is a free and open source distributed version control system (SCM) developed by Linus Torvalds in 2005 ( Linux OS founder). It is created to control everything rom small to large projects with speed and efficiency. Leading companies like Google, Facebook, Microsoft uses GIT everyday.

If you want to learn more about GIT check this Quick tutorial,

First of all make sure you have your Git environment set up.You need to set up both your local environment and a Git repository (I prefer

GIT client application Mac/Windows

For GIT gui client application i recommended you to go with,

GitHub is the place to share code with friends, co-workers, classmates, and complete strangers. Over five million people use GitHub to build amazing things together.

Unity3d settings

You need to do these settings

Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode.

enter image description here

Enable External option in Unity ? Preferences ? Packages ? Repository

enter image description here

Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode.

enter image description here

Source: Using Git With 3D Games Source Control

Cast Int to enum in Java

Try MyEnum.values()[x] where x must be 0 or 1, i.e. a valid ordinal for that enum.

Note that in Java enums actually are classes (and enum values thus are objects) and thus you can't cast an int or even Integer to an enum.

How do I reformat HTML code using Sublime Text 2?

There is a nice open source CodeFormatter plugin, which(along reindenting) can beautify dirty code even all of it is in single line.

Is there any kind of hash code function in JavaScript?

The JavaScript specification defines indexed property access as performing a toString conversion on the index name. For example,

myObject[myProperty] = ...;

is the same as

myObject[myProperty.toString()] = ...;

This is necessary as in JavaScript


is the same as


And yes, it makes me sad as well :-(

In Bootstrap 3,How to change the distance between rows in vertical?

There's a simply way of doing it. You define for all the rows, except the first one, the following class with properties:

   position: relative;
   top: -20px;

Then you apply the class to all non-first rows and adjust the negative top value to fit your desired row space. It's easy and works way better. :) Hope it helped.

How to check if a file exists in Ansible?

You can use Ansible stat module to register the file, and when module to apply the condition.

- name: Register file
        path: "/tmp/test_file"
      register: file_path

- name: Create file if it doesn't exists
        path: "/tmp/test_file"
        state: touch
      when: file_path.stat.exists == False

HTML/CSS: Making two floating divs the same height

This works for me in IE 7, FF 3.5, Chrome 3b, Safari 4 (Windows).

Also works in IE 6 if you uncomment the clearer div at the bottom. Edit: as Natalie Downe said, you can simply add width: 100%; to #container instead.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="" xml:lang="en">
    <style type="text/css">
        #container {
            overflow: hidden;
            border: 1px solid black;
            background-color: red;
        #left-col {
            float: left;
            width: 50%;
            background-color: white;
        #right-col {
            float: left;
            width: 50%;
            margin-right: -1px; /* Thank you IE */
    <div id='container'>
        <div id='left-col'>
            Test content<br />
        <div id='right-col'>
            Test content
        <!--div style='clear: both;'></div-->

I don't know a CSS way to vertically center the text in the right div if the div isn't of fixed height. If it is, you can set the line-height to the same value as the div height and put an inner div containing your text with display: inline; line-height: 110%.

How to find day of week in php in a specific timezone

My solution is this:

$tempDate = '2012-07-10';
echo date('l', strtotime( $tempDate));

Output is: Tuesday

$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));

Output is: Tue

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

How do I compute the intersection point of two lines?

Using formula from:

 def findIntersection(x1,y1,x2,y2,x3,y3,x4,y4):
        px= ( (x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4) ) / ( (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) ) 
        py= ( (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4) ) / ( (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) )
        return [px, py]

How to get current location in Android

You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.

If you don't use the onLocationChanged it always will be the old location.

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on:
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert:

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

multiple conditions for filter in spark data frames

In java spark dataset it can be used as

Dataset userfilter = user.filter(col("gender").isin("male","female"));

What is the best (and safest) way to merge a Git branch into master?

git checkout master
git pull origin master
# Merge branch test into master
git merge test

After merging, if the file is changed, then when you merge it will through error of "Resolve Conflict"

So then you need to first resolve all your conflicts then, you have to again commit all your changes and then push

git push origin master

This is better do who has done changes in test branch, because he knew what changes he has done.

How can I change the font size using seaborn FacetGrid?

The FacetGrid plot does produce pretty small labels. While @paul-h has described the use of sns.set as a way to the change the font scaling, it may not be the optimal solution since it will change the font_scale setting for all plots.

You could use the seaborn.plotting_context to change the settings for just the current plot:

with sns.plotting_context(font_scale=1.5):
    sns.factorplot(x, y ...)

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Maximum size of an Array in Javascript

Like @maerics said, your target machine and browser will determine performance.

But for some real world numbers, on my 2017 enterprise Chromebook, running the operation:

Array(x).fill(0).filter(x => x < 6).length
  • x=5e4 takes 16ms, good enough for 60fps
  • x=4e6 takes 250ms, which is noticeable but not a big deal
  • x=3e7 takes 1300ms, which is pretty bad
  • x=4e7 takes 11000ms and allocates an extra 2.5GB of memory

So around 30 million elements is a hard upper limit, because the javascript VM falls off a cliff at 40 million elements and will probably crash the process.

EDIT: In the code above, I'm actually filling the array with elements and looping over them, simulating the minimum of what an app might want to do with an array. If you just run Array(2**32-1) you're creating a sparse array that's closer to an empty JavaScript object with a length, like {length: 4294967295}. If you actually tried to use all those 4 billion elements, you'll definitely your user's javascript process.

Learning Ruby on Rails

I've been moving from C# in my professional career to looking at Ruby and RoR in my personal life, and I've found linux to be slightly more appealing personally for development. Particularly now that I've started using git, the implementation is cleaner on linux.

Currently I'm dual booting and getting closer to running Ubuntu full time. I'm using gedit with various plugins for the development environment. And as of late 2010, I'm making the push to use Vim for development, even over Textmate on OS X.

A large amount of the Rails developers are using (gasp) Macs, which has actually got me thinking in that direction.

Although I haven't tried it, Ruby in Steel gives you a Ruby IDE inside the Visual Studio world, and IronRuby is the .NET flavor of Ruby, if you're interested.

As far as books are concerned, the Programming Ruby (also known as the Pickaxe) book from the Pragmatic Programmers is the de-facto for learning Ruby. I bit the bullet and purchased that book and Agile Web Development with Rails; both books have been excellent.

Peepcode screencasts and PDF books have also been great for getting started; at $9 per screencast it's hard to go wrong. I actually bought a 5-pack.

Also check out the following:

I've burned through the backlog of Rails and Rails Envy podcasts in the past month and they have provided wonderful insight into lots of topics, even regarding software development in general.

jquery .on() method with load event

I'm not sure what you're going for here--by the time jQuery(document).ready() has executed, it has already loaded, and thus document's load event will already have been called. Attaching the load event handler at this point will have no effect and it will never be called. If you're attempting to alert "started" once the document has loaded, just put it right in the (document).ready() call, like this:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {



If, as your code also appears to insinuate, you want to fire the alert when .abc has loaded, put it in an individual .load handler:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {

    $(".abc").on("load", function() {

Finally, I see little point in using jQuery in one place and $ in another. It's generally better to keep your code consistent, and either use jQuery everywhere or $ everywhere, as the two are generally interchangeable.

Is not required for packages in Python 3.3+

Based on my experience, even with python 3.3+, an empty is still needed sometimes. One situation is when you want to refer a subfolder as a package. For example, when I ran python -m, it didn't work until I created an empty under the test folder. And I'm talking about 3.6.6 version here which is pretty recent.

Apart from that, even for reasons of compatibility with existing source code or project guidelines, its nice to have an empty in your package folder.

How to copy data from one HDFS to another HDFS?

distcp command use for copying from one cluster to another cluster in parallel. You have to set the path for namenode of src and path for namenode of dst, internally it use mapper.


$ hadoop distcp <src> <dst>

there few options you can set for distcp

-m for no. of mapper for copying data this will increase speed of copying.

-atomic for auto commit the data.

-update will only update data that is in old version.

There are generic command for copying files in hadoop are -cp and -put but they are use only when the data volume is less.

Run/install/debug Android applications over Wi-Fi?

1- For this I am considering you have already installed the latest version of Android studio. If not you can download it from here.

2 - You can set the platform tools path in environment variable (optional).

3 - Make sure your device and pc connected to same network.

  • plug in the data cable from pc to device.

  • Now, type adb tcpip 5555

  • remove data cable.

  • Then type adb connect

  • here 5555 is the port number and is the ip address of the mobile device you can get id address from the mobile settings .

  • Then go to About device and go to status you can see the ip address of the device.

  • You can connect multiple device from different ports which can give ease in development.

  • Or you can go to this link for brief description with screenshots.

How to convert JTextField to String and String to JTextField?

JTextField allows us to getText() and setText() these are used to get and set the contents of the text field, for example.

text = texfield.getText();

hope this helps

Get month and year from date cells Excel

Try this formula (it will return value from A1 as is if it's not a date):


Or this formula (it's more strict, it will return #VALUE error if A1 is not date):


How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

Java Regex Capturing Groups

This is totally OK.

  1. The first group ( always captures the whole area that is covered by your regular expression. In this case, it's the whole string.
  2. Regular expressions are greedy by default, meaning that the first group captures as much as possible without violating the regex. The (.*)(\\d+) (the first part of your regex) covers the ...QT300 int the first group and the 0 in the second.
  3. You can quickly fix this by making the first group non-greedy: change (.*) to (.*?).

For more info on greedy vs. lazy, check this site.

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I have also got stuck into this and believe me disabling SELinux is not a good idea.

Please just use below and you are good,

sudo restorecon -R /var/www/mysite


Reporting (free || open source) Alternatives to Crystal Reports in Winforms

I would suggest that you use the fyiReporting (Forked and Moved Now Current as of 2012) tool if you are looking to replace Crystal Reports. I have used both fyiReporting and Crystal and would have to say that I prefer fyiReporting(though their website is ghetto).

Reasons for choosing fyiReporting

  1. If you want to replace Crystal then you are used to having a Report designer. FyiReporting has its own GUI just like Crystal Reports for creating and running reports(You could just create and distribute reports without building an application).

  2. FyiReports allows you to export the Report as PDF, excel and mht(static web page) just to mention a few.

  3. FyiReports are xml based so the report definition can be saved in a database and altered at anytime.

  4. If you are using .Net FyiReporting has a Web and Windows Forms control for embedding the report in your applications(much like crystal reports). I am not so sure about Java as I am a .Net guy.

Anyway give FyiReports a try.

Create a OpenSSL certificate on Windows

You can certainly use putty (puttygen.exe) to do that.

Or you can get Cygwin to use the utilities you just described.

Set HTML dropdown selected option using JSTL

In Servlet do:

String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);

Then in JSP do:

<select name="roleName">
    <c:forEach items="${roleNames}" var="role">
        <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>

It will print the selected attribute of the HTML <option> element so that you end up like:

<select name="roleName">
    <option value="cat">cat</option>
    <option value="rat" selected>rat</option>
    <option value="unicorn">unicorn</option>

Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

Change the jquery show()/hide() animation?

Use slidedown():


Javascript Date Validation ( DD/MM/YYYY) & Age Checking

var date=/^[0-9]{1,2}\-[0-9]{1,2}\-[0-9]{1,4}$/;


alert("Enter correct date");

alert(" working");

How to get html to print return value of javascript function?

<script type="text/javascript">
    document.write("<p>" + Date() + "</p>");

Is a good example.

How to fully clean bin and obj folders within Visual Studio?

Clean will remove all intermediate and final files created by the build process, such as .obj files and .exe or .dll files.

It does not, however, remove the directories where those files get built. I don't see a compelling reason why you need the directories to be removed. Can you explain further?

If you look inside these directories before and after a "Clean", you should see your compiled output get cleaned up.

Reference - What does this error mean in PHP?

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew ?????? ?????????. which means "double colon".

This error typically happens if you inadvertently put :: in your code.

Related Questions:


Construct pandas DataFrame from items in nested dictionary

So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d

import pandas as pd
{'RAY Index': {, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}

The command

<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06

where pd.Panel(d)[item] yields a dataframe

pd.Panel(d)['SPX Index']
2014-11-03  2014-11-04  2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33

You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.

major   minor      RAY Index    SPX Index
PX_LAST 2014-11-03  1199.460    2017.81
PX_LAST 2014-11-04  1195.323    2012.10
PX_LAST 2014-11-05  1200.936    2023.57
PX_LAST 2014-11-06  1206.061    2031.21
PX_OPEN 2014-11-03  1200.140    2018.21
PX_OPEN 2014-11-04  1197.690    2015.81
PX_OPEN 2014-11-05  1195.320    2015.29
PX_OPEN 2014-11-06  1200.620    2023.33

Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here

Just as an example

major        minor  2014-11-03  2014-11-04  2014-11-05  2014-11-06
RAY Index   PX_LAST 1199.46    1195.323     1200.936    1206.061
RAY Index   PX_OPEN 1200.14    1197.690     1195.320    1200.620
SPX Index   PX_LAST 2017.81    2012.100     2023.570    2031.210
SPX Index   PX_OPEN 2018.21    2015.810     2015.290    2023.330

Hope this helps.

How to use font-awesome icons from node-modules

Since I'm currently learning node js, I also encountered this problem. All I did was, first of all, install the font-awesome using npm

npm install font-awesome --save-dev

after that, I set a static folder for the css and fonts:

app.use('/fa', express.static(__dirname + '/node_modules/font-awesome/css'));
app.use('/fonts', express.static(__dirname + '/node_modules/font-awesome/fonts'));

and in html:

<link href="/fa/font-awesome.css" rel="stylesheet" type="text/css">

and it works fine!

Subset data to contain only columns whose names match a condition

Try grepl on the names of your data.frame. grepl matches a regular expression to a target and returns TRUE if a match is found and FALSE otherwise. The function is vectorised so you can pass a vector of strings to match and you will get a vector of boolean values returned.


#  Data
df <- data.frame( ABC_1 = runif(3),
            ABC_2 = runif(3),
            XYZ_1 = runif(3),
            XYZ_2 = runif(3) )

#      ABC_1     ABC_2     XYZ_1     XYZ_2
#1 0.3792645 0.3614199 0.9793573 0.7139381
#2 0.1313246 0.9746691 0.7276705 0.0126057
#3 0.7282680 0.6518444 0.9531389 0.9673290

#  Use grepl
df[ , grepl( "ABC" , names( df ) ) ]
#      ABC_1     ABC_2
#1 0.3792645 0.3614199
#2 0.1313246 0.9746691
#3 0.7282680 0.6518444

#  grepl returns logical vector like this which is what we use to subset columns
grepl( "ABC" , names( df ) )

To answer the second part, I'd make the subset data.frame and then make a vector that indexes the rows to keep (a logical vector) like this...

df <- data.frame( ABC_1 = sample(0:1,3,repl = TRUE),
            ABC_2 = sample(0:1,3,repl = TRUE),
            XYZ_1 = sample(0:1,3,repl = TRUE),
            XYZ_2 = sample(0:1,3,repl = TRUE) )

# We will want to discard the second row because 'all' ABC values are 0:
#  ABC_1 ABC_2 XYZ_1 XYZ_2
#1     0     1     1     0
#2     0     0     1     0
#3     1     1     1     0

df1 <- df[ , grepl( "ABC" , names( df ) ) ]

ind <- apply( df1 , 1 , function(x) any( x > 0 ) )

df1[ ind , ]
#  ABC_1 ABC_2
#1     0     1
#3     1     1

iOS change navigation bar title font and color

My Swift code for change Navigation Bar title:

let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
self.navigationController.navigationBar.titleTextAttributes = attributes

And if you want to change background font too then I have this in my AppDelegate:

let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal)

How to update/refresh specific item in RecyclerView

You can use the notifyItemChanged(int position) method from the RecyclerView.Adapter class. From the documentation:

Notify any registered observers that the item at position has changed. Equivalent to calling notifyItemChanged(position, null);.

This is an item change event, not a structural change event. It indicates that any reflection of the data at position is out of date and should be updated. The item at position retains the same identity.

As you already have the position, it should work for you.

Get driving directions using Google Maps API v2

This is what I am using,

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
intent.addCategory(Intent.CATEGORY_LAUNCHER );     
intent.setClassName("", "");
startActivity(intent); Address already in use: JVM_Bind <null>:80

I do a goofy mistake and It take me 2 hour to solve It.I mentioned it here for other persons may be help them.The mistake was I enable ssl connector and changed both https and http ports to same number .

Center a position:fixed element

You basically need to set top and left to 50% to center the left-top corner of the div. You also need to set the margin-top and margin-left to the negative half of the div's height and width to shift the center towards the middle of the div.

Thus, provided a <!DOCTYPE html> (standards mode), this should do:

position: fixed;
width: 500px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px; /* Negative half of height. */
margin-left: -250px; /* Negative half of width. */

Or, if you don't care about centering vertically and old browsers such as IE6/7, then you can instead also add left: 0 and right: 0 to the element having a margin-left and margin-right of auto, so that the fixed positioned element having a fixed width knows where its left and right offsets start. In your case thus:

position: fixed;
width: 500px;
height: 200px;
margin: 5% auto; /* Will not center vertically and won't work in IE6/7. */
left: 0;
right: 0;

Again, this works only in IE8+ if you care about IE, and this centers only horizontally not vertically.

Handling warning for possible multiple enumeration of IEnumerable

If you only need to check the first element you can peek on it without iterating the whole collection:

public List<object> Foo(IEnumerable<object> objects)
    object firstObject;
    if (objects == null || !TryPeek(ref objects, out firstObject))
        throw new ArgumentException();

    var list = DoSomeThing(firstObject);
    var secondList = DoSomeThingElse(objects);

    return list;

public static bool TryPeek<T>(ref IEnumerable<T> source, out T first)
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    IEnumerator<T> enumerator = source.GetEnumerator();
    if (!enumerator.MoveNext())
        first = default(T);
        source = Enumerable.Empty<T>();
        return false;

    first = enumerator.Current;
    T firstElement = first;
    source = Iterate();
    return true;

    IEnumerable<T> Iterate()
        yield return firstElement;
        using (enumerator)
            while (enumerator.MoveNext())
                yield return enumerator.Current;

How do I refresh a DIV content?

This one $("#yourDiv").load(" #yourDiv > *"); is the best if you are planning to just reload a <div>

Make sure to use an id and not a class. Also, remember to paste <script src=""></script> in the <head> section of the html file, if you haven't already. In opposite case it won't work.

Center form submit buttons HTML / CSS

I see a few answers here, most of them complicated or with some cons (additional divs, text-align doesn't work because of display: inline-block). I think this is the simplest and problem-free solution:


    <!-- Rows -->
        <td><input name="email" type="email" /></td>
        <td><input type="submit" value="Register!" /></td>


table input[type="submit"] {
    display: block;
    margin: 0 auto;

How to import JsonConvert in C# application?

After instaling the package you need to add the newtonsoft.json.dll into assemble path by runing the flowing command.

Before we can use our assembly, we have to add it to the global assembly cache (GAC). Open the Visual Studio 2008 Command Prompt again (for Vista/Windows7/etc. open it as Administrator). And execute the following command. gacutil /i d:\myMethodsForSSIS\myMethodsForSSIS\bin\Release\myMethodsForSSIS.dll

flow this link for more informATION

How can I replace non-printable Unicode characters in Java?

I propose it remove the non printable characters like below instead of replacing it

private String removeNonBMPCharacters(final String input) {
    StringBuilder strBuilder = new StringBuilder();
    input.codePoints().forEach((i) -> {
        if (Character.isSupplementaryCodePoint(i)) {
        } else {
    return strBuilder.toString();

Call a stored procedure with parameter in c#

cmd.Parameters.Add(String parameterName, Object value) is deprecated now. Instead use cmd.Parameters.AddWithValue(String parameterName, Object value)

Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value)

There is no difference in terms of functionality. The reason they deprecated the cmd.Parameters.Add(String parameterName, Object value) in favor of AddWithValue(String parameterName, Object value) is to give more clarity. Here is the MSDN reference for the same

private void button1_Click(object sender, EventArgs e) {
  using (SqlConnection con = new SqlConnection(dc.Con)) {
    using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.AddWithValue("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
      cmd.Parameters.AddWithValue("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;


Installing PG gem on OS X - failure to build native extension

If you are using Ubuntu try to install following lib file

sudo apt-get install libpq-dev

and then

gem install pg

worked for me.

Python Checking a string's first and last character

When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1

Finding what methods a Python object has

On top of the more direct answers, I'd be remiss if I didn't mention IPython.

Hit Tab to see the available methods, with autocompletion.

And once you've found a method, try:


to see the pydocs, method signature, etc.

Ahh... REPL.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

In case anyone arrives looking for how to generate a relative path from the rails console

=> "/images/my_image.png"

Or the controller

include ActionView::Helpers::AssetTagHelper
=> "/images/my_image.png"

syntaxerror: unexpected character after line continuation character in python


f = open(D\\python\\HW\\2_1 - Copy.cp,"r");


f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")

  1. File path needs to be a string (constant)
  2. need colon in Windows file path
  3. space after comma for better style
  4. ; after statement is allowed but fugly.

What tutorial are you using?

Objective C - Assign, Copy, Retain

  1. assign

    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:

    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:

    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”

iPad/iPhone hover problem causes the user to double click a link

Avoid changing of "display" style inside of hover css event. I had "display: block" in hover state. After removing ios went on lins by single tap. By the way it seems that latest IOS updates fixed this "feature"

Pressing Ctrl + A in Selenium WebDriver

One more solution (in Java, because you didn't tell us your language - but it works the same way in all languages with Keys class):

String selectAll = Keys.chord(Keys.CONTROL, "a");

You can use this to select the whole text in an <input>, or on the whole page (just find the html element and send this to it).

For using Selenium Ruby bindings:

There's no chord() method in the Keys class in Ruby bindings. Therefore, as suggested by Hari Reddy, you'll have to use Selenium Advanced user interactions API, see ActionBuilder:


How to display image from URL on Android

InputStream URLcontent = (InputStream) new URL(url).getContent();
Drawable image = Drawable.createFromStream(URLcontent, "your source link");

this has worked for me

Why aren't Xcode breakpoints functioning?

If you tried all basic checks, check for for Optimization Level in project target and project settings. make sure you selected None for debug.

enter image description here

fileReader.readAsBinaryString to upload files

The best way in browsers that support it, is to send the file as a Blob, or using FormData if you want a multipart form. You do not need a FileReader for that. This is both simpler and more efficient than trying to read the data.

If you specifically want to send it as multipart/form-data, you can use a FormData object:

var xmlHttpRequest = new XMLHttpRequest();"POST", '/pushfile', true);
var formData = new FormData();
// This should automatically set the file name and type.
formData.append("file", file);
// Sending FormData automatically sets the Content-Type header to multipart/form-data

You can also send the data directly, instead of using multipart/form-data. See the documentation. Of course, this will need a server-side change as well.

// file is an instance of File, e.g. from a file input.
var xmlHttpRequest = new XMLHttpRequest();"POST", '/pushfile', true);

xmlHttpRequest.setRequestHeader("Content-Type", file.type);

// Send the binary data.
// Since a File is a Blob, we can send it directly.

For browser support, see: (most browsers, including IE 10+).

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

Generate preview image from Video file?

Two ways come to mind:

  • Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that

  • Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.

Getting error: ISO C++ forbids declaration of with no type

Your declaration is int ttTreeInsert(int value);

However, your definition/implementation is

ttTree::ttTreeInsert(int value)

Notice that the return type int is missing in the implementation. Instead it should be

int ttTree::ttTreeInsert(int value)
    return 1; // or some valid int

JavaScript: How to get parent element by selector?

Using leech's answer with indexOf (to support IE)

This is using what leech talked about, but making it work for IE (IE doesn't support matches):

function closest(el, selector, stopSelector) {
  var retval = null;
  while (el) {
    if (el.className.indexOf(selector) > -1) {
      retval = el;
    } else if (stopSelector && el.className.indexOf(stopSelector) > -1) {
    el = el.parentElement;
  return retval;

It's not perfect, but it works if the selector is unique enough so it won't accidentally match the incorrect element.

How do I append one string to another in Python?

it really depends on your application. If you're looping through hundreds of words and want to append them all into a list, .join() is better. But if you're putting together a long sentence, you're better off using +=.

Hive: how to show all partitions of a table?

CLI has some limit when ouput is displayed. I suggest to export output into local file:

$hive -e 'show partitions table;' > partitions

Get current rowIndex of table in jQuery

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();