Programs & Examples On #Axis2

A Web Services/SOAP/WSDL framework supported by the Apache Software Foundation

Difference between Apache CXF and Axis

Another advantage of CXF: it connects to web servers using NTLMV2 authentication out of the box. (used by Windows 2008 & up) Before using CXF, I hacked Axis2 to use HTTPClient V4 + JCIFS to make this possible.

How do you Change a Package's Log Level using Log4j?

I just encountered the issue and couldn't figure out what was going wrong even after reading all the above and everything out there. What I did was

  1. Set root logger level to WARN
  2. Set package log level to DEBUG

Each logging implementation has it's own way of setting it via properties or via code(lot of help available on this)

Irrespective of all the above I would not get the logs in my console or my log file. What I had overlooked was the below...

enter image description here

All I was doing with the above jugglery was controlling only the production of the logs(at root/package/class etc), left of the red line in above image. But I was not changing the way displaying/consumption of the logs of the same, right of the red line in above image. Handler(Consumption) is usually defaulted at INFO, therefore your precious debug statements wouldn't come through. Consumption/displaying is controlled by setting the log levels for the Handlers(ConsoleHandler/FileHandler etc..) So I went ahead and set the log levels of all my handlers to finest and everything worked.

This point was not made clear in a precise manner in any place.

I hope someone scratching their head, thinking why the properties are not working will find this bit helpful.

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread:

Java Webservice Client (Best way)

What is the best approach to do this JAVA?

I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:

  1. I don't like its architecture and hate its counter productive deployment model.
  2. I find it to be low quality project.
  3. I don't like its performances (see this benchmark against JAX-WS RI).
  4. It's always a nightmare to setup dependencies (I use Maven and I always have to fight with the gazillion of dependencies) (see #2)
  5. Axis sucked big time and Axis2 isn't better. No, this is not a personal opinion, there is a consensus.
  6. I suffered once, never again.

The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.

I read about SAAJ, looks like that will be more granular level of approach?

To do what?

Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?

Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport.

Can someone send the links for some good tutorials on these topics?

That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:

What are the options we need to use while generating the code using the WSDL2Java?

No options, use wsimport :)

See also

Related questions

The endpoint reference (EPR) for the Operation not found is

I had this same problem using curl to send a soap request. Solved it by adding "content-type: text/xml" to the http header.

I hope this helps someone.

Content is not allowed in Prolog SAXParserException

Check the XML. It is not a valid xml.

Prolog is the first line with xml version info. It ok not to include it in your xml.

This error is thrown when the parser reads an invalid tag at the start of the document. Normally where the prolog resides.


  1. Root/><document>
  2. Root<document>

How to restore default perspective settings in Eclipse IDE

The solution that worked for me. Delete this folder:


Convert integer to hexadecimal and back again

Try the following to convert it to hex

public static string ToHex(this int value) {
  return String.Format("0x{0:X}", value);

And back again

public static int FromHex(string value) {
  // strip the leading 0x
  if ( value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
    value = value.Substring(2);
  return Int32.Parse(value, NumberStyles.HexNumber);

Angularjs ng-model doesn't work inside ng-if

You can use $parent to refer to the model defined in the parent scope like this

<input type="checkbox" ng-model="$parent.testb" />

Combining a class selector and an attribute selector with jQuery

This will also work:

$(".myclass[reference='12345']").css('border', '#000 solid 1px');

xampp MySQL does not start

Try this: really quick + worked for me:

  1. Open Task Manager > Services Tab
  2. Find "mysqlweb" service > right-click it to stop service
  3. Launch Xampp again

ps: excuse image below for different language :)

enter image description here

Python datetime to string without microsecond component

We can try something like below

import datetime

date_generated =
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]

Export DataTable to Excel with Open Xml SDK in c#

I also wrote a C#/VB.Net "Export to Excel" library, which uses OpenXML and (more importantly) also uses OpenXmlWriter, so you won't run out of memory when writing large files.

Full source code, and a demo, can be downloaded here:

Export to Excel

It's dead easy to use. Just pass it the filename you want to write to, and a DataTable, DataSet or List<>.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx");

And if you're calling it from an ASP.Net application, pass it the HttpResponse to write the file out to.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx", Response);

Round integers to the nearest 10

I wanted to do the same thing, but with 5 instead of 10, and came up with a simple function. Hope it's useful:

def roundToFive(num):
    remaining = num % 5
    if remaining in range(0, 3):
        return num - remaining
    return num + (5 - remaining)


A TCP connection is specified by the tuple (source IP, source port, destination IP, destination port).

The reason why there is a TIME_WAIT state following session shutdown is because there may still be live packets out in the network on their way to you (or from you which may solicit a response of some sort). If you were to re-create that same tuple and one of those packets showed up, it would be treated as a valid packet for your connection (and probably cause an error due to sequencing).

So the TIME_WAIT time is generally set to double the packets maximum age. This value is the maximum age your packets will be allowed to get to before the network discards them.

That guarantees that, before you're allowed to create a connection with the same tuple, all the packets belonging to previous incarnations of that tuple will be dead.

That generally dictates the minimum value you should use. The maximum packet age is dictated by network properties, an example being that satellite lifetimes are higher than LAN lifetimes since the packets have much further to go.

What is the difference between Bootstrap .container and .container-fluid classes?

From a display perspective .container gives you more control over the what the users are seeing, and makes it easier to see what the users will see as you only have 4 variations of display (5 in the case of bootstrap 5) because the sizes relate to the same as the grid sizes. e.g. .col-xs, .col-sm, .col, and .col-lg.

What this means, is that when you are doing user testing if you test on a displays with the 4 different sizes you see all the veriations in display.

When using .container-fluid because the witdh is related to the viewport width the display is dynamic, so the varations are much greater and users with very large screens or uncommon screen widths may see results you weren't expecting.

PostgreSQL: days/months/years between two dates

Almost the same function as you needed (based on atiruz's answer, shortened version of UDF from here)

    CASE type
        WHEN 'year' THEN
            RETURN date_part('year', date_to) - date_part('year', date_from);
        WHEN 'month' THEN
            age := age(date_to, date_from);
            RETURN date_part('year', age) * 12 + date_part('month', age);
            RETURN (date_to - date_from)::int;


/* Get months count between two dates */
SELECT datediff('month', '2015-02-14'::date, '2016-01-03'::date);
/* Result: 10 */

/* Get years count between two dates */
SELECT datediff('year', '2015-02-14'::date, '2016-01-03'::date);
/* Result: 1 */

/* Get days count between two dates */
SELECT datediff('day', '2015-02-14'::date, '2016-01-03'::date);
/* Result: 323 */

/* Get months count between specified and current date */
SELECT datediff('month', '2015-02-14'::date, NOW()::date);
/* Result: 47 */

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Jupyter is base on ipython, a permanent solution could be changing the ipython config options.

Create a config file

$ ipython profile create
$ ipython locate

Edit the config file

$ cd /Users/username/.ipython
$ vi profile_default/

The following lines allow you to add your module path to sys.path

c.InteractiveShellApp.exec_lines = [
    'import sys; sys.path.append("/path/to/your/module")'

At the jupyter startup the previous line will be executed

Here you can find more details about ipython config

Emulator error: This AVD's configuration is missing a kernel file

I tried what ChrLipp suggested, but that wasn't the problem, as the image was already installed. What I did was run:

android avd

to start the emulator manually. Then I stopped the emulator, and form that point on the

cca emulate android

app started working, without the "missing a kernel file" error.

Ping with timestamp on Windows CLI

This might fit the bill for later Windows versions:

for /l %i in (1,0,2) do @echo|cmd /v:on /c set /p=!time! & ping -n 1 | findstr "Reply timed" && timeout /t 2 > nul:

How to catch SQLServer timeout exceptions

Whats the value for the SqlException.ErrorCode property? Can you work with that?

When having timeouts, it may be worth checking the code for -2146232060.

I would set this up as a static const in your data code.

Memcache Vs. Memcached

They are not identical. Memcache is older but it has some limitations. I was using just fine in my application until I realized you can't store literal FALSE in cache. Value FALSE returned from the cache is the same as FALSE returned when a value is not found in the cache. There is no way to check which is which. Memcached has additional method (among others) Memcached::getResultCode that will tell you whether key was found.

Because of this limitation I switched to storing empty arrays instead of FALSE in cache. I am still using Memcache, but I just wanted to put this info out there for people who are deciding.

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
 The Twelve Days of Christmas

The error about well-formed XML on the root level should disappear (though there may be other issues).

npm install error - unable to get local issuer certificate

A disclaimer: This solution is less secure, bad practice, don't do this. I had a duplicate error message--I'm behind a corporate VPN/firewall. I was able to resolve this issue by adding a .typingsrc file to my user directory (C:\Users\MyUserName\.typingsrc in windows). Of course, anytime you're circumventing SSL you should be yapping to your sys admins to fix the certificate issue.

Change the registry URL from https to http, and as seen in nfiles' answser above, set rejectUnauthorized to false.

.typingsrc (placed in project directory or in user root directory)

     "rejectUnauthorized": false,
     "registryURL": ""

Optionally add your github token (I didn't find success until I had added this too.)

    "rejectUnauthorized": false,
    "registryURL": "",
    "githubToken": "YourGitHubToken"

See instructions for setting up your github token at

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

An alternative to jcoby's proposal would be:

class NilClass
  def nil_or_empty?

class String
  def nil_or_empty?

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
    using (MemoryStream ms = new MemoryStream())
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

What's the difference between SCSS and Sass?

Sass was the first one, and the syntax is a bit different. For example, including a mixin:

Sass: +mixinname()
Scss: @include mixinname()

Sass ignores curly brackets and semicolons and lay on nesting, which I found more useful.

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

This worked for me ....

#include <stdio.h>
#include <time.h>   /* Needed for struct timespec */

int nsleep(long miliseconds)
   struct timespec req, rem;

   if(miliseconds > 999)
        req.tv_sec = (int)(miliseconds / 1000);                            /* Must be Non-Negative */
        req.tv_nsec = (miliseconds - ((long)req.tv_sec * 1000)) * 1000000; /* Must be in range of 0 to 999999999 */
        req.tv_sec = 0;                         /* Must be Non-Negative */
        req.tv_nsec = miliseconds * 1000000;    /* Must be in range of 0 to 999999999 */

   return nanosleep(&req , &rem);

int main()
   int ret = nsleep(2500);
   printf("sleep result %d\n",ret);
   return 0;

What is 'PermSize' in Java?

The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.

Run PHP function on html button click

If you want to make a server request you should use AJAX, so you can send your desired parameters to the server and it can run whatever php you want with these parameters.

Example with pure javascript:

<input type="text" id="name" value="..."/>
<input type="text" id="location" value="..."/>
<input type="button" onclick="ajaxFunction();" value="Submit" />
<div id="ajaxDiv"></div>
<script type="text/javascript">    
    function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                var ajaxDisplay = document.getElementById('ajaxDiv');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
        var name = document.getElementById('name').value;
        var location = document.getElementById('location').value;
        var queryString = "?name=" + name + "&location=" + location;"POST", "some.php" + queryString, true);

Example with jQuery Ajax:

  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );

You can have one file with functions called for example functions.php


  myFunction($Name, $Location) {
      // etc...
  myFunction2() {
  // ... many functions


<?php include("functions.php");    
$Name = $_POST['name'];
$Location = $_POST['location'];

myFunction($Name, $Location);

// make what you want with these variables...?>

Most common C# bitwise operations on enums


Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:

public enum TestFlags
    One = 1,
    Two = 2,
    Three = 4,
    Four = 8,
    Five = 16,
    Six = 32,
    Seven = 64,
    Eight = 128,
    Nine = 256,
    Ten = 512

class Program
    static void Main(string[] args)
        TestFlags f = TestFlags.Five; /* or any other enum */
        bool result = false;

        Stopwatch s = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
            result |= f.HasFlag(TestFlags.Three);
        Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*

        for (int i = 0; i < 10000000; i++)
            result |= (f & TestFlags.Three) != 0;
        Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*        


Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.

Autowiring two beans implementing same interface - how to set default bean to autowire?

What about @Primary?

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.

public class HibernateDeviceDao implements DeviceDao

Or if you want your Jdbc version to be used by default:

<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">

@Primary is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.

Android Studio Stuck at Gradle Download on create new project

Invalidate Caches and Restart

It worked for me.

Moving all files from one directory to another using Python

Try this:

import shutil
import os
source_dir = '/path/to/source_folder'
target_dir = '/path/to/dest_folder'
file_names = os.listdir(source_dir)
for file_name in file_names:
    shutil.move(os.path.join(source_dir, file_name), target_dir)

Local Storage vs Cookies

Well, local storage speed greatly depends on the browser the client is using, as well as the operating system. Chrome or Safari on a mac could be much faster than Firefox on a PC, especially with newer APIs. As always though, testing is your friend (I could not find any benchmarks).

I really don't see a huge difference in cookie vs local storage. Also, you should be more worried about compatibility issues: not all browsers have even begun to support the new HTML5 APIs, so cookies would be your best bet for speed and compatibility.

Testing socket connection in Python

12 years later for anyone having similar problems.

    s.connect((address, '80'))
    alert('failed' + address, 'down')

doesn't work because the port '80' is a string. Your port needs to be int.

    s.connect((address, 80))

This should work. Not sure why even the best answer didnt see this.

How can a web application send push notifications to iOS devices?

You can use pushover if you don't want to create your own native app:

CSS3 transform: rotate; in IE9

I know this is old, but I was having this same issue, found this post, and while it didn't explain exactly what was wrong, it helped me to the right answer - so hopefully my answer helps someone else who might be having a similar problem to mine.

I had an element I wanted rotated vertical, so naturally I added the filter: for IE8 and then the -ms-transform property for IE9. What I found is that having the -ms-transform property AND the filter applied to the same element causes IE9 to render the element very poorly. My solution:

  1. If you are using the transform-origin property, add one for MS too (-ms-transform-origin: left bottom;). If you don't see your element, it could be that it's rotating on it's middle axis and thus leaving the page somehow - so double check that.

  2. Move the filter: property for IE7&8 to a separate style sheet and use an IE conditional to insert that style sheet for browsers less than IE9. This way it doesn't affect the IE9 styles and all should work fine.

  3. Make sure to use the correct DOCTYPE tag as well; if you have it wrong IE9 will not work properly.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.

map is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)

noremap is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map. (Think of the nore prefix to mean "non-recursive".)

(Note that there are also the ! modes like map! that apply to insert & command-line.)

See below for what "recursive" means in this context.

Prepending a mode letter like n modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map wouldn't apply to (e.g. "insert").

Use help map-modes will show you a few tables that explain how to control which modes the mapping applies to.

Mode letters:

  • n: normal only
  • v: visual and select
  • o: operator-pending
  • x: visual only
  • s: select only
  • i: insert
  • c: command-line
  • l: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)

"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.

The expansion stops when one of these is true:

  1. the result is no longer mapped to anything else.
  2. a non-recursive mapping has been applied (i.e. the "noremap" [or one of its ilk] is the final expansion).

At that point, Vim's default "meaning" of the final result is applied/executed.

"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.


 nmap K H
 nnoremap H G
 nnoremap G gg

The above causes K to expand to H, then H to expand to G and stop. It stops because of the nnoremap, which expands and stops immediately. The meaning of G will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).

The mapping of G to gg only applies if you press G, but not if you press K. This mapping doesn't affect pressing K regardless of whether G was mapped recursively or not, since it's line 2 that causes the expansion of K to stop, so line 3 wouldn't be used.

Django TemplateDoesNotExist?

If you encounter this problem when you add an app from scratch. It is probably because that you miss some settings. Three steps is needed when adding an app.

1?Create the directory and template file.

Suppose you have a project named mysite and you want to add an app named your_app_name. Put your template file under mysite/your_app_name/templates/your_app_name as following.

+-- mysite
¦   +--
¦   +--
¦   +--
+-- your_app_name
¦   +--
¦   +--
¦   +--
¦   +-- templates
¦   ¦   +-- your_app_name
¦   ¦       +-- my_index.html
¦   +--
¦   +--

2?Add your app to INSTALLED_APPS.



3?Add your app directory to DIRS in TEMPLATES.


        'DIRS': [os.path.join(BASE_DIR, 'templates'),
                 os.path.join(BASE_DIR, 'your_app_name', 'templates', 'your_app_name'),

Finding diff between current and last version

Firstly, use "git log" to list the logs for the repository.

Now, select the two commit IDs, pertaining to the two commits. You want to see the differences (example - Top most commit and some older commit (as per your expectation of current-version and some old version)).

Next, use:

git diff <commit_id1> <commit_id2>


git difftool <commit_id1> <commit_id2>

how to bind img src in angular 2 in ngFor?

I hope i am understanding your question correctly, as the above comment says you need to provide more information.

In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.

<div *ngFor="let student of students">  

 <img [src]="student.image">


How to Check if value exists in a MySQL database

This works for me :

$db = mysqli_connect('localhost', 'UserName', 'Password', 'DB_Name') or die('Not Connected');
mysqli_set_charset($db, 'utf8');

$sql = mysqli_query($db,"SELECT * FROM `mytable` WHERE city='c7'");
$sql = mysqli_fetch_assoc($sql);
$Checker = $sql['city'];

if  ($Checker != null) {
    echo 'Already exists';
} else {

    echo 'Not found';

How to get complete current url for Cakephp

Cakephp 3.x anywhere:


Access denied for user 'homestead'@'localhost' (using password: YES)

Two way to solve it

First way (Not recommended)

Open your database config file (laravel_root/config/database.php) & search for the below code block.

        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'blog'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),

Change the code block as below

        'host'      => 'yourHostName',
        'database'  => 'YourDatabastName',
        'username'  => 'YoutDatabaseUsername',
        'password'  => 'YourDatabasePassword',

Second way (Recommended by Laravel)

Check your Laravel root there have a file call .env if not exist, look for .env.example, copy/rename it as .env after that the file looks blow !





Modify the below block as follow


Now it will work fine.

JavaScript hard refresh of current page

window.location.href = window.location.href Invalid postback or callback argument

After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.

This caused the app pool to give up and reply with the exception noted in the question.

Somewhere along the way my installshield project had its App pool definition changed to use "3" (probably just a mis-click or mis-type).

100% width in React Native Flexbox

You should use Dimensions

First, define Dimensions.

import { Dimensions } from "react-native";

var width = Dimensions.get('window').width; //full width
var height = Dimensions.get('window').height; //full height

then, change line1 style like below:

line1: {
    backgroundColor: '#FDD7E4',
    width: width,

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

Connecting to SQL Server with Visual Studio Express Editions

My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.

This difference in IDE behavior is one of the key reasons for upgrading to a full version.

SQL Query NOT Between Two Dates

How about trying:

select * from 'test_table'
where end_date < CAST('2009-12-15' AS DATE)
or start_date > CAST('2010-01-02' AS DATE)

which will return all date ranges which do not overlap your date range at all.

Android studio doesn't list my phone under "Choose Device"

I face Same problem. In my case i solved this by following some steps.

  1. click attached debugger to android process (It located In android tools inside run button)

  2. if see adb not responding error dialog. then click restart of dialogue button.

  3. Now you can see which device is connected. now close this window.

  4. again press run button. Now you find your targeted device or emulator which is connected.

Hopefully it helps you.

Does the join order matter in SQL?

If you try joining C on a field from B before joining B, i.e.:

       on B.x = C.x
       on A.x = B.x

your query will fail, so in this case the order matters.

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    "reply": true

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    private String workstationUuid;
    // getter and setter

the switch up your method

public void setWorkstation(Data data) {
    // use getter to retrieve it

Fastest way to remove first char in a String

I would just use

string data= "/temp string";
data = data.substring(1)

Output: temp string

That always works for me.

PHP how to get local IP of system

This is an old post, but get it with this:

function getLocalIp()
{ return gethostbyname(trim(`hostname`)); }

For example:

die( getLocalIp() );

Found it on another site, do not remove the trim command because otherwise you will get the computers name.

BACKTICKS (The special quotes): It works because PHP will attempt to run whatever it's between those "special quotes" (backticks) as a shell command and returns the resulting output.


Is very similar (but much more efficient) than doing:

$exec = exec("hostname"); //the "hostname" is a valid command in both windows and linux
$hostname = trim($exec); //remove any spaces before and after
$ip = gethostbyname($hostname); //resolves the hostname using local hosts resolver or DNS

How to clear APC cache entries?

New APC Admin interface have options to add/clear user cache and opcode cache, One interesting functionality is to add/refresh/delete directory's from opCode Cache

APC Admin Documentation

enter image description here

Error type 3 Error: Activity class {} does not exist

If anyone is seeing this,

This fix worked for me as nothing from the above worked:

  1. Remove the installed debug APK from your phone
  2. In Android Studio, go to Build, choose Build APK(s)
  3. Put this generated APK on your phone and launch it
  4. Exit this app and try to debug your app again from Android Studio

This worked for me

PostgreSQL Autoincrement

Since PostgreSQL 10

CREATE TABLE test_new (
    payload text

Node.js EACCES error when listening on most ports

Remember if you use sudo to bind to port 80 and are using the env variables PORT & NODE_ENV you must reexport those vars as you are now under root profile and not your user profile. So, to get this to work on my Mac i did the following:

sudo su
export NODE_ENV=production
export PORT=80
docpad run

Cannot authenticate into mongo, "auth fails"

In MongoDB 3.0, it now supports multiple authentication mechanisms.

  1. MongoDB Challenge and Response (SCRAM-SHA-1) - default in 3.0
  2. MongoDB Challenge and Response (MONGODB-CR) - previous default (< 3.0)

If you started with a new 3.0 database with new users created, they would have been created using SCRAM-SHA-1.

So you will need a driver capable of that authentication:

If you had a database upgraded from 2.x with existing user data, they would still be using MONGODB-CR, and the user authentication database would have to be upgraded:

Now, connecting to MongoDB 3.0 with users created with SCRAM-SHA-1 are required to specify the authentication database (via command line mongo client), and using other mechanisms if using a driver.

$> mongo -u USER -p PASSWORD --authenticationDatabase admin

In this case, the "admin" database, which is also the default will be used to authenticate.

How to convert data.frame column from Factor to numeric

From ?factor:

To transform a factor f to approximately its original numeric values, as.numeric(levels(f))[f] is recommended and slightly more efficient than as.numeric(as.character(f)).

Get difference between 2 dates in JavaScript?

Here is one way:

const date1 = new Date('7/13/2010');_x000D_
const date2 = new Date('12/15/2010');_x000D_
const diffTime = Math.abs(date2 - date1);_x000D_
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); _x000D_
console.log(diffTime + " milliseconds");_x000D_
console.log(diffDays + " days");

Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.

Remove characters from NSString?

If you want to support more than one space at a time, or support any whitespace, you can do this:

NSString* noSpaces =
    [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

Python, compute list difference

In case you want the difference recursively going deep into items of your list, I have written a package for python:


Install from PyPi:

pip install deepdiff

If you are Python3 you need to also install:

pip install future six

Example usage

>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function

Same object returns empty

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> ddiff = DeepDiff(t1, t2)
>>> print (ddiff.changes)

Type of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> ddiff = DeepDiff(t1, t2)
>>> print (ddiff.changes)
    {'type_changes': ["root[2]: 2=<type 'int'> vs. 2=<type 'str'>"]}

Value of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> ddiff = DeepDiff(t1, t2)
>>> print (ddiff.changes)
    {'values_changed': ['root[2]: 2 ====>> 4']}

Item added and/or removed

>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes)
    {'dic_item_added': ['root[5, 6]'],
     'dic_item_removed': ['root[4]'],
     'values_changed': ['root[2]: 2 ====>> 4']}

String difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
    { 'values_changed': [ 'root[2]: 2 ====>> 4',
                          "root[4]['b']:\n--- \n+++ \n@@ -1 +1 @@\n-world\n+world!"]}
>>> print (ddiff.changes['values_changed'][1])
    @@ -1 +1 @@

String difference 2

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
    { 'values_changed': [ "root[4]['b']:\n--- \n+++ \n@@ -1,5 +1,4 @@\n-world!\n-Goodbye!\n+world\n 1\n 2\n End"]}
>>> print (ddiff.changes['values_changed'][0])
    @@ -1,5 +1,4 @@

Type change

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
    { 'type_changes': [ "root[4]['b']: [1, 2, 3]=<type 'list'> vs. world\n\n\nEnd=<type 'str'>"]}

List difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
    { 'list_removed': ["root[4]['b']: [3]"]}

List difference 2: Note that it DOES NOT take order into account

>>> # Note that it DOES NOT take order into account
... t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
    { }

List that contains dictionary:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
    { 'dic_item_removed': ["root[4]['b'][2][2]"],
      'values_changed': ["root[4]['b'][2][1]: 1 ====>> 3"]}

SQL Server: converting UniqueIdentifier to string in a case statement

Instead of Str(RequestID), try convert(varchar(38), RequestID)

How to get just one file from another branch

Everything is much simpler, use git checkout for that.

Suppose you're on master branch, to get app.js from new-feature branch do:

git checkout new-feature path/to/app.js

// note that there is no leading slash in the path!

This will bring you the contents of the desired file. You can, as always, use part of sha1 instead of new-feature branch name to get the file as it was in that particular commit.

Note:new-feature needs to be a local branch, not a remote one.

Deprecated Java HttpClient - How hard can it be?

I would suggest using the below method if you are trying to read the json data only.

URL requestUrl=new URL(url);
URLConnection con = requestUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
int cp;
try {
 catch(Exception e){
 String json=sb.toString();

Comments in Markdown

You can try

Your comments go here however you cannot leave
// a blank line so fill blank lines with

How to find the nearest parent of a Git branch?

An alternative: git rev-list master | grep "$(git rev-list HEAD)" | head -1

Get the last commit that it's both my branch and master (or whatever branch you want to specify)

How to change the status bar color in Android?

i used this code to change status bar to transparent


to change it to color in style used this code i used in fragment in onDetach()


Jquery post, response in new window

Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:

$.post(url, function (data) {
    var w ='about:blank', 'windowname');

Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)

What is the parameter "next" used for in Express?

It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an id was given, and assign it to req.user.

Below, you could have a route like:

app.get('/users', function(req, res) {
  // check for and maybe do something with req.user

Since /users/123 will match the route in your example first, that will first check and find user 123; then /users can do something with the result of that.

Route middleware is a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a Users model with an async findOne():

function loadUser(req, res, next) {
  if (req.params.userId) {
    Users.findOne({ id: req.params.userId }, function(err, user) {
      if (err) {
        next(new Error("Couldn't find user: " + err));

      req.user = user;
  } else {

// ...

app.get('/user/:userId', loadUser, function(req, res) {
  // do something with req.user

app.get('/users/:userId?', loadUser, function(req, res) {
  // if req.user was set, it's because userId was specified (and we found the user).

// Pretend there's a "loadItem()" which operates similarly, but with itemId.
app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {

Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:

 * Only allows the page to be accessed if the user is an admin.
 * Requires use of `loadUser` middleware.
function requireAdmin(req, res, next) {
  if (!req.user || !req.user.admin) {
    next(new Error("Permission denied."));


app.get('/top/secret', loadUser, requireAdmin, function(req, res) {

Hope this gave you some inspiration!

How do I vertically center an H1 in a div?

Just use padding top and bottom, it will automatically center the content vertically.

How do I load external fonts into an HTML document?

I did not see any reference to Raphael.js. So I thought I'd include it here. Raphael.js is backwards compatible all the way back to IE5 and a very early Firefox as well as all of the rest of the browsers. It uses SVG when it can and VML when it can not. What you do with it is to draw onto a canvas. Some browsers will even let you select the text that is generated. Raphael.js can be found here:

It can be as simple as creating your paper drawing area, specifying the font, font-weight, size, etc... and then telling it to put your string of text onto the paper. I am not sure if it gets around the licensing issues or not but it is drawing the text so I'm fairly certain it does circumvent the licensing issues. But check with your lawyer to be sure. :-)

How to move div vertically down using CSS

A standard width space for a standard 16px font is 4px.


Selenium WebDriver.get(url) does not open the URL

This worked for me (Tested on Ubuntu Desktop 11.04 with Python-2.7):

from selenium import webdriver

driver = webdriver.Firefox()

jQuery hover and class selector

This can be achieved in CSS using the :hover pseudo-class. (:hover doesn't work on <div>s in IE6)


<div id="menu">
   <a class="menuItem" href=#>Bla</a>
   <a class="menuItem" href=#>Bla</a>
   <a class="menuItem" href=#>Bla</a>


.menuItem:hover {

Split string on the first white space occurrence

I'm not sure why all other answers are so complicated, when you can do it all in one line, handling the lack of space as well.

As an example, let's get the first and "rest" components of a name:

const [first, rest] = 'John Von Doe'.split(/\s+(.*)/);
console.log({ first, rest });

// As array
const components = 'Surma'.split(/\s+(.*)/);

Access an arbitrary element in a dictionary in Python

How about, this. Not mentioned here yet.

py 2 & 3

a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2

jQuery get the image src

src should be in quotes:

$('.img1 img').attr('src');

How can I tell jackson to ignore a property for which I don't have control over the source code?

Annotation based approach is better. But sometimes manual operation is needed. For this purpose you can use without method of ObjectWriter.

ObjectMapper mapper   = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
ObjectWriter writer   = mapper.writer().withoutAttribute("property1").withoutAttribute("property2");
String       jsonText = writer.writeValueAsString(sourceObject);

how to bind datatable to datagridview in c#

Even better:

DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();

ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;

ServersTable.DataSource = SBind;

You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.

How do I provide a username and password when running "git clone [email protected]"?

This is an excellent Stack Overflow question, and the answers have been very instructive, such that I was able to resolve an annoying problem I ran into recently.

The organization that I work for uses Atlassian's BitBucket product (not Github), essentially their version of GitHub so that repositories can be secured completely on premise. I was running into a similar problem as @coordinate, in that my password was required for a new repository I checked out. My credentials had been saved globally for all BitBucket projects, so I'm not sure what prompted the loss of credentials.

In short, I was able to enter the following GIT command (supplying only my username), which then prompted Git's Credential Manager to prompt me for the password, which I was then able to save.

git clone https://[email protected]/git/[organization]/[team]/[repository.git]

NOTE: the bracketed directory sub-paths simply refer to internal references, and will vary for you!

How can I URL encode a string in Excel VBA?

Version of the above supporting UTF8:

Private Const CP_UTF8 = 65001

#If VBA7 Then
  Private Declare PtrSafe Function WideCharToMultiByte Lib "kernel32" ( _
    ByVal CodePage As Long, _
    ByVal dwFlags As Long, _
    ByVal lpWideCharStr As LongPtr, _
    ByVal cchWideChar As Long, _
    ByVal lpMultiByteStr As LongPtr, _
    ByVal cbMultiByte As Long, _
    ByVal lpDefaultChar As Long, _
    ByVal lpUsedDefaultChar As Long _
    ) As Long
  Private Declare Function WideCharToMultiByte Lib "kernel32" ( _
    ByVal CodePage As Long, _
    ByVal dwFlags As Long, _
    ByVal lpWideCharStr As Long, _
    ByVal cchWideChar As Long, _
    ByVal lpMultiByteStr As Long, _
    ByVal cbMultiByte As Long, _
    ByVal lpDefaultChar As Long, _
    ByVal lpUsedDefaultChar As Long _
    ) As Long
#End If

Public Function UTF16To8(ByVal UTF16 As String) As String
Dim sBuffer As String
Dim lLength As Long
If UTF16 <> "" Then
    #If VBA7 Then
        lLength = WideCharToMultiByte(CP_UTF8, 0, CLngPtr(StrPtr(UTF16)), -1, 0, 0, 0, 0)
        lLength = WideCharToMultiByte(CP_UTF8, 0, StrPtr(UTF16), -1, 0, 0, 0, 0)
    #End If
    sBuffer = Space$(lLength)
    #If VBA7 Then
        lLength = WideCharToMultiByte(CP_UTF8, 0, CLngPtr(StrPtr(UTF16)), -1, CLngPtr(StrPtr(sBuffer)), LenB(sBuffer), 0, 0)
        lLength = WideCharToMultiByte(CP_UTF8, 0, StrPtr(UTF16), -1, StrPtr(sBuffer), LenB(sBuffer), 0, 0)
    #End If
    sBuffer = StrConv(sBuffer, vbUnicode)
    UTF16To8 = Left$(sBuffer, lLength - 1)
    UTF16To8 = ""
End If
End Function

Public Function URLEncode( _
   StringVal As String, _
   Optional SpaceAsPlus As Boolean = False, _
   Optional UTF8Encode As Boolean = True _
) As String

Dim StringValCopy As String: StringValCopy = IIf(UTF8Encode, UTF16To8(StringVal), StringVal)
Dim StringLen As Long: StringLen = Len(StringValCopy)

If StringLen > 0 Then
    ReDim Result(StringLen) As String
    Dim I As Long, CharCode As Integer
    Dim Char As String, Space As String

  If SpaceAsPlus Then Space = "+" Else Space = "%20"

  For I = 1 To StringLen
    Char = Mid$(StringValCopy, I, 1)
    CharCode = Asc(Char)
    Select Case CharCode
      Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
        Result(I) = Char
      Case 32
        Result(I) = Space
      Case 0 To 15
        Result(I) = "%0" & Hex(CharCode)
      Case Else
        Result(I) = "%" & Hex(CharCode)
    End Select
  Next I
  URLEncode = Join(Result, "")

End If
End Function


How to read response headers in angularjs?

Why not simply try this:

var promise = $http.get(url, {
    params: query
}).then(function(response) {
  console.log('Content-Range: ' + response.headers('Content-Range'));

Especially if you want to return the promise so it could be a part of a promises chain.

Format number to 2 decimal places

This is how I used this is as an example:

CAST(vAvgMaterialUnitCost.`avgUnitCost` AS DECIMAL(11,2)) * woMaterials.`qtyUsed` AS materialCost

App.Config Transformation for projects which are not Web Projects in Visual Studio?

So I ended up taking a slightly different approach. I followed Dan's steps through step 3, but added another file: App.Base.Config. This file contains the configuration settings you want in every generated App.Config. Then I use BeforeBuild (with Yuri's addition to TransformXml) to transform the current configuration with the Base config into the App.config. The build process then uses the transformed App.config as normal. However, one annoyance is you kind of want to exclude the ever-changing App.config from source control afterwards, but the other config files are now dependent upon it.

  <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
  <Target Name="BeforeBuild" Condition="exists('app.$(Configuration).config')">
    <TransformXml Source="App.Base.config" Transform="App.$(Configuration).config" Destination="App.config" />

Sublime Text 2 multiple line edit

Worked for me on OS X + Sublime build 3083:

OPTION (ALT) + select lines

How to check if my string is equal to null?

You can check string equal to null using this:

String Test = null;

If the result is 0 then (Test+"") = "null".

Targeting only Firefox with CSS

Now that Firefox Quantum 57 is out with substantial — and potentially breaking — improvements to Gecko collectively known as Stylo or Quantum CSS, you may find yourself in a situation where you have to distinguish between legacy versions of Firefox and Firefox Quantum.

From my answer here:

You can use @supports with a calc(0s) expression in conjunction with @-moz-document to test for Stylo — Gecko does not support time values in calc() expressions but Stylo does:

@-moz-document url-prefix() {
  @supports (animation: calc(0s)) {
    /* Stylo */

Here's a proof-of-concept:

body::before {_x000D_
  content: 'Not Fx';_x000D_
@-moz-document url-prefix() {_x000D_
  body::before {_x000D_
    content: 'Fx legacy';_x000D_
  @supports (animation: calc(0s)) {_x000D_
    body::before {_x000D_
      content: 'Fx Quantum';_x000D_

Targeting legacy versions of Firefox is a little tricky — if you're only interested in versions that support @supports, which is Fx 22 and up, @supports not (animation: calc(0s)) is all you need:

@-moz-document url-prefix() {
  @supports not (animation: calc(0s)) {
    /* Gecko */

... but if you need to support even older versions, you'll need to make use of the cascade, as demonstrated in the proof-of-concept above.

When should I use GET or POST method? What's the difference between them?

The GET method:

  • It is used only for sending 256 character date

  • When using this method, the information can be seen on the browser

  • It is the default method used by forms

  • It is not so secured.

The POST method:

  • It is used for sending unlimited data.

  • With this method, the information cannot be seen on the browser

  • You can explicitly mention the POST method

  • It is more secured than the GET method

  • It provides more advanced features

How to install JDK 11 under Ubuntu?

Just updated older Ubuntu versions to openJDK 11
Actually I need it for Jenkins only and it seems to work fine.

Ubuntu 12.04 (Precise):
Download from openjdk-lts (11.0.4+11-1~12.04) precise

Ubuntu 14.04 (Trusty):
Download from openjdk-lts (11.0.5+10-2ubuntu1~14.04) trusty

After download I installed the files with Ubuntu Software Center ("headless" first!)
Then I selected the new version with sudo update-alternatives --config java

I didn't have to change any environment variables (like JAVA_HOME) - maybe Jenkins doesn't care about them...

How to close IPython Notebook properly?

Step 1 - On shell just do control+z (control+c) Step 2 _ close the web browser

Where to place and how to read configuration resource files in servlet based application?

You can you with your source folder so whenever you build, those files are automatically copied to the classes directory.

Instead of using properties file, use XML file.

If the data is too small, you can even use web.xml for accessing the properties.

Please note that any of these approach will require app server restart for changes to be reflected.

Graphviz: How to go from .dot to a graph?

You can also output your file in xdot format, then render it in a browser using canviz, a JavaScript library.

Canviz on

To see an example, there is a "Canviz Demo" link on the page above as of November 2, 2014.

How do I draw a set of vertical lines in gnuplot?

alternatively you can also do this:

p '< echo "x y"' w impulse

x and y are the coordinates of the point to which you draw a vertical bar

how to mysqldump remote db from local machine

Bassed on this page here:

Compare two MySQL databases

I modified it so you can use ddbb in diferent hosts.


echo "Usage: dbdiff [user1:pass1@dbname1:host] [user2:pass2@dbname2:host] [ignore_table1:ignore_table2...]"

dump () {
  up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
  mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname -h $host $table > $2

rm -f /tmp/db.diff

# Compare
up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
for table in `mysql -u $user -p$pass $dbname -h $host -N -e "show tables" --batch`; do
  if [ "`echo $3 | grep $table`" = "" ]; then
    echo "Comparing '$table'..."
    dump $1 /tmp/file1.sql
    dump $2 /tmp/file2.sql
    diff -up /tmp/file1.sql /tmp/file2.sql >> /tmp/db.diff
    echo "Ignored '$table'..."
less /tmp/db.diff
rm -f /tmp/file1.sql /tmp/file2.sql

Set cellpadding and cellspacing in CSS?

Say that we want to assign a 10px "cellpadding" and a 15px "cellspacing" to our table, in a HTML5-compliant way. I will show here two methods giving really similar outputs.

Two different sets of CSS properties apply to the same HTML markup for the table, but with opposite concepts:

  • the first one uses the default value for border-collapse (separate) and uses border-spacing to provide the cellspacing,

  • the second one switches border-collapse to collapse and uses the border property as the cellspacing.

In both cases, the cellpadding is achieved by assigning padding:10px to the tds and, in both cases, the background-color assigned to them is only for the sake of a clearer demo.

First method:

<td>Header 1</td><td>Header 2</td>

Second method:

td{background-color:#00eb55;padding:10px;border:15px solid #fff}
<td>Header 1</td><td>Header 2</td>

What does "javascript:void(0)" mean?

From what I've seen, the void operator has 3 common uses in JavaScript. The one that you're referring to, <a href="javascript:void(0)"> is a common trick to make an <a> tag a no-op. Some browsers treat <a> tags differently based on whether they have a href , so this is a way to create a link with a href that does nothing.

The void operator is a unary operator that takes an argument and returns undefined. So var x = void 42; means x === undefined. This is useful because, outside of strict mode, undefined is actually a valid variable name. So some JavaScript developers use void 0 instead of undefined. In theory, you could also do <a href="javascript:undefined"> and it would so the same thing as void(0).

Speed up rsync with Simultaneous/Concurrent File Transfers?

Have you tried using

With rclone you could do something like

rclone copy "${source}/${subfolder}/" "${target}/${subfolder}/" --progress --multi-thread-streams=N

where --multi-thread-streams=N represents the number of threads you wish to spawn.

How do I mock a class without an interface?

Most mocking frameworks (Moq and RhinoMocks included) generate proxy classes as a substitute for your mocked class, and override the virtual methods with behavior that you define. Because of this, you can only mock interfaces, or virtual methods on concrete or abstract classes. Additionally, if you're mocking a concrete class, you almost always need to provide a parameterless constructor so that the mocking framework knows how to instantiate the class.

Why the aversion to creating interfaces in your code?

Updating .class file in jar

You can find source code of any .jar file online, import the same project in your IDE with basic setups. Make necessary changes in .java file and compile it for .class files.

Once compilation is done You need to extract the jar file, replace the old .class file with new one.

And use below command for reconstruct .jar file

Jar cf test.jar *

Note : I have done so many time this changes in our project, hope you will find it useful.

How to do a HTTP HEAD request from the windows command line?

I'd download PuTTY and run a telnet session on port 80 to the webserver you want

HEAD /resource HTTP/1.1

You could alternatively download Perl and try LWP's HEAD command. Or write your own script.

How do I exclude Weekend days in a SQL Server query?

Try this code

select (DATEDIFF(DD,'2014-08-01','2014-08-14')+1)- (DATEDIFF(WK,'2014-08-01','2014-08-14')* 2)

Multiple Where clauses in Lambda expressions

You can include it in the same where statement with the && operator...

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty 
    && l.InternalName != String.Empty)

You can use any of the comparison operators (think of it like doing an if statement) such as...

List<Int32> nums = new List<int>();


var results = nums.Where(x => x == 3 || x == 10);

...would bring back 3 and 10.

How can I change the font-size of a select option?

We need a trick here...

Normal select-dropdown things won't accept styles. BUT. If there's a "size" parameter in the tag, almost any CSS will apply. With this in mind, I've created a fiddle that's practically equivalent to a normal select tag, plus the value can be edited manually like a ComboBox in visual languages (unless you put readonly in the input tag).

A simplified example:


    /* only these 2 lines are truly required */
    .stylish span {position:relative;}
    .stylish select {position:absolute;left:0px;display:none}

    /* now you can style the hell out of them */
    .stylish input    { ... }
    .stylish select   { ... }
    .stylish option   { ... }
    .stylish optgroup { ... }

<div class="stylish">
    <label> Choose your superhero: </label>
        <input onclick="$(this).closest('div').find('select').slideToggle(110)">
        <select size=15 onclick="$(this).hide().closest('div').find('input').val($(this).find('option:selected').text());">

            <optgroup label="Fantasy"></optgroup>
            <option value="gandalf">Gandalf</option>
            <option value="harry">Harry Potter</option>
            <option value="jon">Jon Snow</option>

            <optgroup label="Comics"></optgroup>
            <option value="tony">Tony Stark</option>
            <option value="steve">Steven Rogers</option>
            <option value="natasha">Natasha Romanova</option>


        For the sake of simplicity, I used jQuery here.
        Today it's easy to do the same without it, now
        that we have querySelector(), closest(), etc.


A live example:

Note 1: Sorry for the gradients & all fancy stuff, no they're not necessary, yes I'm showing off, I know, hashtag onlyhuman, hashtag notproud.

Note 2: Those <optgroup> tags don't encapsulate the options belonging under them as they normally should; this is intentional. It's better for the styling (the well-mannered way would be a lot less stylable), and yes this is painless and works in every browser.

How to change the Jupyter start-up folder

Easy way!

1 - Type jupyer notebook in start menu


2 - Make shortcut on desktop of jupyter notebook ( Right click mouse!)


3 - Only drag and drop your favorite folder in the shortcut

compare differences between two tables in mysql

I found another solution in this link

SELECT MIN (tbl_name) AS tbl_name, PK, column_list
  SELECT ' source_table ' as tbl_name, S.PK, S.column_list
  FROM source_table AS S
  SELECT 'destination_table' as tbl_name, D.PK, D.column_list
  FROM destination_table AS D 
)  AS alias_table
GROUP BY PK, column_list

How do I get the day of week given a date?

import datetime

this should give you your real day number - 1 = sunday, 2 = monday, etc...

How to merge a transparent png image with another image using PIL

from PIL import Image

background ="test1.png")
foreground ="test2.png")

background.paste(foreground, (0, 0), foreground)

First parameter to .paste() is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a mask that will be used to paste the image. If you pass a image with transparency, then the alpha channel is used as mask.

Check the docs.

How do you change the datatype of a column in SQL Server?

For changing data type

alter table table_name 
alter column column_name datatype [NULL|NOT NULL]

For changing Primary key

ALTER TABLE table_name  

JavaScript Promises - reject vs. throw

Yes, the biggest difference is that reject is a callback function that gets carried out after the promise is rejected, whereas throw cannot be used asynchronously. If you chose to use reject, your code will continue to run normally in asynchronous fashion whereas throw will prioritize completing the resolver function (this function will run immediately).

An example I've seen that helped clarify the issue for me was that you could set a Timeout function with reject, for example:

new Promise((resolve, reject) => {
  setTimeout(()=>{reject('err msg');console.log('finished')}, 1000);
  return resolve('ret val')
.then((o) => console.log("RESOLVED", o))
.catch((o) => console.log("REJECTED", o));

The above could would not be possible to write with throw.

  new Promise((resolve, reject) => {
    setTimeout(()=>{throw new Error('err msg')}, 1000);
    return resolve('ret val')
  .then((o) => console.log("RESOLVED", o))
  .catch((o) => console.log("REJECTED", o));
  console.log("IGNORED", o)

In the OP's small example the difference in indistinguishable but when dealing with more complicated asynchronous concept the difference between the two can be drastic.

How do you generate a random double uniformly distributed between 0 and 1 from C++?

An old school solution like:

double X=((double)rand()/(double)RAND_MAX);

Should meet all your criteria (portable, standard and fast). obviously the random number generated has to be seeded the standard procedure is something like:


C# - How to add an Excel Worksheet programmatically - Office XP / 2003

Do not forget to include Reference to Microsoft Excel 12.0/11.0 object Library

using Excel = Microsoft.Office.Interop.Excel;
// Include this Namespace

Microsoft.Office.Interop.Excel.Application xlApp = null;
Excel.Workbook xlWorkbook = null;
Excel.Sheets xlSheets = null;
Excel.Worksheet xlNewSheet = null;
string worksheetName ="Sheet_Name";
object readOnly1 = false;

object isVisible = true;

object missing = System.Reflection.Missing.Value;

    xlApp = new Microsoft.Office.Interop.Excel.Application();

    if (xlApp == null)

    // Uncomment the line below if you want to see what's happening in Excel
    // xlApp.Visible = true;

    xlWorkbook = xlApp.Workbooks.Open(@"C:\Book1.xls", missing, readOnly1, missing, missing, missing, missing, missing, missing, missing, missing, isVisible, missing, missing, missing);

    xlSheets = (Excel.Sheets)xlWorkbook.Sheets;

    // The first argument below inserts the new worksheet as the first one
    xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
    xlNewSheet.Name = worksheetName;

    xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
    //xlApp = null;

Checking if a list of objects contains a property with a specific value

using System.Linq;    
list.Where(x=> x.Name == nameToExtract);

Edit: misread question (now all matches)

How to understand nil vs. empty vs. blank in Ruby

Don't forget any? which is generally !empty?. In Rails I typically check for the presence of something at the end of a statement with if something or unless something then use blank? where needed since it seems to work everywhere.

How to Completely Uninstall Xcode and Clear All Settings

Before taking such drastic measures, quit Xcode and follow all the instructions here for cleaning out the caches:

How to Empty Caches and Clean All Targets Xcode 4

If that doesn't help, and you decide you really need a clean installation of Xcode, then, in addition to all of the stuff in that answer, trash the Xcode app itself, plus trash your ~/Library/Developer folder and your ~/Library/Preferences/ file. I think that should just about do it.

Bootstrap modal appearing under background

This problem can often be experienced when using things like gradients in CSS for things like backgrounds or even accordion headers.

Unfortunately, modifying or overriding core Bootstrap CSS is undesirable, and can lead to unwanted side effects. The least intrusive approach is to add data-backdrop="false" but you may notice that the fade effect no longer works as expected.

After following recent releases of Bootstrap, version 3.3.5 seems to resolve this issue with no unwanted side effects.


Be sure to include the CSS files and JavaScript files from 3.3.5.

C convert floating point to int

Use in C

int C = var_in_float;

They will convert implicit

Creating a thumbnail from an uploaded image

I'm guessing you have already figured this one out. But I see that you are storing the images as "longblobs" leading me to think you are storing the entire binary content of the pic.

I hope you have realized that it makes much more sense to simply store the file names in your DB and then use that info to grab the pics out of an "upload" folder or similar.

TIP - dont save a file path.. just the file name .. add the path info in your code as needed. That way you have the most freedom down the line. If you need to change folder structure, you can do it in your code rather than changing DB records.

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

The way to do this in .NET Core is (at the time of writing) as follows:

public async Task<IActionResult> YourAction(YourModel model)
    if (ModelState.IsValid)
        return StatusCode(200);

    return StatusCode(400);

The StatusCode method returns a type of StatusCodeResult which implements IActionResult and can thus be used as a return type of your action.

As a refactor, you could improve readability by using a cast of the HTTP status codes enum like:

return StatusCode((int)HttpStatusCode.OK);

Furthermore, you could also use some of the built in result types. For example:

return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON

Ref. StatusCodeResult -

Entity Framework 5 Updating a Record

I have added an extra update method onto my repository base class that's similar to the update method generated by Scaffolding. Instead of setting the entire object to "modified", it sets a set of individual properties. (T is a class generic parameter.)

public void Update(T obj, params Expression<Func<T, object>>[] propertiesToUpdate)

    foreach (var p in propertiesToUpdate)
        Context.Entry(obj).Property(p).IsModified = true;

And then to call, for example:

public void UpdatePasswordAndEmail(long userId, string password, string email)
    var user = new User {UserId = userId, Password = password, Email = email};

    Update(user, u => u.Password, u => u.Email);


I like one trip to the database. Its probably better to do this with view models, though, in order to avoid repeating sets of properties. I haven't done that yet because I don't know how to avoid bringing the validation messages on my view model validators into my domain project.

Capturing standard out and error with Start-Process


We have been using the function as provided above by LPG.

However, this contains a bug you might encounter when you start a process that generates a lot of output. Due to this you might end up with a deadlock when using this function. Instead use the adapted version below:

Function Execute-Command ($commandTitle, $commandPath, $commandArguments)
  Try {
    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = $commandPath
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = $commandArguments
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
        commandTitle = $commandTitle
        stdout = $p.StandardOutput.ReadToEnd()
        stderr = $p.StandardError.ReadToEnd()
        ExitCode = $p.ExitCode
  Catch {

Further information on this issue can be found at MSDN:

A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardError.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardError stream.

What is the best open XML parser for C++?

TinyXML, and also Boost.PropertyTree. The latter does not fulfill all official requirements, but is very simple.

How to use sha256 in php5.3.0

First of all, sha256 is a hashing algorithm, not a type of encryption. An encryption would require having a way to decrypt the information back to its original value (collisions aside).

Looking at your code, it seems it should work if you are providing the correct parameter.

  • Try using a literal string in your code first, and verify its validity instead of using the $_POST[] variable

  • Try moving the comparison from the database query to the code (get the hash for the given user and compare to the hash you have just calculated)

But most importantly before deploying this in any kind of public fashion, please remember to sanitize your inputs. Don't allow arbitrary SQL to be insert into the queries. The best idea here would be to use parameterized queries.

How to calculate the intersection of two sets?

Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor

The javadoc of retainAll() says it's exactly what you want:

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

How to subtract 30 days from the current date using SQL Server


Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

       CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
       AS DATETIME))

Does Python have an ordered set?

If you're using the ordered set to maintain a sorted order, consider using a sorted set implementation from PyPI. The sortedcontainers module provides a SortedSet for just this purpose. Some benefits: pure-Python, fast-as-C implementations, 100% unit test coverage, hours of stress testing.

Installing from PyPI is easy with pip:

pip install sortedcontainers

Note that if you can't pip install, simply pull down the and files from the open-source repository.

Once installed you can simply:

from sortedcontainers import SortedSet

The sortedcontainers module also maintains a performance comparison with several alternative implementations.

For the comment that asked about Python's bag data type, there's alternatively a SortedList data type which can be used to efficiently implement a bag.

How to Round to the nearest whole number in C#

Write your own round method. Something like,

function round(x) rx = Math.ceil(x) if (rx - x <= .000001) return int(rx) else return int(x) end

How to disable spring security for particular url

I have a better way:


ComboBox- SelectionChanged event has old value, not new value

This should work for you ...

int myInt= ((data)(((object[])(e.AddedItems))[0])).kid;

What static analysis tools are available for C#?

Have you seen CAT.NET?

From the blurb -

CAT.NET is a binary code analysis tool that helps identify common variants of certain prevailing vulnerabilities that can give rise to common attack vectors such as Cross-Site Scripting (XSS), SQL Injection and XPath Injection.

I used an early beta and it did seem to turn up a few things worth looking at.

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

In my case, I commited a spell mistake in @Named("beanName"), it was suppose to be "beanName", but I wrote "beanNam", for example.

AngularJs event to call after content is loaded

The solution that work for me is the following

app.directive('onFinishRender', ['$timeout', '$parse', function ($timeout, $parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    if (!!attr.onFinishRender) {

            if (!!attr.onStartRender) {
                if (scope.$first === true) {
                    $timeout(function () {
                        if (!!attr.onStartRender) {

Controller code is the following

$scope.crearTooltip = function () {

Html code is the following

<tr ng-repeat="item in $data" on-finish-render="crearTooltip()">

jquery : focus to div is not working

a <div> can be focused if it has a tabindex attribute. (the value can be set to -1)

For example:


In addition, consider setting outline: none !important; so it displayed without a focus rectangle.

var element = $("#focus_point");
element.css('outline', 'none !important')
       .attr("tabindex", -1)

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/ libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

xxxxxx.exe is not a valid Win32 application

There are at least two solutions:

  1. You need Visual Studio 2010 installed, then from Visual Studio 2010, View -> Solution Explorer -> Right Click on your project -> Choose Properties from the context menu, you'll get the windows "your project name" Property Pages -> Configuration Properties -> General -> Platform toolset, choose "Visual Studio 2010 (v100)".
  2. You need the Visual Studio 2012 Update 1 described in Windows XP Targeting with C++ in Visual Studio 2012

How do you properly use namespaces in C++?

I prefer using a top-level namespace for the application and sub namespaces for the components.

The way you can use classes from other namespaces is surprisingly very similar to the way in java. You can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.

MyISAM versus InnoDB

I think this is an excellent article on explaining the differences and when you should use one over the other:

Adding event listeners to dynamically added elements using jQuery

Using .on() you can define your function once, and it will execute for any dynamically added elements.

for example

$('#staticDiv').on('click', 'yourSelector', function() {
  //do something

Tokenizing strings in C

When reading the strtok documentation, I see you need to pass in a NULL pointer after the first "initializing" call. Maybe you didn't do that. Just a guess of course.

How to detect my browser version and operating system using JavaScript?

Try this one..

// Browser with version  Detection
navigator.sayswho= (function(){
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    return M;

var browser_version          = navigator.sayswho;
alert("Welcome to " + browser_version);

check out the working fiddle ( here )

What is the significance of 1/1/1753 in SQL Server?

This is whole story how date problem was and how Big DBMSs handled these problems.

During the period between 1 A.D. and today, the Western world has actually used two main calendars: the Julian calendar of Julius Caesar and the Gregorian calendar of Pope Gregory XIII. The two calendars differ with respect to only one rule: the rule for deciding what a leap year is. In the Julian calendar, all years divisible by four are leap years. In the Gregorian calendar, all years divisible by four are leap years, except that years divisible by 100 (but not divisible by 400) are not leap years. Thus, the years 1700, 1800, and 1900 are leap years in the Julian calendar but not in the Gregorian calendar, while the years 1600 and 2000 are leap years in both calendars.

When Pope Gregory XIII introduced his calendar in 1582, he also directed that the days between October 4, 1582, and October 15, 1582, should be skipped—that is, he said that the day after October 4 should be October 15. Many countries delayed changing over, though. England and her colonies didn't switch from Julian to Gregorian reckoning until 1752, so for them, the skipped dates were between September 4 and September 14, 1752. Other countries switched at other times, but 1582 and 1752 are the relevant dates for the DBMSs that we're discussing.

Thus, two problems arise with date arithmetic when one goes back many years. The first is, should leap years before the switch be calculated according to the Julian or the Gregorian rules? The second problem is, when and how should the skipped days be handled?

This is how the Big DBMSs handle these questions:

  • Pretend there was no switch. This is what the SQL Standard seems to require, although the standard document is unclear: It just says that dates are "constrained by the natural rules for dates using the Gregorian calendar"—whatever "natural rules" are. This is the option that DB2 chose. When there is a pretence that a single calendar's rules have always applied even to times when nobody heard of the calendar, the technical term is that a "proleptic" calendar is in force. So, for example, we could say that DB2 follows a proleptic Gregorian calendar.
  • Avoid the problem entirely. Microsoft and Sybase set their minimum date values at January 1, 1753, safely past the time that America switched calendars. This is defendable, but from time to time complaints surface that these two DBMSs lack a useful functionality that the other DBMSs have and that the SQL Standard requires.
  • Pick 1582. This is what Oracle did. An Oracle user would find that the date-arithmetic expression October 15 1582 minus October 4 1582 yields a value of 1 day (because October 5–14 don't exist) and that the date February 29 1300 is valid (because the Julian leap-year rule applies). Why did Oracle go to extra trouble when the SQL Standard doesn't seem to require it? The answer is that users might require it. Historians and astronomers use this hybrid system instead of a proleptic Gregorian calendar. (This is also the default option that Sun picked when implementing the GregorianCalendar class for Java—despite the name, GregorianCalendar is a hybrid calendar.)

Source 1 and 2

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

If you have multiple projects in solution, then setUp project as started where you have your truth App.config.

Java - How to create new Entry (key, value)

You could actually go with: Map.Entry<String, String> en= Maps.immutableEntry(key, value);

How to set JFrame to appear centered, regardless of monitor resolution?

As simple as this...

setSize(220, 400);

or if you are using a frame then set the frame to

frame.setSize(220, 400);

For clarification, from the docs:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Margin is the spacing outside your element, just as padding is the spacing inside your element.

Setting the bottom margin indicates what distance you want below the current block. Setting a negative top margin indicates that you want negative spacing above your block. Negative spacing may in itself be a confusing concept, but just the way positive top margin pushes content down, a negative top margin pulls content up.

How to identify numpy types in python?

Note that the type(numpy.ndarray) is a type itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.

See also: - -

>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
>>> type(a) == np.ndarray
>>> isinstance(a, np.ndarray)

Fun with booleans:

>>> b = a.astype('int32') == 11
>>> b[0]
>>> isinstance(b[0], bool)
>>> isinstance(b[0], np.bool)
>>> isinstance(b[0], np.bool_)
>>> isinstance(b[0], np.bool8)
>>> b[0].dtype == np.bool
>>> b[0].dtype == bool  # python equivalent

More fun with scalar types, see: -

>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
>>> isinstance(x[0], np.uint64)
>>> isinstance(x[0], np.integer)
True  # generic integer
>>> isinstance(x[0], int)
False  # but not a python int in this case

# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind                                                                                           
>>> np.dtype('int64').kind                                                                                          
>>> np.dtype('float').kind                                                                                          
>>> np.dtype('half').kind                                                                                           

# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
>>> x[0].dtype == np.dtype(np.integer)

# Down these paths there be dragons:

# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
>>> isinstance(x[0].dtype, np.uint64)
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False  # again, confusing the .dtype with a specific dtype

# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:

>>> x[0].dtype <= np.dtype(np.uint64)
>>> x[0].dtype <= np.dtype(np.float)
>>> x[0].dtype <= np.dtype(np.half)
False  # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False  # oh boy
>>> x[0].dtype ==
False  # ya, no luck here either
>>> x[0].dtype == np.int_
False  # or here
>>> x[0].dtype == np.uint64
True  # have to end on a good note!

How to do an update + join in PostgreSQL?

First Table Name: tbl_table1 (tab1). Second Table Name: tbl_table2 (tab2).

Set the tbl_table1's ac_status column to "INACTIVE"

update common.tbl_table1 as tab1
set ac_status= 'INACTIVE' --tbl_table1's "ac_status"
from common.tbl_table2 as tab2
where tab1.ref_id= '1111111' 
and tab2.rel_type= 'CUSTOMER';

how to open Jupyter notebook in chrome on windows

step1: Go to search menu of windows and type default app.

step 2: go to WEB BROWSER title and change it to Google Chrome.

step3: Go to search menu of windows and type jupyter notebook

This will open the jupyter notebook in Google Chrome

How can I find a specific element in a List<T>?


 list.Find(item =>;

Is there an upper bound to BigInteger?

BigInteger would only be used if you know it will not be a decimal and there is a possibility of the long data type not being large enough. BigInteger has no cap on its max size (as large as the RAM on the computer can hold).

From here.

It is implemented using an int[]:

  110       /**
  111        * The magnitude of this BigInteger, in <i>big-endian</i> order: the
  112        * zeroth element of this array is the most-significant int of the
  113        * magnitude.  The magnitude must be "minimal" in that the most-significant
  114        * int ({@code mag[0]}) must be non-zero.  This is necessary to
  115        * ensure that there is exactly one representation for each BigInteger
  116        * value.  Note that this implies that the BigInteger zero has a
  117        * zero-length mag array.
  118        */
  119       final int[] mag;

From the source

From the Wikipedia article Arbitrary-precision arithmetic:

Several modern programming languages have built-in support for bignums, and others have libraries available for arbitrary-precision integer and floating-point math. Rather than store values as a fixed number of binary bits related to the size of the processor register, these implementations typically use variable-length arrays of digits.

Remove menubar from Electron app

The menu can be hidden or auto-hidden (like in Slack or VS Code - you can press Alt to show/hide the menu).

Relevant methods:

---- win.setMenu(menu) - Sets the menu as the window’s menu bar, setting it to null will remove the menu bar. (This will remove the menu completly)


---- win.setAutoHideMenuBar(hide) - Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only
when users press the single Alt key.



There is also the method for making a frameless window as shown bellow:

(no close button no anything. Can be what we want (better design))

const { BrowserWindow } = require('electron')
let win = new BrowserWindow({ width: 800, height: 600, frame: false })


Edit: (new)

win.removeMenu() Linux Windows Remove the window's menu bar.

Added win.removeMenu() to remove application menus instead of using win.setMenu(null)

That is added from v5 as per:

Electron v7 bug

For Electron 7.1.1 use Menu.setApplicationMenu instead of win.removeMenu()

as per this thread:

And the big note is: you have to call it before creating the BrowserWindow! Or it will not work!

const {app, BrowserWindow, Menu} = require('electron')


const browserWindow = new BrowserWindow({/*...*/});

UPDATE (Setting autoHideMenuBar on BrowserWindow construction)

As by @kcpr comment! We can set the property and many on the constructor

That's available on the latest stable version of electron by now which is 8.3!
But too in old versions i checked for v1, v2, v3, v4!
It's there in all versions!

As per this link

And for the v8.3

The doc link

From the doc for the option:

autoHideMenuBar Boolean (optional) - Auto hide the menu bar unless the Alt key is pressed. Default is false.

Here a snippet to illustrate it:

let browserWindow = new BrowserWindow({
    width: 800,
    height: 600,
    autoHideMenuBar: true // <<< here



This will contain a 'non-empty' value if the request was sent through HTTPS

PHP Server Variables

Granting Rights on Stored Procedure to another user of Oracle

I'm not sure that I understand what you mean by "rights of ownership".

If User B owns a stored procedure, User B can grant User A permission to run the stored procedure

GRANT EXECUTE ON b.procedure_name TO a

User A would then call the procedure using the fully qualified name, i.e.

  b.procedure_name( <<list of parameters>> );

Alternately, User A can create a synonym in order to avoid having to use the fully qualified procedure name.

CREATE SYNONYM procedure_name FOR b.procedure_name;

  procedure_name( <<list of parameters>> );

How to activate a specific worksheet in Excel?

I would recommend you to use worksheet's index instead of using worksheet's name, in this way you can also loop through sheets "dynamically"

for i=1 to thisworkbook.sheets.count
'You can add more code 
with activesheet
end with
next i

It will also, improve performance.

Show DialogFragment with animation growing from a point

Add this code on values anim


call on styles.xml

<style name="DialogScale">
    <item name="android:windowEnterAnimation">@anim/scale_in</item>
    <item name="android:windowExitAnimation">@anim/scale_out</item>

On java code: set Onclick

public void onClick(View v) {
        fab_onclick(, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
      //  Dialogs.fab_onclick(, "Scale");


setup on method:

alertDialog.getWindow().getAttributes().windowAnimations = type;

Best way to find if an item is in a JavaScript array?

[ ].has(obj)

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        return false;                       
    // writable:false,
    // enumerable:false

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

the use of 2nd arg (flag) forces comparation by value instead of reference

comparing raw objects

[o1].has(o2,true) // true if every level value is same

iptables LOG and DROP in one rule

for china GFW:

sudo iptables -I INPUT -s -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"

sudo iptables -I INPUT -s -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"

sudo iptables -I INPUT -s -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"

How to measure time taken between lines of code in python?

If you want to measure CPU time, can use time.process_time() for Python 3.3 and above:

import time
start = time.process_time()
# your code here    
print(time.process_time() - start)

First call turns the timer on, and second call tells you how many seconds have elapsed.

There is also a function time.clock(), but it is deprecated since Python 3.3 and will be removed in Python 3.8.

There are better profiling tools like timeit and profile, however time.process_time() will measure the CPU time and this is what you're are asking about.

If you want to measure wall clock time instead, use time.time().

WPF Image Dynamically changing Image source during runtime

I can think of two things:

First, try loading the image with:

string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));

Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".

Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at

how do you pass images (bitmaps) between android activities using bundles?

If you pass it as a Parcelable, you're bound to get a JAVA BINDER FAILURE error. So, the solution is this: If the bitmap is small, like, say, a thumbnail, pass it as a byte array and build the bitmap for display in the next activity. For instance:

in your calling activity...

Intent i = new Intent(this, NextActivity.class);
Bitmap b; // your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("byteArray", bs.toByteArray());

...and in your receiving activity

if(getIntent().hasExtra("byteArray")) {
    ImageView previewThumbnail = new ImageView(this);
    Bitmap b = BitmapFactory.decodeByteArray(

How to send file contents as body entity using cURL

I believe you're looking for the @filename syntax, e.g.:

strip new lines

curl --data "@/path/to/filename" http://...

keep new lines

curl --data-binary "@/path/to/filename" http://...

curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary in place of --data

Order by descending date - month, day and year

I'm guessing EventDate is a char or varchar and not a date otherwise your order by clause would be fine.

You can use CONVERT to change the values to a date and sort by that

   CONVERT(DateTime, EventDate,101)  DESC

The problem with that is, as Sparky points out in the comments, if EventDate has a value that can't be converted to a date the query won't execute.

This means you should either exclude the bad rows or let the bad rows go to the bottom of the results

To exclude the bad rows just add WHERE IsDate(EventDate) = 1

To let let the bad dates go to the bottom you need to use CASE


       WHEN IsDate(EventDate) = 1 THEN CONVERT(DateTime, EventDate,101)
       ELSE null

Split string based on regex

I suggest

l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)

Check this demo.

How can I output leading zeros in Ruby?

As stated by the other answers, "%03d" % number works pretty well, but it goes against the rubocop ruby style guide:

Favor the use of sprintf and its alias format over the fairly cryptic String#% method

We can obtain the same result in a more readable way using the following:

format('%03d', number)

Jquery submit form

You can try like:

        //perform anythng

Or even you can try like

$(".nextbutton").click(function() { 

How can I uninstall an application using PowerShell?

I found out that Win32_Product class is not recommended because it triggers repairs and is not query optimized. Source

I found this post from Sitaram Pamarthi with a script to uninstall if you know the app guid. He also supplies another script to search for apps really fast here.

Use like this: .\uninstall.ps1 -GUID {C9E7751E-88ED-36CF-B610-71A1D262E906}


param (            

 [string]$ComputerName = $env:computername,

 try {
  $returnval = ([WMICLASS]"\\$computerName\ROOT\CIMV2:win32_process").Create("msiexec `/x$AppGUID `/norestart `/qn")
 } catch {
  write-error "Failed to trigger the uninstallation. Review the error message"
 switch ($($returnval.returnvalue)){
  0 { "Uninstallation command triggered successfully" }
  2 { "You don't have sufficient permissions to trigger the command on $Computer" }
  3 { "You don't have sufficient permissions to trigger the command on $Computer" }
  8 { "An unknown error has occurred" }
  9 { "Path Not Found" }
  9 { "Invalid Parameter"}

std::cin input with spaces?

I rather use the following method to get the input:

#include <iostream>
#include <string>

using namespace std;

int main(void) {
    string name;

    cout << "Hello, Input your name please: ";
    getline(cin, name);

    return 0;

It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

It seems that your action needs k but ModelBinder can not find it (from form, or request or view data or ..) Change your action to this:

public ActionResult DetailsData(int? k)

        EmployeeContext Ec = new EmployeeContext();
        if (k != null)
           Employee emp = Ec.Employees.Single(X => X.EmpId == k.Value);

           return View(emp);
        return View();

How to include *.so library in Android Studio?

Solution 1 : Creation of a JniLibs folder

Create a folder called “jniLibs” into your app and the folders containing your *.so inside. The "jniLibs" folder needs to be created in the same folder as your "Java" or "Assets" folders.

Solution 2 : Modification of the build.gradle file

If you don’t want to create a new folder and keep your *.so files into the libs folder, it is possible !

In that case, just add your *.so files into the libs folder (please respect the same architecture as the solution 1 : libs/armeabi/.so for instance) and modify the build.gradle file of your app to add the source directory of the jniLibs.

sourceSets {
    main {
        jniLibs.srcDirs = ["libs"]

You will have more explanations, with screenshots to help you here ( Step 6 ):

EDIT It had to be jniLibs.srcDirs, not jni.srcDirs - edited the code. The directory can be a [relative] path that points outside of the project directory.

How may I reference the script tag that loaded the currently-executing script?

Consider this algorithm. When your script loads (if there are multiple identical scripts), look through document.scripts, find the first script with the correct "src" attribute, and save it and mark it as 'visited' with a data-attribute or unique className.

When the next script loads, scan through document.scripts again, passing over any script already marked as visited. Take the first unvisited instance of that script.

This assumes that identical scripts will likely execute in the order in which they are loaded, from head to body, from top to bottom, from synchronous to asynchronous.

(function () {
  var scripts = document.scripts;

  // Scan for this data-* attribute
  var dataAttr = 'data-your-attribute-here';

  var i = 0;
  var script;
  while (i < scripts.length) {
    script = scripts[i];
    if (/your_script_here\.js/i.test(script.src)
        && !script.hasAttribute(dataAttr)) {

        // A good match will break the loop before
        // script is set to null.

    // If we exit the loop through a while condition failure,
    // a check for null will reveal there are no matches.
    script = null;

   * This specific your_script_here.js script tag.
   * @type {Element|Node}
  var yourScriptVariable = null;

  // Mark the script an pass it on.
  if (script) {
    script.setAttribute(dataAttr, '');
    yourScriptVariable = script;

This will scan through all the script for the first matching script that isn't marked with the special attribute.

Then mark that node, if found, with a data-attribute so subsequent scans won't choose it. This is similar to graph traversal BFS and DFS algorithms where nodes may be marked as 'visited' to prevent revisitng.

Removing white space around a saved image in matplotlib

I found something from Arvind Pereira ( and seemed to work for me:

plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)

Ansible - Use default if a variable is not defined

The question is quite old, but what about:

- hosts: 'localhost'
    - debug:
        msg: "{{ ( a | default({})).get('nested', {}).get('var','bar') }}"

It looks less cumbersome to me...

Peak detection in a 2D array

Heres another approach that I used when doing something similar for a large telescope:

1) Search for the highest pixel. Once you have that, search around that for the best fit for 2x2 (maybe maximizing the 2x2 sum), or do a 2d gaussian fit inside the sub region of say 4x4 centered on the highest pixel.

Then set those 2x2 pixels you have found to zero (or maybe 3x3) around the peak center

go back to 1) and repeat till the highest peak falls below a noise threshold, or you have all the toes you need

Percentage width in a RelativeLayout

Interestingly enough, building on the answer from @olefevre, one can not only do 50/50 layouts with "invisible struts", but all sorts of layouts involving powers of two.

For example, here is a layout that cuts the width into four equal parts (actually three, with weights of 1, 1, 2):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:layout_height="wrap_content" >

        android:background="#000000" />

        android:layout_toLeftOf="@+id/strut" >

            android:background="#000000" />

            android:text="Far Left" />

            android:text="Near Left" />

            android:text="Right" />


What is __declspec and when do I need to use it?

It is mostly used for importing symbols from / exporting symbols to a shared library (DLL). Both Visual C++ and GCC compilers support __declspec(dllimport) and __declspec(dllexport). Other uses (some Microsoft-only) are documented in the MSDN.

Trigger event when user scroll to specific element - with jQuery

Fire scroll only once after a successful scroll

The accepted answer worked for me (90%) but I had to tweak it a little to actually fire only once.

$(window).on('scroll',function() {
            var hT = $('#comment-box-section').offset().top,
                hH = $('#comment-box-section').outerHeight(),
                wH = $(window).height(),
                wS = $(this).scrollTop();

            if (wS > ((hT+hH-wH)-500)){
                console.log('comment box section arrived! eh');
                // After Stuff


Note: By successful scroll I mean when user has scrolled to my element or in other words when my element is in view.

How to create a DataFrame from a text file in Spark

You can read a file to have an RDD and then assign schema to it. Two common ways to creating schema are either using a case class or a Schema object [my preferred one]. Follows the quick snippets of code that you may use.

Case Class approach

case class Test(id:String,name:String)
val myFile = sc.textFile("file.txt")
val df= x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()

Schema Approach

import org.apache.spark.sql.types._
val schemaString = "id name"
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, nullable=true))
val schema = StructType(fields)

val dfWithSchema ="header","false").schema(schema).csv("file.txt")

The second one is my preferred approach since case class has a limitation of max 22 fields and this will be a problem if your file has more than 22 fields!

Entity Framework Queryable async

Long story short,
IQueryable is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable expressions, and then interprets and runs the expression as a whole.
But ToList() method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync), will run imediately, because it is IQueryable followed by ToListAsync() method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerables.
Meanwhile your second method (GetAllUrls), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.

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

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

Combine multiple JavaScript files into one JS file

Just combine the text files and then use something like the YUI Compressor.

Files can be easily combined using the command cat *.js > main.js and main.js can then be run through the YUI compressor using java -jar yuicompressor-x.y.z.jar -o main.min.js main.js.

Update Aug 2014

I've now migrated to using Gulp for javascript concatenation and compression as with various plugins and some minimal configuration you can do things like set up dependencies, compile coffeescript etc as well as compressing your JS.

Inline CSS styles in React: how to implement a:hover?

Full CSS support is exactly the reason this huge amount of CSSinJS libraries, to do this efficiently, you need to generate actual CSS, not inline styles. Also inline styles are much slower in react in a bigger system. Disclaimer - I maintain JSS.

Include .so library in apk in android studio

To include native libraries you need:

  1. create "jar" file with special structure containing ".so" files;
  2. include that file in dependencies list.

To create jar file, use the following snippet:

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'

tasks.withType(Compile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)

To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

Highlight Bash/shell code in Markdown files

Using the knitr package:

```{r, engine='bash', code_block_name} ...


```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt

You can also use:

  • engine='sh' for shell
  • engine='python' for Python
  • engine='perl', engine='haskell' and a bunch of other C-like languages and even gawk, AWK, etc.

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

Efficient way to rotate a list in python

It depends on what you want to have happen when you do this:

>>> shift([1,2,3], 14)

You might want to change your:

def shift(seq, n):
    return seq[n:]+seq[:n]


def shift(seq, n):
    n = n % len(seq)
    return seq[n:] + seq[:n]

How do you access the matched groups in a JavaScript regular expression?

Get all group occurrence

let m=[], s = "something format_abc  format_def  format_ghi";_x000D_
s.replace(/(?:^|\s)format_(.*?)(?:\s|$)/g, (x,y)=> m.push(y));_x000D_

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

It is hard to get pip working on El Capitan for several reasons:

  1. OS X doesn't set some distutils variables correctly, so pip tries to install ancillary files in locations under /System/Library/. El Capitan blocks this, which is the error you are running into.
  2. OS X includes a number of outdated packages under /System/Library/. pip often wants to upgrade these but cannot on El Capitan.
  3. OS X places /System/Library/ higher in the python search order than /Library/Python/2.7/site-packages (the system-wide python package location), so even if you manage to install newer versions of some packages, the old ones still get loaded, breaking some dependencies.

There are workarounds for all of these at . But you may be best off installing your own version of Python via the standard Python installer, Homebrew or Anaconda.

fail to change placeholder color with Bootstrap 3

Bootstrap has 3 lines of CSS, within your bootstrap.css generated file that control the placeholder text color:

.form-control::-moz-placeholder {
  color: #999999;
  opacity: 1;
.form-control:-ms-input-placeholder {
  color: #999999;
.form-control::-webkit-input-placeholder {
  color: #999999;

Now if you add this to your own CSS file it won't override bootstrap's because it is less specific. So assmuning your form inside a then add that to your CSS:

form .form-control::-moz-placeholder {
  color: #fff;
  opacity: 1;
form .form-control:-ms-input-placeholder {
  color: #fff;
form .form-control::-webkit-input-placeholder {
  color: #fff;

Voila that will override bootstrap's CSS.

IIS7 Permissions Overview - ApplicationPoolIdentity

Giving access to the IIS AppPool\YourAppPoolName user may be not enough with IIS default configurations.

In my case, I still had the error HTTP Error 401.3 - Unauthorized after adding the AppPool user and it was fixed only after adding permissions to the IUSR user.

This is necessary because, by default, Anonymous access is done using the IUSR. You can set another specific user, the Application Pool or continue using the IUSR, but don't forget to set the appropriate permissions.

authentication tab

Credits to this answer: HTTP Error 401.3 - Unauthorized

Installing Homebrew on OS X

On an out of the box MacOS High Sierra 10.13.6

$ ruby -e "$(curl -fsSL"

Gives the following error:

curl performs SSL certificate verification by default, using a "bundle" of Certificate Authority (CA) public keys (CA certs). If the default bundle file isn't adequate, you can specify an alternate file using the --cacert option.

If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL).

If you'd like to turn off curl's verification of the certificate, use the -k (or --insecure) option.

HTTPS-proxy has similar options --proxy-cacert and --proxy-insecure.

Solution: Just add a k to your Curl Options

$ ruby -e "$(curl -fsSLk"

When restoring a backup, how do I disconnect all active connections?

None of these were working for me, couldn't delete or disconnect current users. Also couldn't see any active connections to the DB. Restarting SQL Server (Right click and select Restart) allowed me to do it.

Dark theme in Netbeans 7 or 8

Netbeans 8

Tools -> Options -> Appearance (Look & Feel Tab)

(NetBeans -> Preferences -> Appearance (Look & Feel Tab) on OS X)

Netbeans 7.x

Tools -> Plugins -> Available -> Dark Look and Feel - Install this plugin.

Once this plugin is installed, restarting netbeans should automatically switch to Dark Metal.

There are 2 themes that comes with this plugin - Dark Metal & Dark Nimbus

In order to switch themes, use the below option :

Tools -> Options -> Miscellaneous -> Windows -> Preferred Look & Feel option

enter image description here

Using sessions & session variables in a PHP Login Script

I always do OOP and use this class to maintain the session so u can use the function is_logged_in to check if the user is logged in or not, and if not you do what you wish to.

class Session
private $logged_in=false;
public $user_id;

function __construct() {
if($this->logged_in) {
  // actions to take right away if user is logged in
} else {
  // actions to take right away if user is not logged in

public function is_logged_in() {
   return $this->logged_in;

public function login($user) {
// database should find user based on username/password
  $this->user_id = $_SESSION['user_id'] = $user->id;
  $this->logged_in = true;

public function logout() {
$this->logged_in = false;

private function check_login() {
if(isset($_SESSION['user_id'])) {
  $this->user_id = $_SESSION['user_id'];
  $this->logged_in = true;
} else {
  $this->logged_in = false;


$session = new Session();

How do I get the App version and build number using Swift?

Xcode 8, Swift 3:

let gAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "0"
let gAppBuild = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") ?? "0"

Should try...catch go inside or outside a loop?

As long as you are aware of what you need to accomplish in the loop you could put the try catch outside the loop. But it is important to understand that the loop will then end as soon as the exception occurs and that may not always be what you want. This is actually a very common error in Java based software. People need to process a number of items, such as emptying a queue, and falsely rely on an outer try/catch statement handling all possible exceptions. They could also be handling only a specific exception inside the loop and not expect any other exception to occur. Then if an exception occurs that is not handled inside the loop then the loop will be "preemted", it ends possibly prematurely and the outer catch statement handles the exception.

If the loop had as its role in life to empty a queue then that loop very likely could end before that queue was really emptied. Very common fault.

Initializing C# auto-properties

You can do it via the constructor of your class:

public class foo {
  public foo(){
    Bar = "bar";
  public string Bar {get;set;}

If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):

public class foo {
  private foo(){
    Bar = "bar";
    Baz = "baz";
  public foo(int something) : this(){
    //do specialized initialization here
    Baz = string.Format("{0}Baz", something);
  public string Bar {get; set;}
  public string Baz {get; set;}

If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.

How to drop SQL default constraint without knowing its name?

declare @table_name nvarchar(100)
declare @col_name nvarchar(100)
declare @constraint nvarchar(100)
set @table_name = N'TableName'
set @col_name = N'ColumnName'

IF EXISTS (select       c.*
    from        sys.columns c 
    inner join  sys.tables t on t.object_id = c.object_id
    where = @table_name
    and = @col_name) 

sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where = @table_name
and = @col_name

    IF LEN(ISNULL(@constraint, '')) <> 0
        DECLARE @sqlcmd VARCHAR(MAX)
        SET @sqlcmd = 'ALTER TABLE ' + QUOTENAME(@table_name) + ' DROP CONSTRAINT' + 
        EXEC (@sqlcmd);



Razor/CSHTML - Any Benefit over what we have?

One of the benefits is that Razor views can be rendered inside unit tests, this is something that was not easily possible with the previous ASP.Net renderer.

From ScottGu's announcement this is listed as one of the design goals:

Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).

instanceof Vs getClass( )

getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code:

class ParentClass{
public class SubClass extends ParentClass{
    public static void main(String []args){
        ParentClass parentClassInstance = new ParentClass();
        SubClass subClassInstance = new SubClass();
        if(subClassInstance instanceof ParentClass){
            System.out.println("SubClass extends ParentClass. subClassInstance is instanceof ParentClass");
        if(subClassInstance.getClass() != parentClassInstance.getClass()){
            System.out.println("Different getClass() return results with subClassInstance and parentClassInstance ");


SubClass extends ParentClass. subClassInstance is instanceof ParentClass.

Different getClass() return results with subClassInstance and parentClassInstance.