Programs & Examples On #Operations

Java NIO FileChannel versus FileOutputstream performance / usefulness

If you are not using the transferTo feature or non-blocking features you will not notice a difference between traditional IO and NIO(2) because the traditional IO maps to NIO.

But if you can use the NIO features like transferFrom/To or want to use Buffers, then of course NIO is the way to go.

What's the difference between a single precision and double precision floating point operation?

To add to all the wonderful answers here

First of all float and double are both used for representation of numbers fractional numbers. So, the difference between the two stems from the fact with how much precision they can store the numbers.

For example: I have to store 123.456789 One may be able to store only 123.4567 while other may be able to store the exact 123.456789.

So, basically we want to know how much accurately can the number be stored and is what we call precision.

Quoting @Alessandro here

The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.

Float can accurately store about 7-8 digits in the fractional part while Double can accurately store about 15-16 digits in the fractional part

So, float can store double the amount of fractional part. That is why Double is called double the float

How to customize a Spinner in Android

Create a custom adapter with a custom layout for your spinner.

Spinner spinner = (Spinner) findViewById(;
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.travelreasons, R.layout.simple_spinner_item);


<TextView xmlns:android="" 
    android:ellipsize="marquee" />


<CheckedTextView xmlns:android="" 
    android:ellipsize="marquee" />

In styles add your custom dimensions and height as per your requirement.

 <style name="spinnerItemStyle" parent="android:Widget.TextView.SpinnerItem">


  <style name="spinnerDropDownItemStyle" parent="android:TextAppearance.Widget.TextView.SpinnerItem">


What is a software framework?

Technically, you don't need a framework. If you're making a really really simple site (think of the web back in 1992), you can just do it all with hard-coded HTML and some CSS.

And if you want to make a modern webapp, you don't actually need to use a framework for that, either.

You can instead choose to write all of the logic you need yourself, every time. You can write your own data-persistence/storage layer, or - if you're too busy - just write custom SQL for every single database access. You can write your own authentication and session handling layers. And your own template rending logic. And your own exception-handling logic. And your own security functions. And your own unit test framework to make sure it all works fine. And your own... [goes on for quite a long time]

Then again, if you do use a framework, you'll be able to benefit from the good, usually peer-reviewed and very well tested work of dozens if not hundreds of other developers, who may well be better than you. You'll get to build what you want rapidly, without having to spend time building or worrying too much about the infrastructure items listed above.

You can get more done in less time, and know that the framework code you're using or extending is very likely to be done better than you doing it all yourself.

And the cost of this? Investing some time learning the framework. But - as virtually every web dev out there will attest - it's definitely worth the time spent learning to get massive (really, massive) benefits from using whatever framework you choose.

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

Built-in support since Handlebars 1.0rc1

Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.

How to use it

For arrays:

{{#each myArray}}
    Index: {{@index}} Value = {{this}}

For objects:

{{#each myObject}}
    Key: {{@key}} Value = {{this}}

Note that only properties passing the hasOwnProperty test will be enumerated.

git push to specific branch

I would like to add an updated answer - now I have been using git for a while, I find that I am often using the following commands to do any pushing (using the original question as the example):

  • git push origin amd_qlp_tester - push to the branch located in the remote called origin on remote-branch called amd_qlp_tester.
  • git push -u origin amd_qlp_tester - same as last one, but sets the upstream linking the local branch to the remote branch so that next time you can just use git push/pull if not already linked (only need to do it once).
  • git push - Once you have set the upstream you can just use this shorter version.

Note -u option is the short version of --set-upstream - they are the same.

How to subtract X day from a Date object in Java?

Java 8 and later

With Java 8's date time API change, Use LocalDate

LocalDate date =;

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

SQL query, if value is null then return 1

SELECT orderhed.ordernum, orderhed.orderdate, currrate.currencycode,  

case(currrate.currentrate) when null then 1 else currrate.currentrate end

FROM orderhed LEFT OUTER JOIN currrate ON = AND orderhed.orderdate = currrate.effectivedate  

Node.js for() loop returning the same values at each loop

I would suggest doing this in a more functional style :P

function CreateMessageboard(BoardMessages) {
  var htmlMessageboardString = BoardMessages
   .map(function(BoardMessage) {
     return MessageToHTMLString(BoardMessage);

Try this

How to make a PHP SOAP call using the SoapClient class

You can use SOAP services this way too:

//Create the client object
$soapclient = new SoapClient('');

//Use the functions of the client, the params of the function are in 
//the associative array
$params = array('CountryName' => 'Spain', 'CityName' => 'Alicante');
$response = $soapclient->getWeather($params);


// Get the Cities By Country
$param = array('CountryName' => 'Spain');
$response = $soapclient->getCitiesByCountry($param);


This is an example with a real service, and it works when the url is up.

Just in case the is down.

Here is another example using the example web service from W3C XML Web Services example, you can find more information on the link.

//Create the client object
$soapclient = new SoapClient('');

//Use the functions of the client, the params of the function are in
//the associative array
$params = array('Celsius' => '25');
$response = $soapclient->CelsiusToFahrenheit($params);


// Get the Celsius degrees from the Farenheit
$param = array('Fahrenheit' => '25');
$response = $soapclient->FahrenheitToCelsius($param);


This is working and returning the converted temperature values.

Hope this helps.

How to get text from EditText?

String fname = ((EditText)findViewById(;
String lname = ((EditText)findViewById(;
((EditText)findViewById( + " "+lname);

What does "Git push non-fast-forward updates were rejected" mean?

It means that there have been other commits pushed to the remote repository that differ from your commits. You can usually solve this with a

git pull

before you push

Ultimately, "fast-forward" means that the commits can be applied directly on top of the working tree without requiring a merge.

Notice: Undefined offset: 0 in

As explained it happens because there is no data in the $cur_votes[0] and hence it throws an error.

To ensure your code works fine, before performing "$votes_up = $cur_votes[0]+1;" echo the $cur_votes[0] value to see if there is any value stored or not.

Surely, there is no value stored.

Can't find android device using "adb devices" command

I had Xamarin installed and tried to use Unity. Basically in any case you have to kill any application that might be talking to your device through ADB

Java: How to access methods from another class

Method 1:

If the method DoSomethingBeta was static you need only call:


Method 2:

If Alpha extends from Beta you could call DoSomethingBeta() directly.

public class Alpha extends Beta{
     public void DoSomethingAlpha() {
          DoSomethingBeta();  //?

Method 3:

Alternatively you need to have access to an instance of Beta to call the methods from it.

public class Alpha {
     public void DoSomethingAlpha() {
          Beta cbeta = new Beta();
          cbeta.DoSomethingBeta();  //?

Incidentally is this homework?

PHP/MySQL: How to create a comment section in your website

Create a new table called comments

They should have a column containing the id of the post they are assigned to.

Make a form which adds a new comment to that table.

An example (not tested so may contain lil' syntax errors): I call a page with comments a post


<!-- Post content here -->

<!-- Then cmments below -->
$result = mysql_query("SELECT * FROM comments WHERE postid=0");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
<div class="comment">
By: <?php echo $row->author; //Or similar in your table ?>
<?php echo;$row->body; ?>
<h1>Leave a comment:</h1>
<form action="insertcomment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="hidden" name="postid" value="<?php //your posts id ?>" />
<input type="submit" />


//First check if everything is filled in
if(/*some statements*/)
//Do a mysql_real_escape_string() to all fields

//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
die("Fill out everything please. Mkay.");

You must change the code a bit to make it work. I'n not doing your homework. Only a part of it ;)

Single vs double quotes in JSON

You can dump JSON with double quote by:

import json

# mixing single and double quotes
data = {'jsonKey': 'jsonValue',"title": "hello world"}

# get string with all double quotes
json_string = json.dumps(data) 

How can I use onItemSelected in Android?

You're almost there. As you can see, the onItemSelected will give you a position parameter, you can use this to retrieve the object from your adapter, as in getItemAtPosition(position).




public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
        "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),

This will put a message on screen, with the selected item printed by its toString() method.

How to copy an object in Objective-C

another.obj = [obj copyWithZone: zone];

I think, that this line causes memory leak, because you access to obj through property which is (I assume) declared as retain. So, retain count will be increased by property and copyWithZone.

I believe it should be:

another.obj = [[obj copyWithZone: zone] autorelease];


SomeOtherObject *temp = [obj copyWithZone: zone];
another.obj = temp;
[temp release]; 

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock

For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock

Using :before CSS pseudo element to add image to modal

You should use the background attribute to give an image to that element, and I would use ::after instead of before, this way it should be already drawn on top of your element.

  content: '';
  width: /* width of the image */;
  height: /* height of the image */;
  display: block;

Getting RSA private key from PEM BASE64 Encoded private key file

Parsing PKCS1 (only PKCS8 format works out of the box on Android) key turned out to be a tedious task on Android because of the lack of ASN1 suport, yet solvable if you include Spongy castle jar to read DER Integers.

String privKeyPEM = key.replace(
"-----BEGIN RSA PRIVATE KEY-----\n", "")
    .replace("-----END RSA PRIVATE KEY-----", "");

// Base64 decode the data

byte[] encodedPrivateKey = Base64.decode(privKeyPEM, Base64.DEFAULT);

try {
    ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
    Enumeration<?> e = primitive.getObjects();
    BigInteger v = ((DERInteger) e.nextElement()).getValue();

    int version = v.intValue();
    if (version != 0 && version != 1) {
        throw new IllegalArgumentException("wrong version for RSA private key");
     * In fact only modulus and private exponent are in use.
    BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
    BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger coefficient = ((DERInteger) e.nextElement()).getValue();

    RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(spec);
} catch (IOException e2) {
    throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
    throw new IllegalStateException(e);

How to send post request to the below post method using postman rest client

  1. Open Postman.
  2. Enter URL in the URL bar http://{server:port}/json/metallica/post.
  3. Click Headers button and enter Content-Type as header and application/json in value.
  4. Select POST from the dropdown next to the URL text box.
  5. Select raw from the buttons available below URL text box.
  6. Select JSON from the following dropdown.
  7. In the textarea available below, post your request object:

     "title" : "test title",
     "singer" : "some singer"
  8. Hit Send.

  9. Refer to screenshot below: enter image description here

How to find numbers from a string?

Based on @brettdj's answer using a VBScript regex ojbect with two modifications:

  • The function handles variants and returns a variant. That is, to take care of a null case; and
  • Uses explicit object creation, with a reference to the "Microsoft VBScript Regular Expressions 5.5" library
Function GetDigitsInVariant(inputVariant As Variant) As Variant
  ' Returns:
  '     Only the digits found in a varaint.
  ' Examples:
  '     GetDigitsInVariant(Null) => Null
  '     GetDigitsInVariant("") => ""
  '     GetDigitsInVariant(2021-/05-May/-18, Tue) => 20210518
  '     GetDigitsInVariant(2021-05-18) => 20210518
  ' Notes:
  '     If the inputVariant is null, null will be returned.
  '     If the inputVariant is "", "" will be returned.
  ' Usage:
  '     VBA IDE Menu > Tools > References ...
  '       > "Microsoft VBScript Regular Expressions 5.5" > [OK]

  ' With an explicit object reference to RegExp we can get intellisense
  ' and review the object heirarchy with the object browser
  ' (VBA IDE Menu > View > Object Browser).
  Dim regex As VBScript_RegExp_55.RegExp
  Set regex = New VBScript_RegExp_55.RegExp
  Dim result As Variant
  result = Null
  If IsNull(inputVariant) Then
    result = Null
    With regex
      .Global = True
      .Pattern = "[^\d]+"
      result = .Replace(inputVariant, vbNullString)
    End With
  End If
  GetDigitsInVariant = result
End Function


Private Sub TestGetDigitsInVariant()
  Dim dateVariants As Variant
  dateVariants = Array(Null, "", "2021-/05-May/-18, Tue", _
          "2021-05-18", "18/05/2021", "3434 ..,sdf,sfd 444")
  Dim dateVariant As Variant
  For Each dateVariant In dateVariants
    Debug.Print dateVariant & ": ", , GetDigitsInVariant(dateVariant)
  Next dateVariant
End Sub

How to get text box value in JavaScript

<!DOCTYPE html>
<label>Enter your Name here: </label><br>
<input type= text id="namehere" onchange="displayname()"><br>

function displayname() {
    document.getElementById("demo").innerHTML = 


<p id="demo"></p>


Android view layout_width - how to change programmatically?

Or simply:

view.getLayoutParams().width = 400;

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
    //for IE ONLY!

How to get document height and width without using jquery

Get document size without jQuery


And use this if you need Screen size


warning: assignment makes integer from pointer without a cast

What Jeremiah said, plus the compiler issues the warning because the production:

*src ="anotherstring";

says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.

-- pete

How do I set the selected item in a comboBox to match my string using C#?

This should do the trick:

Combox1.SelectedIndex = Combox1.FindStringExact("test1")

Group by month and year in MySQL

You must do something like this

SELECT onDay, id, 
CONCAT(YEAR(onDay),"-",MONTH(onDay)) as sdate 
FROM ... where stockParent_id =16120 group by sdate order by onDay

Play/pause HTML 5 video using JQuery

You could use the basic HTML player or you can make your own custom one. Just saying. If you want you can refer to ... and have a scroll through or not. It is to to you.

CURRENT_DATE/CURDATE() not working as default DATE value

I came to this page with the same question in mind, but it worked for me!, Just thought to update here , may be helpful for someone later!!

MariaDB [niffdb]> desc invoice;
| Field   | Type   | Null | Key | Default | Extra          |
| inv_id  | int(4) | NO   | PRI | NULL    | auto_increment |
| cust_id | int(4) | NO   | MUL | NULL    |                |
| inv_dt  | date   | NO   |     | NULL    |                |
| smen_id | int(4) | NO   | MUL | NULL    |                |
4 rows in set (0.003 sec)

Query OK, 0 rows affected (0.003 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [niffdb]> desc invoice;
| Field   | Type   | Null | Key | Default   | Extra          |
| inv_id  | int(4) | NO   | PRI | NULL      | auto_increment |
| cust_id | int(4) | NO   | MUL | NULL      |                |
| inv_dt  | date   | NO   |     | curdate() |                |
| smen_id | int(4) | NO   | MUL | NULL      |                |
4 rows in set (0.002 sec)

MariaDB [niffdb]> SELECT VERSION();
| VERSION()                 |
| 10.3.18-MariaDB-0+deb10u1 |
1 row in set (0.010 sec)

MariaDB [niffdb]>

How to resize an image to fit in the browser window?

Resize Image to Fit the Screen by the Longest Side maintaining its Aspect Ratio

img[src$="#fit"] {
    width: 100vw;
    height: auto;
    max-width: none;
    max-height: 100vh;
    object-fit: contain;
  • width: 100vw - image width will be 100% of view port

  • height: auto - image height will be scaled proportionally

  • max-height: 100vw - if image height would become more than view port it will be decreased to fit the screen, consequently image width will be decreased because of the following property

  • object-fit: contain - the replaced content is scaled to maintain its aspect ratio while fitting within the element's content box

    Note: object-fit is fully supported only since IE 16.0

excel vba getting the row,cell value from selection.address

Is this what you are looking for ?

Sub getRowCol()

    Range("A1").Select ' example

    Dim col, row
    col = Split(Selection.Address, "$")(1)
    row = Split(Selection.Address, "$")(2)

    MsgBox "Column is : " & col
    MsgBox "Row is : " & row

End Sub

How can I detect if a selector returns null?

You may want to do this all the time by default. I've been struggling to wrap the jquery function or jquery.fn.init method to do this without error, but you can make a simple change to the jquery source to do this. Included are some surrounding lines you can search for. I recommend searching jquery source for The jQuery object is actually just the init constructor 'enhanced'

  version = "3.3.1",

  // Define a local copy of jQuery
  jQuery = function( selector, context ) {

    // The jQuery object is actually just the init constructor 'enhanced'
    // Need init if jQuery is called (just allow error to be thrown if not included)
    var result = new jQuery.fn.init( selector, context );
    if ( result.length === 0 ) {
      if (window.console && console.warn && context !== 'failsafe') {
        if (selector != null) {
            new Error('$(\''+selector+'\') selected nothing. Do $(sel, "failsafe") to silence warning. Context:'+context)
    return result;

  // Support: Android <=4.0 only
  // Make sure we trim BOM and NBSP
  rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

jQuery.fn = jQuery.prototype = {

Last but not least, you can get the uncompressed jquery source code here:

The server principal is not able to access the database under the current security context in SQL Server MS 2012

SQL Logins are defined at the server level, and must be mapped to Users in specific databases.

In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.

Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.

enter image description here

These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:

USE {database};
ALTER USER {user} WITH login = {login}

You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.

How to dismiss a Twitter Bootstrap popover by clicking outside?

The answer from @guya works, unless you have something like a datepicker or timepicker in the popover. To fix that, this is what I have done.

if (typeof $('original-title') === 'undefined' && 
    !$('')) {
        var x = $(this).parents().context;
        if(!$(x).hasClass("datepicker") && !$(x).hasClass("ui-timepicker-wrapper")){

How to remove all click event handlers using jQuery?

If you used...

    function myFunc() {
        // ... do something ...

... then it will be easier to unbind later.

How to update Xcode from command line

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

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

form action with javascript

It has been almost 8 years since the question was asked, but I will venture an answer not previously given. The OP said this doesn't work:


And the OP said that this code continued to fail despite trying all the good advice he got. So I will venture a guess. The action is calling checkout() as a static method of the simpleCart class; but maybe checkout() is actually an instance member, and not static. It depends how he defined checkout().

By the way, simpleCart is presumably a class name, and by convention class names have an initial capital letter, so let's use that convention, here. Let's use the name SimpleCart.

Here is some sample code that illustrates defining checkout() as an instance member. This was the correct way to do it, prior to ECMA-6:

function SimpleCart() {
SimpleCart.prototype.checkout = function() { ... };

Many people have used a different technique, as illustrated in the following. This was popular, and it worked, but I advocate against it, because instances are supposed to be defined on the prototype, just once, while the following technique defines the member on this and does so repeatedly, with every instantiation.

function SimpleCart() {
    this.checkout = function() { ... };

And here is an instance definition in ECMA-6, using an official class:

class SimpleCart {
    constructor() { ... }
    checkout()    { ... }

Compare to a static definition in ECMA-6. The difference is just one word:

class SimpleCart {
    constructor() { ... }
    static checkout()    { ... }

And here is a static definition the old way, pre-ECMA-6. Note that the checkout() method is defined outside of the function. It is a member of the function object, not the prototype object, and that's what makes it static.

function SimpleCart() {
SimpleCart.checkout = function() { ... };

Because of the way it is defined, a static function will have a different concept of what the keyword this references. Note that instance member functions are called using the this keyword:


Static member functions are called using the class name:


The problem is that the OP wants to put the call into HTML, where it will be in global scope. He can't use the keyword this because this would refer to the global scope (which is window).

action="javascript:this.checkout()" // not as intended
action="javascript:window.checkout()" // same thing

There is no easy way to use an instance member function in HTML. You can do stuff in combination with JavaScript, creating a registry in the static scope of the Class, and then calling a surrogate static method, while passing an argument to that surrogate that gives the index into the registry of your instance, and then having the surrogate call the actual instance member function. Something like this:

// In Javascript:
SimpleCart.registry[1234] = new SimpleCart();

// In HTML

// In Javascript
SimpleCart.checkout = function(myIndex) {
    var myThis = SimpleCart.registry[myIndex];

You could also store the index as an attribute on the element.

But usually it is easier to just do nothing in HTML and do everything in JavaScript with .addEventListener() and use the .bind() capability.

Correct way to create rounded corners in Twitter Bootstrap

Bootstrap is just a big, useful, yet simple CSS file - not a framework or anything you can't override. I say this because I've noticed many developers got stick with BS classes and became lazy "I-can't-write-CSS-code-anymore" coders [this not being your case of course!].

If it features something you need, go with Bootstrap classes - if not, go write your additional code in good ol' style.css.

To have best of both worlds, you may write your own declarations in LESS and recompile the whole thing upon your needs, minimizing server request as a bonus.

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

You can do this go to Settings > Storage, clicking on the setting menu icon in the top right hand corner and selecting "USB computer connection". I then changed the storage mode to "Camera (PTP)". Done try re installing the driver from device manager.

How do I set the proxy to be used by the JVM

You can set some properties about the proxy server as jvm parameters

-Dhttp.proxyPort=8080, proxyHost, etc.

but if you need pass through an authenticating proxy, you need an authenticator like this example:


public class ProxyAuthenticator extends Authenticator {

    private String userName, password;

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password.toCharArray());

    public ProxyAuthenticator(String userName, String password) {
        this.userName = userName;
        this.password = password;

    import ProxyAuthenticator;

public class Example {

    public static void main(String[] args) {
        String username = System.getProperty("proxy.authentication.username");
        String password = System.getProperty("proxy.authentication.password");

                if (username != null && !username.equals("")) {
            Authenticator.setDefault(new ProxyAuthenticator(username, password));

                // here your JVM will be authenticated


Based on this reply:

Convert a SQL query result table to an HTML table for email

This might give you some idea --

  [Rank]  [int],
  [Player Name]  [varchar](128),
  [Ranking Points] [int],
  [Country]  [varchar](128)

SELECT 1,'Rafael Nadal',12390,'Spain'
SELECT 2,'Roger Federer',7965,'Switzerland'
SELECT 3,'Novak Djokovic',7880,'Serbia'


SET @xml = CAST(( SELECT [Rank] AS 'td','',[Player Name] AS 'td','',
       [Ranking Points] AS 'td','', Country AS 'td'
FROM  #Temp ORDER BY Rank 

SET @body ='<html><body><H3>Tennis Rankings Info</H3>
<table border = 1> 
<th> Rank </th> <th> Player Name </th> <th> Ranking Points </th> <th> Country </th></tr>'    

SET @body = @body + @xml +'</table></body></html>'

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQL ALERTING', -- replace with your SQL Database Mail Profile 
@body = @body,
@body_format ='HTML',
@recipients = '[email protected]', -- replace with your email address
@subject = 'E-mail in Tabular Format' ;


Programmatically navigate using React router

EDIT: React Router v6

I haven't touched React in a while, but want to thank and highlight the comment below by @Shimrit Snapir

on React-Router 6.0 <Redirect /> changed to <Navigate />

React Router V4


if (navigate) {
  return <Redirect to="/" push={true} />

The simple and declarative answer is that you need to use <Redirect to={URL} push={boolean} /> in combination with setState()

push: boolean - when true, redirecting will push a new entry onto the history instead of replacing the current one.

import { Redirect } from 'react-router'

class FooBar extends React.Component {
  state = {
    navigate: false

  render() {
    const { navigate } = this.state
    // here is the important part
    if (navigate) {
      return <Redirect to="/" push={true} />
   // ^^^^^^^^^^^^^^^^^^^^^^^
    return (
        <button onClick={() => this.setState({ navigate: true })}>

Full example here. Read more here.

PS. The example uses ES7+ Property Initializers to initialise state. Look here as well, if you're interested.

How do I get and set Environment variables in C#?

I ran into this while working on a .NET console app to read the PATH environment variable, and found that using System.Environment.GetEnvironmentVariable will expand the environment variables automatically.

I didn't want that to happen...that means folders in the path such as '%SystemRoot%\system32' were being re-written as 'C:\Windows\system32'. To get the un-expanded path, I had to use this:

string keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\";
string existingPathFolderVariable = (string)Registry.LocalMachine.OpenSubKey(keyName).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);

Worked like a charm for me.

Stored Procedure error ORA-06550

create or replace procedure point_triangle

dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);


struct.error: unpack requires a string argument of length 4

By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.

Displaying a webcam feed using OpenCV and Python

As in the opencv-doc you can get video feed from a camera which is connected to your computer by following code.

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
    # Capture frame-by-frame
    ret, frame =
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    if cv2.waitKey(1) & 0xFF == ord('q'):
# When everything done, release the capture

You can change cap = cv2.VideoCapture(0) index from 0 to 1 to access the 2nd camera.
Tested in opencv-3.2.0

Double decimal formatting in Java

First import NumberFormat. Then add this:

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

This will give you two decimal places and put a dollar sign if it's dealing with currency.

import java.text.NumberFormat;
public class Payroll 
     * @param args the command line arguments
    public static void main(String[] args) 
    int hoursWorked = 80;
    double hourlyPay = 15.52;

    double grossPay = hoursWorked * hourlyPay;
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

    System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));


Counting the occurrences / frequency of array elements

Here you go:

Live demo:


This changes the order of the original input array using Array.sort

var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];

function foo(arr) {
  var a = [],
    b = [],

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] !== prev) {
    } else {
      b[b.length - 1]++;
    prev = arr[i];

  return [a, b];

var result = foo(arr);
console.log('[' + result[0] + ']','[' + result[1] + ']')

Converting an integer to a string in PHP

You can simply use the following:

$intVal = 5;
$strVal = trim($intVal);

What is 0x10 in decimal?

0xNNNN (not necessarily four digits) represents, in C at least, a hexadecimal (base-16 because 'hex' is 6 and 'dec' is 10 in Latin-derived languages) number, where N is one of the digits 0 through 9 or A through F (or their lower case equivalents, either representing 10 through 15), and there may be 1 or more of those digits in the number. The other way of representing it is NNNN16.

It's very useful in the computer world as a single hex digit represents four bits (binary digits). That's because four bits, each with two possible values, gives you a total of 2 x 2 x 2 x 2 or 16 (24) values. In other words:

 /                                                                             \
| bF | bE | bD | bC | bB | bA | b9 | b8 | b7 | b6 | b5 | b4 | b3 | b2 | b1 | b0 |
 \_________________/ \_________________/ \_________________/ \_________________/ 
      Hex digit           Hex digit           Hex digit           Hex digit

A base-X number is a number where each position represents a multiple of a power of X.

In base 10, which we humans are used to, the digits used are 0 through 9, and the number 730410 is:

  • (7 x 103) = 700010 ; plus
  • (3 x 102) = 30010 ; plus
  • (0 x 101) = 010 ; plus
  • (4 x 100) = 410 ; equals 7304.

In octal, where the digits are 0 through 7. the number 7548 is:

  • (7 x 82) = 44810 ; plus
  • (5 x 81) = 4010 ; plus
  • (4 x 80) = 410 ; equals 49210.

Octal numbers in C are preceded by the character 0 so 0123 is not 123 but is instead (1 * 64) + (2 * 8) + 3, or 83.

In binary, where the digits are 0 and 1. the number 10112 is:

  • (1 x 23) = 810 ; plus
  • (0 x 22) = 010 ; plus
  • (1 x 21) = 210 ; plus
  • (1 x 20) = 110 ; equals 1110.

In hexadecimal, where the digits are 0 through 9 and A through F (which represent the "digits" 10 through 15). the number 7F2416 is:

  • (7 x 163) = 2867210 ; plus
  • (F x 162) = 384010 ; plus
  • (2 x 161) = 3210 ; plus
  • (4 x 160) = 410 ; equals 3254810.

Your relatively simple number 0x10, which is the way C represents 1016, is simply:

  • (1 x 161) = 1610 ; plus
  • (0 x 160) = 010 ; equals 1610.

As an aside, the different bases of numbers are used for many things.

  • base 10 is used, as previously mentioned, by we humans with 10 digits on our hands.
  • base 2 is used by computers due to the relative ease of representing the two binary states with electrical circuits.
  • base 8 is used almost exclusively in UNIX file permissions so that each octal digit represents a 3-tuple of binary permissions (read/write/execute). It's also used in C-based languages and UNIX utilities to inject binary characters into an otherwise printable-character-only data stream.
  • base 16 is a convenient way to represent four bits to a digit, especially as most architectures nowadays have a word size which is a multiple of four bits.
  • base 64 is used in encoding mail so that binary files may be sent using only printable characters. Each digit represents six binary digits so you can pack three eight-bit characters into four six-bit digits (25% increased file size but guaranteed to get through the mail gateways untouched).
  • as a semi-useful snippet, base 60 comes from some very old civilisation (Babylon, Sumeria, Mesopotamia or something like that) and is the source of 60 seconds/minutes in the minute/hour, 360 degrees in a circle, 60 minutes (of arc) in a degree and so on [not really related to the computer industry, but interesting nonetheless].
  • as an even less-useful snippet, the ultimate question and answer in The Hitchhikers Guide To The Galaxy was "What do you get when you multiply 6 by 9?" and "42". Whilst same say this is because the Earth computer was faulty, others see it as proof that the creator has 13 fingers :-)

Creating an empty list in Python

Just to highlight @Darkonaut answer because I think it should be more visible.

new_list = [] or new_list = list() are both fine (ignoring performance), but append() returns None, as result you can't do new_list = new_list.append(something).

Basic text editor in command prompt?

You can install vim/vi for windows and set windows PATH variable and open it in command line.

How to remove html special chars?

$string = "äácé";

$convert = Array(

$string = strtr($string , $convert );

echo $string; //aace

Returning a stream from File.OpenRead()

You need

    data.Position = 0; // reset to beginning
    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);  

And since your Test() method is imitating the client it ought to Close() or Dispose() the str Stream. And the memoryStream too, just out of principal.

How to change the default GCC compiler in Ubuntu?

I used just the lines below and it worked. I just wanted to compile VirtualBox and VMWare WorkStation using kernel 4.8.10 on Ubuntu 14.04. Initially, most things were not working for example graphics and networking. I was lucky that VMWare workstation requested for gcc 6.2.0. I couldn't start my Genymotion Android emulators because virtualbox was down. Will post results later if necessary.

VER=4.6 ; PRIO=60
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=6 ; PRIO=50
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=4.8 ; PRIO=40
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER

How to get the ASCII value of a character

You are looking for:


"message failed to fetch from registry" while trying to install any module

The below method worked for me, Kudos to github user : midnightcodr

Make sure You remove any nodejs/npm packages already installed.

sudo apt-get purge nodejs

sudo apt-get purge npm

Now Install Node js using the command below( Thanks to midnightcodr on github)

curl -L | bash -s 0.10.24

Note that you can invoke node with command node and not nodejs.

Once node is installed , Install npm

sudo apt-get install npm

Changing tab bar item image and text color iOS

Swift 3

I did it by creating a custom tabbar controller and added this code inside the viewDidLoad method.

    if let count = self.tabBar.items?.count {
        for i in 0...(count-1) {
            let imageNameForSelectedState   = arrayOfImageNameForSelectedState[i]
            let imageNameForUnselectedState = arrayOfImageNameForUnselectedState[i]

            self.tabBar.items?[i].selectedImage = UIImage(named: imageNameForSelectedState)?.withRenderingMode(.alwaysOriginal)
            self.tabBar.items?[i].image = UIImage(named: imageNameForUnselectedState)?.withRenderingMode(.alwaysOriginal)

    let selectedColor   = UIColor(red: 246.0/255.0, green: 155.0/255.0, blue: 13.0/255.0, alpha: 1.0)
    let unselectedColor = UIColor(red: 16.0/255.0, green: 224.0/255.0, blue: 223.0/255.0, alpha: 1.0)

    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: unselectedColor], for: .normal)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: selectedColor], for: .selected)

It worked for me!

enter image description here

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

My case is a bit special which VM option is not avaibale. I use x86 windows 7 system, my way of solving this problem is by doing following procedures:

  1. File - Setting...
  2. In "Build, Execution, Deployment" select "Gradle"
  3. choose "Use default gradle wrapper (recommended)" in "Project-level settings"

After restart Android Studio problem fixed!

How to refresh a Page using react-route Link

To refresh page you don't need react-router, simple js:


To re-render view in React component, you can just fire update with props/state.

Use jQuery to change value of a label

.text is correct, the following code works for me:

$('#lb'+(n+1)).text(a[i].attributes[n].name+": "+ a[i].attributes[n].value);

How to change int into int64?

i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64

SQL select * from column where year = 2010

T-SQL and others;

select * from t where year(Columnx) = 2010

When should I use the Visitor Design Pattern?

Double dispatch is just one reason among others to use this pattern.
But note that it is the single way to implement double or more dispatch in languages that uses a single dispatch paradigm.

Here are reasons to use the pattern :

1) We want to define new operations without changing the model at each time because the model doesn’t change often wile operations change frequently.

2) We don't want to couple model and behavior because we want to have a reusable model in multiple applications or we want to have an extensible model that allow client classes to define their behaviors with their own classes.

3) We have common operations that depend on the concrete type of the model but we don’t want to implement the logic in each subclass as that would explode common logic in multiple classes and so in multiple places.

4) We are using a domain model design and model classes of the same hierarchy perform too many distinct things that could be gathered somewhere else.

5) We need a double dispatch.
We have variables declared with interface types and we want to be able to process them according their runtime type … of course without using if (myObj instanceof Foo) {} or any trick.
The idea is for example to pass these variables to methods that declares a concrete type of the interface as parameter to apply a specific processing. This way of doing is not possible out of the box with languages relies on a single-dispatch because the chosen invoked at runtime depends only on the runtime type of the receiver.
Note that in Java, the method (signature) to call is chosen at compile time and it depends on the declared type of the parameters, not their runtime type.

The last point that is a reason to use the visitor is also a consequence because as you implement the visitor (of course for languages that doesn’t support multiple dispatch), you necessarily need to introduce a double dispatch implementation.

Note that the traversal of elements (iteration) to apply the visitor on each one is not a reason to use the pattern.
You use the pattern because you split model and processing.
And by using the pattern, you benefit in addition from an iterator ability.
This ability is very powerful and goes beyond iteration on common type with a specific method as accept() is a generic method.
It is a special use case. So I will put that to one side.

Example in Java

I will illustrate the added value of the pattern with a chess example where we would like to define processing as player requests a piece moving.

Without the visitor pattern use, we could define piece moving behaviors directly in the pieces subclasses.
We could have for example a Piece interface such as :

public interface Piece{

    boolean checkMoveValidity(Coordinates coord);

    void performMove(Coordinates coord);

    Piece computeIfKingCheck();


Each Piece subclass would implement it such as :

public class Pawn implements Piece{

    public boolean checkMoveValidity(Coordinates coord) {

    public void performMove(Coordinates coord) {

    public Piece computeIfKingCheck() {


And the same thing for all Piece subclasses.
Here is a diagram class that illustrates this design :

[model class diagram

This approach presents three important drawbacks :

– behaviors such as performMove() or computeIfKingCheck() will very probably use common logic.
For example whatever the concrete Piece, performMove() will finally set the current piece to a specific location and potentially takes the opponent piece.
Splitting related behaviors in multiple classes instead of gathering them defeats in a some way the single responsibility pattern. Making their maintainability harder.

– processing as checkMoveValidity() should not be something that the Piece subclasses may see or change.
It is check that goes beyond human or computer actions. This check is performed at each action requested by a player to ensure that the requested piece move is valid.
So we even don’t want to provide that in the Piece interface.

– In chess games challenging for bot developers, generally the application provides a standard API (Piece interfaces, subclasses, Board, common behaviors, etc…) and let developers enrich their bot strategy.
To be able to do that, we have to propose a model where data and behaviors are not tightly coupled in the Piece implementations.

So let’s go to use the visitor pattern !

We have two kinds of structure :

– the model classes that accept to be visited (the pieces)

– the visitors that visit them (moving operations)

Here is a class diagram that illustrates the pattern :

enter image description here

In the upper part we have the visitors and in the lower part we have the model classes.

Here is the PieceMovingVisitor interface (behavior specified for each kind of Piece) :

public interface PieceMovingVisitor {

    void visitPawn(Pawn pawn);

    void visitKing(King king);

    void visitQueen(Queen queen);

    void visitKnight(Knight knight);

    void visitRook(Rook rook);

    void visitBishop(Bishop bishop);


The Piece is defined now :

public interface Piece {

    void accept(PieceMovingVisitor pieceVisitor);

    Coordinates getCoordinates();

    void setCoordinates(Coordinates coordinates);


Its key method is :

void accept(PieceMovingVisitor pieceVisitor);

It provides the first dispatch : a invocation based on the Piece receiver.
At compile time, the method is bound to the accept() method of the Piece interface and at runtime, the bounded method will be invoked on the runtime Piece class.
And it is the accept() method implementation that will perform a second dispatch.

Indeed, each Piece subclass that wants to be visited by a PieceMovingVisitor object invokes the PieceMovingVisitor.visit() method by passing as argument itself.
In this way, the compiler bounds as soon as the compile time, the type of the declared parameter with the concrete type.
There is the second dispatch.
Here is the Bishop subclass that illustrates that :

public class Bishop implements Piece {

    private Coordinates coord;

    public Bishop(Coordinates coord) {

    public void accept(PieceMovingVisitor pieceVisitor) {

    public Coordinates getCoordinates() {
        return coordinates;

    public void setCoordinates(Coordinates coordinates) {
        this.coordinates = coordinates;


And here an usage example :

// 1. Player requests a move for a specific piece
Piece piece = selectPiece();
Coordinates coord = selectCoordinates();

// 2. We check with MoveCheckingVisitor that the request is valid
final MoveCheckingVisitor moveCheckingVisitor = new MoveCheckingVisitor(coord);

// 3. If the move is valid, MovePerformingVisitor performs the move
if (moveCheckingVisitor.isValid()) {
    piece.accept(new MovePerformingVisitor(coord));

Visitor drawbacks

The Visitor pattern is a very powerful pattern but it also has some important limitations that you should consider before using it.

1) Risk to reduce/break the encapsulation

In some kinds of operation, the visitor pattern may reduce or break the encapsulation of domain objects.

For example, as the MovePerformingVisitor class needs to set the coordinates of the actual piece, the Piece interface has to provide a way to do that :

void setCoordinates(Coordinates coordinates);

The responsibility of Piece coordinates changes is now open to other classes than Piece subclasses.
Moving the processing performed by the visitor in the Piece subclasses is not an option either.
It will indeed create another issue as the Piece.accept() accepts any visitor implementation. It doesn't know what the visitor performs and so no idea about whether and how to change the Piece state.
A way to identify the visitor would be to perform a post processing in Piece.accept() according to the visitor implementation. It would be a very bad idea as it would create a high coupling between Visitor implementations and Piece subclasses and besides it would probably require to use trick as getClass(), instanceof or any marker identifying the Visitor implementation.

2) Requirement to change the model

Contrary to some other behavioral design patterns as Decorator for example, the visitor pattern is intrusive.
We indeed need to modify the initial receiver class to provide an accept() method to accept to be visited.
We didn't have any issue for Piece and its subclasses as these are our classes.
In built-in or third party classes, things are not so easy.
We need to wrap or inherit (if we can) them to add the accept() method.

3) Indirections

The pattern creates multiples indirections.
The double dispatch means two invocations instead of a single one :

call the visited (piece) -> that calls the visitor (pieceMovingVisitor)

And we could have additional indirections as the visitor changes the visited object state.
It may look like a cycle :

call the visited (piece) -> that calls the visitor (pieceMovingVisitor) -> that calls the visited (piece)

How do I convert a decimal to an int in C#?

decimal vIn = 0.0M;
int vOut = Convert.ToInt32(vIn);

Here is a very handy convert data type webpage for those of others.

How do I output coloured text to a Linux terminal?

You can use ANSI colour codes.

use these functions.

enum c_color{BLACK=30,RED=31,GREEN=32,YELLOW=33,BLUE=34,MAGENTA=35,CYAN=36,WHITE=37};
void pr(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){

void prl(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

I had the exact same problem, found that I was missing

  <resource-adapter-ref resource-adapter-name="hornetq-ra"/>  
  <bean-instance-pool-ref pool-name="mdb-strict-max-pool"/>  


<subsystem xmlns="urn:jboss:domain:ejb3:1.2">  

in standalone/configuration/standalone.xml

iterating over each character of a String in ruby 1.8.6 (each_char)

"ABCDEFG".chars.each do |char|
  puts char


"ABCDEFG".each_char {|char| p char}

Ruby version >2.5.1

Wait until page is loaded with Selenium WebDriver for Python

You can do that very simple by this function:

def page_is_loading(driver):
    while True:
        x = driver.execute_script("return document.readyState")
        if x == "complete":
            return True
            yield False

and when you want do something after page loading complete,you can use:

Driver = webdriver.Firefox(options=Options, executable_path='geckodriver.exe')

while not page_is_loading(Driver):

Driver.execute_script("alert('page is loaded')")

How to reset form body in bootstrap modal box?

Just find your form and clear before it opens!

    $modal = $('#modal');

How do I make calls to a REST API using C#?

Here are a few different ways of calling an external API in C# (updated 2019).

.NET's built-in ways:

  • WebRequest& WebClient - verbose APIs & Microsoft's documentation is not very easy to follow
  • HttpClient - .NET's newest kid on the block & much simpler to use than above.

Free, open-source NuGet Packages, which frankly have a much better developer experience than .NET's built in clients:

  • ServiceStack.Text (1,000 GitHub stars, 7 million NuGet downloads) (*) - fast, light and resilient.
  • RestSharp (6,000 GitHub stars, 23 million NuGet downloads) (*) - simple REST and HTTP API Client
  • Flurl (1,700 GitHub stars, 3 million NuGet downloads) (*)- a fluent, portable, testable HTTP client library

All the above packages provide a great developer experience (i.e., concise, easy API) and are well maintained.

(*) as at August 2019

Example: Getting a Todo item from a Fake Rest API using ServiceStack.Text. The other libraries have very similar syntax.

class Program
    static void Main(string[] args)
        // Fake rest API
        string url = "";

        // GET data from API & map to POCO
        var todo =  url.GetJsonFromUrl().FromJson<Todo>();

        // Print the result to screen

    public class Todo
        public int UserId { get; set; }
        public int Id { get; set; }
        public string Title { get; set; }
        public bool Completed { get; set; }


Running the above example in a .NET Core Console app, produces the following output.

Enter image description here

Install these packages using NuGet

Install-Package ServiceStack.Text, or

Install-Package RestSharp, or

Install-Package Flurl.Http

JS how to cache a variable

You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.

Cookie *Create and Store a Cookie:*

function setCookie(c_name,value,exdays)
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;

The function which will return the specified cookie:

function getCookie(c_name)
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  if (x==c_name)
    return unescape(y);

Display a welcome message if the cookie is set

function checkCookie()
var username=getCookie("username");
  if (username!=null && username!="")
  alert("Welcome again " + username);
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")

The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.


Set a value to the session storage.


$.sessionStorage( 'foo', {data:'bar'} );

Retrieve the value:

$.sessionStorage( 'foo', {data:'bar'} );

$.sessionStorage( 'foo' );Results:

Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:

var names=[];
names[0]=prompt("New name?");

var storedNames=JSON.parse(localStorage['names']);

Server Side Example using ASP.NET

Adding to Sesion

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

// When retrieving an object from session state, cast it to // the appropriate type.

ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

I hope that answered your question.

IntelliJ - Convert a Java project/module into a Maven project/module

This fixed it for me: Open maven projects tab on the right. Add the pom if not yet present, then click refresh on the top left of the tab.

MySQL Sum() multiple columns

SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table

Are multiple `.gitignore`s frowned on?

As a tangential note, one case where the ability to have multiple .gitignore files is very useful is if you want an extra directory in your working copy that you never intend to commit. Just put a 1-byte .gitignore (containing just a single asterisk) in that directory and it will never show up in git status etc.

How to use store and use session variables across pages?

Starting a Session:

Put below code at the top of file.

<?php session_start();?>

Storing a session variable:

<?php $_SESSION['id']=10; ?>

To Check if data stored in session variable:

<?php if(isset($_SESSION['id']) && !empty(isset($_SESSION['id'])))
echo “Session id “.$_SESSION['id'].” exist”;
echo “Session not set “;?>

?> detail here

What is aria-label and how should I use it?

It's an attribute designed to help assistive technology (e.g. screen readers) attach a label to an otherwise anonymous HTML element.

So there's the <label> element:

<label for="fmUserName">Your name</label>
<input id="fmUserName">

The <label> explicitly tells the user to type their name into the input box where id="fmUserName".

aria-label does much the same thing, but it's for those cases where it isn't practical or desirable to have a label on screen. Take the MDN example:

<button aria-label="Close" onclick="myDialog.close()">X</button>`

Most people would be able to infer visually that this button will close the dialog. A blind person using assistive technology might just hear "X" read aloud, which doesn't mean much without the visual clues. aria-label explicitly tells them what the button will do.

Python group by

Python's built-in itertools module actually has a groupby function , but for that the elements to be grouped must first be sorted such that the elements to be grouped are contiguous in the list:

from operator import itemgetter
sortkeyfn = itemgetter(1)
input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), 
 ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), 
 ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')] 

Now input looks like:

[('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'),
 ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH'), ('11013331', 'KAT'),
 ('9843236', 'KAT'), ('9085267', 'NOT'), ('11788544', 'NOT')]

groupby returns a sequence of 2-tuples, of the form (key, values_iterator). What we want is to turn this into a list of dicts where the 'type' is the key, and 'items' is a list of the 0'th elements of the tuples returned by the values_iterator. Like this:

from itertools import groupby
result = []
for key,valuesiter in groupby(input, key=sortkeyfn):
    result.append(dict(type=key, items=list(v[0] for v in valuesiter)))

Now result contains your desired dict, as stated in your question.

You might consider, though, just making a single dict out of this, keyed by type, and each value containing the list of values. In your current form, to find the values for a particular type, you'll have to iterate over the list to find the dict containing the matching 'type' key, and then get the 'items' element from it. If you use a single dict instead of a list of 1-item dicts, you can find the items for a particular type with a single keyed lookup into the master dict. Using groupby, this would look like:

result = {}
for key,valuesiter in groupby(input, key=sortkeyfn):
    result[key] = list(v[0] for v in valuesiter)

result now contains this dict (this is similar to the intermediate res defaultdict in @KennyTM's answer):

{'NOT': ['9085267', '11788544'], 
 'ETH': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 
 'KAT': ['11013331', '9843236']}

(If you want to reduce this to a one-liner, you can:

result = dict((key,list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn))

or using the newfangled dict-comprehension form:

result = {key:list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn)}

Why is a div with "display: table-cell;" not affected by margin?

Table cells don't respect margin, but you could use transparent borders instead:

div {
  display: table-cell;
  border: 5px solid transparent;

Note: you can't use percentages here... :(

GSON - Date format

This is a bug. Currently you either have to set a timeStyle as well or use one of the alternatives described in the other answers.

Python: get key of index in dictionary

By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. Python Ordered Dictionary

C# MessageBox dialog result

DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
else if (result == DialogResult.No)

jquery how to use multiple ajax calls one after the end of the other

Place them inside of the success: of the one it relies on.

    url: 'http://www.xxxxxxxxxxxxx',
    data: {name: 'xxxxxx'},
    dataType: 'jsonp',
    success: function(data){

        // do stuff

        // call next ajax function
        $.ajax({ xxx });

how to write value into cell with vba code without auto type conversion?

Cells(1,1).Value2 = "'123,456"

note the single apostrophe before the number - this will signal to excel that whatever follows has to be interpreted as text.

Android Studio with Google Play Services

None of the above solution worked for me. Not sure if it is specific to my setup or new release.

I am using Android Studio Beta 0.8.9 and I was not getting any in the library list on following this instruction:

Go to File -> Project Structure -> Select Project Settings -> Select 'Dependencies' Tab Click '+' -> 1.Library Dependencies -> Select

I had already done this:

First of all you have to launch the sdk manager and download and install the following files located under "extras": Android support repository, Google play services, Google repository.

What resolved it was to add from SDK Manager, "Google play services for Froyo" then repeating the first step.

Did not understand the reason properly but this worked.

PS: I just observed that even now when I search for play-services this does not come, but when I directly scroll and look through the list it is right there.

Can I change the fill color of an svg path with CSS?

If you go into the source code of an SVG file you can change the color fill by modifying the fill property.

<svg fill="#3F6078" height="24" viewBox="0 0 24 24" width="24" xmlns="" xmlns:xlink="">

Use your favorite text editor, open the SVG file and play around with it.

How do I iterate and modify Java Sets?

I don't like very much iterator's semantic, please consider this as an option. It's also safer as you publish less of your internal state

private Map<String, String> JSONtoMAP(String jsonString) {

    JSONObject json = new JSONObject(jsonString);
    Map<String, String> outMap = new HashMap<String, String>();

    for (String curKey : (Set<String>) json.keySet()) {
        outMap.put(curKey, json.getString(curKey));

    return outMap;


How to define object in array in Mongoose schema correctly with 2d geo index

You can declare trk by the following ways : - either

trk : [{
    lat : String,
    lng : String


trk : { type : Array , "default" : [] }

In the second case during insertion make the object and push it into the array like

db.update({'Searching criteria goes here'},
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 

or you can set the Array of object by

db.update ({'seraching criteria goes here ' },
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                     "lat": 50.3293284,
                     "lng": 6.9389634
               ]//'inserted Array containing the list of object'

What are the minimum margins most printers can handle?

Every printer is different but 0.25" (6.35 mm) is a safe bet.

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
} will see a popup that says exactly what you want.

However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
                                      "Error: " + getRootCause(ex).getMessage());

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

Error in spring application context schema

I have recently had same issue with JPA-1.3

Nothing worked until I used explicit tools.xsd link

xsi:schemaLocation=" ...
    ... ">

like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" 

Displaying output of a remote command with Ansible

I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...

Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines attribute:

- name: Generate SSH keys for vagrant user
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
  register: vagrant
- debug: var=vagrant.stdout_lines

- name: Show SSH public key
  command: /bin/cat $home_directory/.ssh/
  register: cat
- debug: var=cat.stdout_lines

- name: Wait for user to copy SSH public key
  pause: prompt="Please add the SSH public key above to your GitHub account"
  register: pause
- debug: var=pause.stdout_lines

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

In LINQ, select all values of property X where X != null

There is no way to skip a check if it exists.

How can I find my php.ini on wordpress?

The name of the custom ini file depends on the user_ini.filename php setting. By default this should be .user.ini and the custom configuration files are used on a per-directory basis, so you should be able to either put it in the root of your Wordpress installation or under the wp-admin folder.

You can check the name of your custom configuration file by running:

php -i | grep user_ini.filename

I have created a plugin which makes it possible to change php settings from the Wordpress administration:

Custom PHP Settings

The plugin makes it possible to change settings either using the .htaccess file or the custom php.ini file, depending on how php is running.

How can you debug a CORS request with cURL?

Updated answer that covers most cases

curl -H "Access-Control-Request-Method: GET" -H "Origin: http://localhost" --head
  1. Replace with URL you want to test.
  2. If response includes Access-Control-Allow-* then your resource supports CORS.

Rationale for alternative answer

I google this question every now and then and the accepted answer is never what I need. First it prints response body which is a lot of text. Adding --head outputs only headers. Second when testing S3 URLs we need to provide additional header -H "Access-Control-Request-Method: GET".

Hope this will save time.

How to play a notification sound on websites?

As of 2016, the following will suffice (you don't even need to embed):

let src = '';
let audio = new Audio(src);;

See more here.

Using variables inside a bash heredoc

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

The format of here-documents is:


No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...

What is the difference between Scrum and Agile Development?

As mentioned above by others,

Scrum is an iterative and incremental agile software development method for managing software projects and product or application development. So Scrum is in fact a type of Agile approach which is used widely in software developments.

So, Scrum is a specific flavor of Agile, specifically it is referred to as an agile project management framework.

Also Scrum has mainly two roles inside it, which are: 1. Main/Core Role 2. Ancillary Role

Main/Core role: It consists of mainly three roles: a). Scrum Master, b). Product Owner, c). Development Team.

Ancillary Role: The ancillary roles in Scrum teams are those with no formal role and infrequent involvement in the Scrum procession but nonetheless, they must be taken into account. viz. Stakeholders, Managers.

Scrum Master:- There are 6 types of meetings in scrum:

  • Daily Scrum / Standup
  • Backlog grooming: storyline
  • Scrum of Scrums
  • Sprint Planning meeting
  • Sprint review meeting
  • Sprint retrospective

Let me know if any one need more inputs on this.

C# delete a folder and all files and folders within that folder

The Directory.Delete method has a recursive boolean parameter, it should do what you need

Replace all occurrences of a String using StringBuilder?

Even simple one is using the String ReplaceAll function itself. You can write it as

StringBuilder sb = new StringBuilder("Hi there, are you there?")

How to create a self-signed certificate for a domain name for development?

With IIS's self-signed certificate feature, you cannot set the common name (CN) for the certificate, and therefore cannot create a certificate bound to your choice of subdomain.

One way around the problem is to use makecert.exe, which is bundled with the .Net 2.0 SDK. On my server it's at:

C:\Program Files\Microsoft.Net\SDK\v2.0 64bit\Bin\makecert.exe

You can create a signing authority and store it in the LocalMachine certificates repository as follows (these commands must be run from an Administrator account or within an elevated command prompt):

makecert.exe -n "CN=My Company Development Root CA,O=My Company,
 OU=Development,L=Wallkill,S=NY,C=US" -pe -ss Root -sr LocalMachine
 -sky exchange -m 120 -a sha1 -len 2048 -r

You can then create a certificate bound to your subdomain and signed by your new authority:

(Note that the the value of the -in parameter must be the same as the CN value used to generate your authority above.)

makecert.exe -n "" -pe -ss My -sr LocalMachine
 -sky exchange -m 120 -in "My Company Development Root CA" -is Root
 -ir LocalMachine -a sha1 -eku

Your certificate should then appear in IIS Manager to be bound to your site as explained in Tom Hall's post.

All kudos for this solution to Mike O'Brien for his excellent blog post at

How to convert an integer to a character array using C

Make use of the log10 function to determine the number of digits and do like below:

char * toArray(int number)
    int n = log10(number) + 1;
    int i;
    char *numberArray = calloc(n, sizeof(char));
    for (i = n-1; i >= 0; --i, number /= 10)
        numberArray[i] = (number % 10) + '0';
    return numberArray;

Or the other option is sprintf(yourCharArray,"%ld", intNumber);

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

If you are using SQL Server 2012+ you can use CONCAT function in which we don't have to do any explicit conversion

SET @ActualWeightDIMS = Concat(@Actual_Dims_Lenght, 'x', @Actual_Dims_Width, 'x' 
                        , @Actual_Dims_Height) 

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

$('div').attr('style', '');


$('div').removeAttr('style'); (From Andres's Answer)

To make this a little smaller, try this:


This should speed it up a little because it checks that the divs have the style attribute.

Either way, this might take a little while to process if you have a large amount of divs, so you might want to consider other methods than javascript.

How can I check if a string represents an int, without using try/except?

I really liked Shavais' post, but I added one more test case ( & the built in isdigit() function):

def isInt_loop(v):
    v = str(v).strip()
    # swapping '0123456789' for '9876543210' makes nominal difference (might have because '1' is toward the beginning of the string)
    numbers = '0123456789'
    for i in v:
        if i not in numbers:
            return False
    return True

def isInt_Digit(v):
    v = str(v).strip()
    return v.isdigit()

and it significantly consistently beats the times of the rest:

isInt_try:   0.4628
isInt_str:   0.3556
isInt_re:    0.4889
isInt_re2:   0.2726
isInt_loop:   0.1842
isInt_Digit:   0.1577

using normal 2.7 python:

$ python --version
Python 2.7.10

Both the two test cases I added (isInt_loop and isInt_digit) pass the exact same test cases (they both only accept unsigned integers), but I thought that people could be more clever with modifying the string implementation (isInt_loop) opposed to the built in isdigit() function, so I included it, even though there's a slight difference in execution time. (and both methods beat everything else by a lot, but don't handle the extra stuff: "./+/-" )

Also, I did find it interesting to note that the regex (isInt_re2 method) beat the string comparison in the same test that was performed by Shavais in 2012 (currently 2018). Maybe the regex libraries have been improved?

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash

bash 4 (recursive)

shopt -s globstar
for xls in /path/**/*.xls
  xls2csv "$xls" "${xls%.xls}.csv"

How to set up Spark on Windows?

Here are seven steps to install spark on windows 10 and run it from python:

Step 1: download the spark 2.2.0 tar (tape Archive) gz file to any folder F from this link - Unzip it and copy the unzipped folder to the desired folder A. Rename the spark-2.2.0-bin-hadoop2.7 folder to spark.

Let path to the spark folder be C:\Users\Desktop\A\spark

Step 2: download the hardoop 2.7.3 tar gz file to the same folder F from this link - Unzip it and copy the unzipped folder to the same folder A. Rename the folder name from Hadoop-2.7.3.tar to hadoop. Let path to the hadoop folder be C:\Users\Desktop\A\hadoop

Step 3: Create a new notepad text file. Save this empty notepad file as winutils.exe (with Save as type: All files). Copy this O KB winutils.exe file to your bin folder in spark - C:\Users\Desktop\A\spark\bin

Step 4: Now, we have to add these folders to the System environment.

4a: Create a system variable (not user variable as user variable will inherit all the properties of the system variable) Variable name: SPARK_HOME Variable value: C:\Users\Desktop\A\spark

Find Path system variable and click edit. You will see multiple paths. Do not delete any of the paths. Add this variable value - ;C:\Users\Desktop\A\spark\bin

4b: Create a system variable

Variable name: HADOOP_HOME Variable value: C:\Users\Desktop\A\hadoop

Find Path system variable and click edit. Add this variable value - ;C:\Users\Desktop\A\hadoop\bin

4c: Create a system variable Variable name: JAVA_HOME Search Java in windows. Right click and click open file location. You will have to again right click on any one of the java files and click on open file location. You will be using the path of this folder. OR you can search for C:\Program Files\Java. My Java version installed on the system is jre1.8.0_131. Variable value: C:\Program Files\Java\jre1.8.0_131\bin

Find Path system variable and click edit. Add this variable value - ;C:\Program Files\Java\jre1.8.0_131\bin

Step 5: Open command prompt and go to your spark bin folder (type cd C:\Users\Desktop\A\spark\bin). Type spark-shell.


It may take time and give some warnings. Finally, it will show welcome to spark version 2.2.0

Step 6: Type exit() or restart the command prompt and go the spark bin folder again. Type pyspark:


It will show some warnings and errors but ignore. It works.

Step 7: Your download is complete. If you want to directly run spark from python shell then: go to Scripts in your python folder and type

pip install findspark

in command prompt.

In python shell

import findspark

import the necessary modules

from pyspark import SparkContext
from pyspark import SparkConf

If you would like to skip the steps for importing findspark and initializing it, then please follow the procedure given in importing pyspark in python shell

How to use OpenSSL to encrypt/decrypt files?

Additional comments to mti2935 good answer.

It seems the higher iteration the better protection against brute force, and you should use a high iteration as you can afford performance/resource wise.

On my my old Intel i3-7100 encrypting a rather big file 1.5GB:

 time openssl enc -aes256 -e -pbkdf2 -iter 10000 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
 Seconds: 2,564s

 time openssl enc -aes256 -e -pbkdf2 -iter 262144 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
 Seconds:  2,775s

Not really any difference, didn't check memory usage though(?)

With today's GPUs, and even faster tomorrows, I guess billion brute-force iteration seems possible every seconds.

12 years ago a NVIDIA GeForce 8800 Ultra could iterate over 200.000 millions/sec iterations (MD5 hashing though)

source: Ainane-Barrett-Johnson-Vivar-OpenSSL.pdf

Why isn't .ico file defined when setting window's icon?

I had the same problem too, but I found a solution.


from tkinter import *
# must add
root = Tk()

In the example, what python needed is an icon file, so when you dowload an icon as .png it won't work cause it needs an .ico file. So you need to find converters to convert your icon from png to ico.

Breaking a list into multiple columns in Latex

Using the multicol package and embedding your list in a multicols environment does what you want:


    \item a
    \item b
    \item c
    \item d
    \item e
    \item f

What is the Python equivalent of static variables inside a function?

A static variable inside a Python method

class Count:
    def foo(self):
   += 1
        except AttributeError: 
   = 1


m = Count()       # 1       # 2       # 3

How to check whether particular port is open or closed on UNIX?

Try (maybe as root)

lsof -i -P

and grep the output for the port you are looking for.

For example to check for port 80 do

lsof -i -P | grep :80

Setting up Gradle for api 26 (Android)

you must add in your MODULE-LEVEL build.gradle file with:

//module-level build.gradle file
repositories {
    maven {
        url ''


see: Google's Maven repository

I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url ''}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:

//project-level build.gradle file
allprojects {
 repositories {
    maven {
        url ''
        name 'Google'

UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0

How to get the ASCII value in JavaScript for the characters

Here is the example:

var charCode = "a".charCodeAt(0);_x000D_

Or if you have longer strings:

var string = "Some string";_x000D_
for (var i = 0; i < string.length; i++) {_x000D_

String.charCodeAt(x) method will return ASCII character code at a given position.

How can I add a vertical scrollbar to my div automatically?

You can set :

overflow-y: scroll;height: XX px

Extending an Object in Javascript

You might want to consider using helper library like underscore.js, which has it's own implementation of extend().

And it's also a good way to learn by looking at it's source code. The annotated source code page is quite useful.

PHP salt and hash SHA256 for login password

array hash_algos(void)

echo hash('sha384', 'Message to be hashed'.'salt');

Here is a link to reference

How do you clone an Array of Objects in Javascript?

Here is a my solution, It works for an array of objects or Map. This solution keeps the methods also.

A deep copy means actually creating a new array and copying over the values, since whatever happens to it will never affect the origin one.

This is the best solution for me:

deepCopy(inputObj: any) {
    var newObj = inputObj;
    if (inputObj && typeof inputObj === "object") {
        newObj = === "[object Array]" ? [] : {};
        for (var i in inputObj) {
            newObj[i] = this.deepCopy(inputObj[i]);

        //For maps
        if( === "[object Map]"){
            newObj = new Map;
            inputObj.forEach((v,k) =>{
    return newObj;

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

I usually use some #define and constants to make the calculation easy:

#define NANO_SECOND_MULTIPLIER  1000000  // 1 millisecond = 1,000,000 Nanoseconds

Hence my code would look like this:

timespec sleepValue = {0};

sleepValue.tv_nsec = INTERVAL_MS;
nanosleep(&sleepValue, NULL);

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

TL;DR: To access newer versions of mysql/mariadb after as the root user, after a new install, you need to be in a root shell (ie sudo mysql -u root, or mysql -u root inside a shell started by su - or sudo -i first)

Having just done the same upgrade, on Ubuntu, I had the same issue.

What was odd was that

sudo /usr/bin/mysql_secure_installation

Would accept my password, and allow me to set it, but I couldn't log in as root via the mysql client

I had to start mariadb with

sudo mysqld_safe --skip-grant-tables

to get access as root, whilst all the other users could still access fine.

Looking at the mysql.user table I noticed for root the plugin column is set to unix_socket whereas all other users it is set to 'mysql_native_password'. A quick look at this page: explains that the Unix Socket enables logging in by matching uid of the process running the client with that of the user in the mysql.user table. In other words to access mariadb as root you have to be logged in as root.

Sure enough restarting my mariadb daemon with authentication required I can login as root with

sudo mysql -u root -p


sudo su -
mysql -u root -p

Having done this I thought about how to access without having to do the sudo, which is just a matter of running these mysql queries

GRANT ALL PRIVILEGES on *.* to 'root'@'localhost' IDENTIFIED BY '<password>';

(replacing <password> with your desired mysql root password). This enabled password logins for the root user.

Alternatively running the mysql query:

UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';

Will change the root account to use password login without changing the password, but this may leave you with a mysql/mariadb install with no root password on it.

After either of these you need to restarting mysql/mariadb:

sudo service mysql restart

And voila I had access from my personal account via mysql -u root -p

PLEASE NOTE THAT DOING THIS IS REDUCING SECURITY Presumably the MariaDB developers have opted to have root access work like this for a good reason.

Thinking about it I'm quite happy to have to sudo mysql -u root -p so I'm switching back to that, but I thought I'd post my solution as I couldn't find one elsewhere.

Android failed to load JS bundle

After trying out a combination of the answers here, this is what is working for me.

I'm using Genymotion as my emulator.

1 Start up Genymotion emulator.

2 From a terminal

cd AwesomeProject
react-native run-android # it loads in genymotion and fails with bundle error
react-native start > /dev/null 2>&1 & # from dsissitka
adb reverse tcp:8081 tcp:8081 # from dsissitka

3 Reload from emulator.

It loads!

I can now begin developing.

What process is listening on a certain port on Solaris?

From Solaris 11.2 onwards you can indeed do this with the netstat command. Have a look here. The -u switch is what you are looking for.

If you are on a lower version of Solaris then - as others have pointed out - the Solaris way of doing this is some kind of script wrapper around pfiles command. Beware though that pfiles command halts the process for a split second in order to inspect it. For 99.9% of processes this is unimportant. Unfortunately we have a process that will give a core dump if it is hit with a pfiles command so we are a bit cautious about using the command. Your situation may be totally different if you are in the 99.9%, meaning you can safely use the pfiles command.

adb command not found

In my case with Android Studio 1.1.0 path was this


Add the following to ~/.bash_profile

export PATH=~/Library/Android/sdk/tools:$PATH
export PATH=~/Library/Android/sdk/platform-tools:$PATH

How to align absolutely positioned element to center?

Have you tried using?:

margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */

Not sure if it'll work, but it's worth a try...

Minor edit: Added the margin-left part, as pointed out on the comments by Chetan...

iPad Multitasking support requires these orientations

I am using Xamarin and there is no available option in the UI to specify "Requires full screen". I, therefore, had to follow @Michael Wang's answer with a slight modification. Here goes:

Open the info.plist file in a text editor and add the lines:


I tried setting the value to "YES" but it didn't work, which was kind of expected.

In case you are wondering, I placed the above lines below the UISupportedInterfaceOrientations section


Hope this helps someone. Credit to Michael.

SQL Server: Cannot insert an explicit value into a timestamp column

create table demo ( id int, ts timestamp )

insert into demo(id,ts) values (1, DEFAULT)

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

In this case a[4] is the 5th integer in the array a, ap is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap now holds 45 and when you try to de-reference it (by doing *ap) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.

You should do ap = &(a[4]); or ap = a + 4;

In c array names decays to pointer, so a points to the 1st element of the array.
In this way, a is equivalent to &(a[0]).

Android - shadow on text?

You should be able to add the style, like this (taken from source code for Ringdroid):

  <style name="AudioFileInfoOverlayText">
    <item name="android:paddingLeft">4px</item>
    <item name="android:paddingBottom">4px</item>
    <item name="android:textColor">#ffffffff</item>
    <item name="android:textSize">12sp</item>
    <item name="android:shadowColor">#000000</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>

And in your layout, use the style like this:

 <TextView android:id="@+id/info"
       android:gravity="center" />

Edit: the source code can be viewed here:

Edit2: To set this style programmatically, you'd do something like this (modified from this example to match ringdroid's resources from above)

TextView infoTextView = (TextView) findViewById(;

The signature for setTextAppearance is

public void setTextAppearance (Context context, int resid)

Since: API Level 1
Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance resource.

functional way to iterate over range (ES6/7)

Here's an approach using generators:

function* square(n) {
    for (var i = 0; i < n; i++ ) yield i*i;

Then you can write


Another idea is:

[...Array(5)].map((_, i) => i*i)

Array(5) creates an unfilled five-element array. That's how Array works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See

Alternatively, we could write

Array.from(Array(5)).map((_, i) => i*i)

or, we could take advantage of the second argument to Array#from to skip the map and write

Array.from(Array(5), (_, i) => i*i)

A horrible hack which I saw recently, which I do not recommend you use, is

[...1e4+''].map((_, i) => i*i)

Create nice column output in python

To get fancier tables like

| First Name | Last Name        | Age | Position  |
| John       | Smith            | 24  | Software  |
|            |                  |     | Engineer  |
| Mary       | Brohowski        | 23  | Sales     |
|            |                  |     | Manager   |
| Aristidis  | Papageorgopoulos | 28  | Senior    |
|            |                  |     | Reseacher |

you can use this Python recipe:

PSF License
import cStringIO,operator

def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left',
           separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x):
    """Indents a table by column.
       - rows: A sequence of sequences of items, one sequence per row.
       - hasHeader: True if the first row consists of the columns' names.
       - headerChar: Character to be used for the row separator line
         (if hasHeader==True or separateRows==True).
       - delim: The column delimiter.
       - justify: Determines how are data justified in their column. 
         Valid values are 'left','right' and 'center'.
       - separateRows: True if rows are to be separated by a line
         of 'headerChar's.
       - prefix: A string prepended to each printed row.
       - postfix: A string appended to each printed row.
       - wrapfunc: A function f(text) for wrapping text; each element in
         the table is first wrapped by this function."""
    # closure for breaking logical rows to physical, using wrapfunc
    def rowWrapper(row):
        newRows = [wrapfunc(item).split('\n') for item in row]
        return [[substr or '' for substr in item] for item in map(None,*newRows)]
    # break each logical row into one or more physical ones
    logicalRows = [rowWrapper(row) for row in rows]
    # columns of physical rows
    columns = map(None,*reduce(operator.add,logicalRows))
    # get the maximum of each column by the string length of its items
    maxWidths = [max([len(str(item)) for item in column]) for column in columns]
    rowSeparator = headerChar * (len(prefix) + len(postfix) + sum(maxWidths) + \
    # select the appropriate justify method
    justify = {'center', 'right':str.rjust, 'left':str.ljust}[justify.lower()]
    if separateRows: print >> output, rowSeparator
    for physicalRows in logicalRows:
        for row in physicalRows:
            print >> output, \
                prefix \
                + delim.join([justify(str(item),width) for (item,width) in zip(row,maxWidths)]) \
                + postfix
        if separateRows or hasHeader: print >> output, rowSeparator; hasHeader=False
    return output.getvalue()

# written by Mike Brown
def wrap_onspace(text, width):
    A word-wrap function that preserves existing line breaks
    and most spaces in the text. Expects that existing line
    breaks are posix newlines (\n).
    return reduce(lambda line, word, width=width: '%s%s%s' %
                   ' \n'[(len(line[line.rfind('\n')+1:])
                         + len(word.split('\n',1)[0]
                              ) >= width)],
                  text.split(' ')

import re
def wrap_onspace_strict(text, width):
    """Similar to wrap_onspace, but enforces the width constraint:
       words longer than width are split."""
    wordRegex = re.compile(r'\S{'+str(width)+r',}')
    return wrap_onspace(wordRegex.sub(lambda m: wrap_always(,width),text),width)

import math
def wrap_always(text, width):
    """A simple word-wrap function that wraps text on exactly width characters.
       It doesn't split the text in words."""
    return '\n'.join([ text[width*i:width*(i+1)] \
                       for i in xrange(int(math.ceil(1.*len(text)/width))) ])

if __name__ == '__main__':
    labels = ('First Name', 'Last Name', 'Age', 'Position')
    data = \
    '''John,Smith,24,Software Engineer
       Mary,Brohowski,23,Sales Manager
       Aristidis,Papageorgopoulos,28,Senior Reseacher'''
    rows = [row.strip().split(',')  for row in data.splitlines()]

    print 'Without wrapping function\n'
    print indent([labels]+rows, hasHeader=True)
    # test indent with different wrapping functions
    width = 10
    for wrapper in (wrap_always,wrap_onspace,wrap_onspace_strict):
        print 'Wrapping function: %s(x,width=%d)\n' % (wrapper.__name__,width)
        print indent([labels]+rows, hasHeader=True, separateRows=True,
                     prefix='| ', postfix=' |',
                     wrapfunc=lambda x: wrapper(x,width))

    # output:
    #Without wrapping function
    #First Name | Last Name        | Age | Position         
    #John       | Smith            | 24  | Software Engineer
    #Mary       | Brohowski        | 23  | Sales Manager    
    #Aristidis  | Papageorgopoulos | 28  | Senior Reseacher 
    #Wrapping function: wrap_always(x,width=10)
    #| First Name | Last Name  | Age | Position   |
    #| John       | Smith      | 24  | Software E |
    #|            |            |     | ngineer    |
    #| Mary       | Brohowski  | 23  | Sales Mana |
    #|            |            |     | ger        |
    #| Aristidis  | Papageorgo | 28  | Senior Res |
    #|            | poulos     |     | eacher     |
    #Wrapping function: wrap_onspace(x,width=10)
    #| First Name | Last Name        | Age | Position  |
    #| John       | Smith            | 24  | Software  |
    #|            |                  |     | Engineer  |
    #| Mary       | Brohowski        | 23  | Sales     |
    #|            |                  |     | Manager   |
    #| Aristidis  | Papageorgopoulos | 28  | Senior    |
    #|            |                  |     | Reseacher |
    #Wrapping function: wrap_onspace_strict(x,width=10)
    #| First Name | Last Name  | Age | Position  |
    #| John       | Smith      | 24  | Software  |
    #|            |            |     | Engineer  |
    #| Mary       | Brohowski  | 23  | Sales     |
    #|            |            |     | Manager   |
    #| Aristidis  | Papageorgo | 28  | Senior    |
    #|            | poulos     |     | Reseacher |

The Python recipe page contains a few improvements on it.

The type arguments for method cannot be inferred from the usage

I wanted to make a simple and understandable example

if you call a method like this, your client will not know return type

var interestPoints = Mediator.Handle(new InterestPointTypeRequest
                LanguageCode = request.LanguageCode,
                AgentId = request.AgentId,
                InterestPointId = request.InterestPointId,

Then you should say to compiler i know the return type is List<InterestPointTypeMap>

var interestPoints  = Mediator.Handle<List<InterestPointTypeMap>>(new InterestPointTypeRequest
                LanguageCode = request.LanguageCode,
                AgentId = request.AgentId,
                InterestPointId = request.InterestPointId,
                InterestPointTypeId = request.InterestPointTypeId

the compiler will no longer be mad at you for knowing the return type

What is the correct wget command syntax for HTTPS with username and password?

By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and download link to your needs.

wget --user=username --ask-password

Redis command to get all available keys?

In order to get all the keys available in redis server, you should open redis-cli and type: KEYS * In order to get more help please visit this page: This Link

jQuery delete all table rows except first

Consider a table with id tbl: the jQuery code would be:

$('#tbl tr:not(:first)').remove();

What is syntax for selector in CSS for next element?

Not exactly. The h1.hc-reform > p means "any p exactly one level underneath h1.hc-reform".

What you want is h1.hc-reform + p. Of course, that might cause some issues in older versions of Internet Explorer; if you want to make the page compatible with older IEs, you'll be stuck with either adding a class manually to the paragraphs or using some JavaScript (in jQuery, for example, you could do something like $('h1.hc-reform').next('p').addClass('first-paragraph')).

More info: or

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

nVarchar2 is a Unicode-only storage.

Though both data types are variable length String datatypes, you can notice the difference in how they store values. Each character is stored in bytes. As we know, not all languages have alphabets with same length, eg, English alphabet needs 1 byte per character, however, languages like Japanese or Chinese need more than 1 byte for storing a character.

When you specify varchar2(10), you are telling the DB that only 10 bytes of data will be stored. But, when you say nVarchar2(10), it means 10 characters will be stored. In this case, you don't have to worry about the number of bytes each character takes.

DB2 Date format

select to_char(current date, 'yyyymmdd') from sysibm.sysdummy1

result: 20160510

sql like operator to get the numbers only

With SQL 2012 and later, you could use TRY_CAST/TRY_CONVERT to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL -- note though that this will match scientific notation too (1+E34). (If you use decimal, then scientific notation won't match)

Is it worth using Python's re.compile?

I ran this test before stumbling upon the discussion here. However, having run it I thought I'd at least post my results.

I stole and bastardized the example in Jeff Friedl's "Mastering Regular Expressions". This is on a macbook running OSX 10.6 (2Ghz intel core 2 duo, 4GB ram). Python version is 2.6.1.

Run 1 - using re.compile

import re 
import time 
import fpformat
Regex1 = re.compile('^(a|b|c|d|e|f|g)+$') 
Regex2 = re.compile('^[a-g]+$')
TimesToDo = 1000
TestString = "" 
for i in range(1000):
    TestString += "abababdedfg"
StartTime = time.time() 
for i in range(TimesToDo): 
Seconds = time.time() - StartTime 
print "Alternation takes " + fpformat.fix(Seconds,3) + " seconds"

StartTime = time.time() 
for i in range(TimesToDo): 
Seconds = time.time() - StartTime 
print "Character Class takes " + fpformat.fix(Seconds,3) + " seconds"

Alternation takes 2.299 seconds
Character Class takes 0.107 seconds

Run 2 - Not using re.compile

import re 
import time 
import fpformat

TimesToDo = 1000
TestString = "" 
for i in range(1000):
    TestString += "abababdedfg"
StartTime = time.time() 
for i in range(TimesToDo):'^(a|b|c|d|e|f|g)+$',TestString) 
Seconds = time.time() - StartTime 
print "Alternation takes " + fpformat.fix(Seconds,3) + " seconds"

StartTime = time.time() 
for i in range(TimesToDo):'^[a-g]+$',TestString) 
Seconds = time.time() - StartTime 
print "Character Class takes " + fpformat.fix(Seconds,3) + " seconds"

Alternation takes 2.508 seconds
Character Class takes 0.109 seconds

POST data in JSON format

Not sure if you want jQuery.

var form;

form.onsubmit = function (e) {
  // stop the regular form submission

  // collect the form data while iterating over the inputs
  var data = {};
  for (var i = 0, ii = form.length; i < ii; ++i) {
    var input = form[i];
    if ( {
      data[] = input.value;

  // construct an HTTP request
  var xhr = new XMLHttpRequest();, form.action, true);
  xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

  // send the collected data as JSON

  xhr.onloadend = function () {
    // done

How do I count unique values inside a list

Use a set:

words = ['a', 'b', 'c', 'a']
unique_words = set(words)             # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3

Armed with this, your solution could be as simple as:

words = []
ipta = raw_input("Word: ")

while ipta:
  ipta = raw_input("Word: ")

unique_word_count = len(set(words))

print "There are %d unique words!" % unique_word_count

What is the use of printStackTrace() method in Java?

The printStackTrace() helps the programmer understand where the actual problem occurred. The printStackTrace() method is a member of the class Throwable in the java.lang package.

Shall we always use [unowned self] inside closure in Swift

According to Apple-doc

  • Weak references are always of an optional type, and automatically become nil when the instance they reference is deallocated.

  • If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference

Example -

    // if my response can nil use  [weak self]
      resource.request().onComplete { [weak self] response in
      guard let strongSelf = self else {
      let model = strongSelf.updateModel(response)

    // Only use [unowned self] unowned if guarantees that response never nil  
      resource.request().onComplete { [unowned self] response in
      let model = self.updateModel(response)

How to refresh activity after changing language (Locale) inside application

This approach will work on all API level device.

  1. Use Base Activity for attachBaseContext to set the locale language and extend this activity for all activities

    open class  BaseAppCompactActivity() : AppCompatActivity() {
        override fun attachBaseContext(newBase: Context) {
        override fun onCreate(savedInstanceState: Bundle?) {
  2. Use Application attachBaseContext and onConfigurationChanged to set the locale language

    public class MyApplication extends Application {
        private static MyApplication application;
        public void onCreate() {
        public static MyApplication getApplication() {
            return application;
         * overide to change local sothat language can be chnaged from android device  nogaut and above
        protected void attachBaseContext(Context base) {
        public void onConfigurationChanged(Configuration newConfig) {
        /*** also handle chnage  language if  device language chnaged **/
        private void setLanguageFromNewConfig(Configuration newConfig){
            Prefs.putSaveLocaleLanguage(this,  selectedLocaleLanguage );
  3. Use Locale Helper for handling language changes, this approach work on all device

    object LocaleHelper {
        private var defaultLanguage  :String = KycUtility.KYC_LANGUAGE.ENGLISH.languageCode
        fun onAttach(context: Context, defaultLanguage: String): Context {
            return setLocale(context, defaultLanguage)
        fun setLocale(context: Context, language: String): Context {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                updateResources(context, language)
            } else updateResourcesLegacy(context, language)
        private fun updateResources(context: Context, language: String): Context {
            val locale = Locale(language)
            val configuration = context.getResources().getConfiguration()
            return context.createConfigurationContext(configuration)
        private fun updateResourcesLegacy(context: Context, language: String): Context {
            val locale = Locale(language)
            val resources = context.getResources()
            val configuration = resources.getConfiguration()
            configuration.locale = locale
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            resources.updateConfiguration(configuration, resources.getDisplayMetrics())
            return context

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

Don't use keyworks like "ad", "ads", "advertise", etc. in image url or image class. Adblock block them automatically.

window.location.href doesn't redirect

Make sure you're not sending a '#' at the end of your URL. In my case, that was preventing window.location.href from working.

The ResourceConfig instance does not contain any root resource classes

In my case I have added the jars twice in build path after importing from war. It worked fine after removing the extra jars which was showing error deployment descriptor error pages



Floating elements within a div, floats outside of div. Why?

Here's more modern approach:

.parent {display: flow-root;} 

No more clearfixes.

p.s. Using overflow: hidden; hides the box-shadow so...

EditText underline below text property

You can change the color of EditText programmatically just using this line of code easily:


Remove "whitespace" between div element

Using a <br/> for making a new row it's a bad solution from the start. Make your container #div1 to have a width equal to 3 child-divs. <br/> in my opinion should not be used in other places than paragraphs.

Increase permgen space

For tomcat you can increase the permGem space by using


For this you need to create (if not already exists) a file named in tomcat/bin folder and include following line in it

   export JAVA_OPTS="-XX:MaxPermSize=128m"

Reference :

Using an array as needles in strpos

Reply to @binyamin and @Timo.. (not enough points to add a comment..) but the result doesn't contain the position..
The code below will return the actual position of the first element which is what strpos is intended to do. This is useful if you're expecting to find exactly 1 match.. If you're expecting to find multiple matches, then position of first found may be meaningless.

function strposa($haystack, $needle, $offset=0) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $query) {
      $res=strpos($haystack, $query, $offset);
      if($res !== false) return $res; // stop on first true result
    return false;

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

property 'map' does not exist on type 'observable response ' angular 6

Solution: Update Angular CLI And Core Version

ng update @angular/cli           //Update Angular CLi 
ng update @angular/core          //Update Angular Core 
npm install --save rxjs-compat   //For Map Call For Post Method 

Given a URL to a text file, what is the simplest way to read the contents of the text file?

The requests library has a simpler interface and works with both Python 2 and 3.

import requests

response = requests.get(target_url)
data = response.text

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

There is a companion tool called Oracle Data Modeler that you could take a look at. There are online demos available at the site that will get you started. It used to be an added cost item, but I noticed that once again it's free.

From the Data Modeler overview page:

SQL Developer Data Modeler is a free data modeling and design tool, proving a full spectrum of data and database modeling tools and utilities, including modeling for Entity Relationship Diagrams (ERD), Relational (database design), Data Type and Multi-dimensional modeling, with forward and reverse engineering and DDL code generation. The Data Modeler imports from and exports to a variety of sources and targets, provides a variety of formatting options and validates the models through a predefined set of design rules.

php return 500 error but no error log

What happened for me when this was an issue, was that the site had used too much memory, so I'm guessing that it couldn't write to an error log or displayed the error. For clarity, it was a Wordpress site that did this. Upping the memory limit on the server showed the site again.

How can I parse a time string containing milliseconds in it with python?

To give the code that nstehr's answer refers to (from its source):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." +
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." +
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)


CSS: image link, change on hover

You could do the following, without needing CSS...

<a href="ENTER_DESTINATION_URL"><img src="URL_OF_FIRST_IMAGE_SOURCE" onmouseover="this.src='URL_OF_SECOND_IMAGE_SOURCE'" onmouseout="this.src='URL_OF_FIRST_IMAGE_SOURCE_AGAIN'" /></a>


This solution was PERFECT for my needs! I found this solution here.

Disclaimer: Having a solution that is possible without CSS is important to me because I design content on the Jive-x cloud community platform which does not give us access to global CSS.

GUI Tool for PostgreSQL

Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.

Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.

Why can't DateTime.Parse parse UTC date

To correctly parse the string given in the question without changing it, use the following:

using System.Globalization;

string dateString = "Tue, 1 Jan 2008 00:00:00 UTC";
DateTime parsedDate = DateTime.ParseExact(dateString, "ddd, d MMM yyyy hh:mm:ss UTC", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);

This implementation uses a string to specify the exact format of the date string that is being parsed. The DateTimeStyles parameter is used to specify that the given string is a coordinated universal time string.

Turn Pandas Multi-Index into column

This doesn't really apply to your case but could be helpful for others (like myself 5 minutes ago) to know. If one's multindex have the same name like this:

Trial        Trial
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34 

df.reset_index(inplace=True) will fail, cause the columns that are created cannot have the same names.

So then you need to rename the multindex with df.index = df.index.set_names(['Trial', 'measurement']) to get:

Trial    measurement       

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34 

And then df.reset_index(inplace=True) will work like a charm.

I encountered this problem after grouping by year and month on a datetime-column(not index) called live_date, which meant that both year and month were named live_date.

What are the differences between the different saving methods in Hibernate?

This link explains in good manner :

We all have those problems that we encounter just infrequently enough that when we see them again, we know we’ve solved this, but can’t remember how.

The NonUniqueObjectException thrown when using Session.saveOrUpdate() in Hibernate is one of mine. I’ll be adding new functionality to a complex application. All my unit tests work fine. Then in testing the UI, trying to save an object, I start getting an exception with the message “a different object with the same identifier value was already associated with the session.” Here’s some example code from Java Persistence with Hibernate.

            Session session = sessionFactory1.openSession();
            Transaction tx = session.beginTransaction();
            Item item = (Item) session.get(Item.class, new Long(1234));
            session.close(); // end of first session, item is detached

            item.getId(); // The database identity is "1234"
            item.setDescription("my new description");
            Session session2 = sessionFactory.openSession();
            Transaction tx2 = session2.beginTransaction();
            Item item2 = (Item) session2.get(Item.class, new Long(1234));
            session2.update(item); // Throws NonUniqueObjectException

To understand the cause of this exception, it’s important to understand detached objects and what happens when you call saveOrUpdate() (or just update()) on a detached object.

When we close an individual Hibernate Session, the persistent objects we are working with are detached. This means the data is still in the application’s memory, but Hibernate is no longer responsible for tracking changes to the objects.

If we then modify our detached object and want to update it, we have to reattach the object. During that reattachment process, Hibernate will check to see if there are any other copies of the same object. If it finds any, it has to tell us it doesn’t know what the “real” copy is any more. Perhaps other changes were made to those other copies that we expect to be saved, but Hibernate doesn’t know about them, because it wasn’t managing them at the time.

Rather than save possibly bad data, Hibernate tells us about the problem via the NonUniqueObjectException.

So what are we to do? In Hibernate 3, we have merge() (in Hibernate 2, use saveOrUpdateCopy()). This method will force Hibernate to copy any changes from other detached instances onto the instance you want to save, and thus merges all the changes in memory before the save.

        Session session = sessionFactory1.openSession();
        Transaction tx = session.beginTransaction();
        Item item = (Item) session.get(Item.class, new Long(1234));
        session.close(); // end of first session, item is detached

        item.getId(); // The database identity is "1234"
        item.setDescription("my new description");
        Session session2 = sessionFactory.openSession();
        Transaction tx2 = session2.beginTransaction();
        Item item2 = (Item) session2.get(Item.class, new Long(1234));
        Item item3 = session2.merge(item); // Success!

It’s important to note that merge returns a reference to the newly updated version of the instance. It isn’t reattaching item to the Session. If you test for instance equality (item == item3), you’ll find it returns false in this case. You will probably want to work with item3 from this point forward.

It’s also important to note that the Java Persistence API (JPA) doesn’t have a concept of detached and reattached objects, and uses EntityManager.persist() and EntityManager.merge().

I’ve found in general that when using Hibernate, saveOrUpdate() is usually sufficient for my needs. I usually only need to use merge when I have objects that can have references to objects of the same type. Most recently, the cause of the exception was in the code validating that the reference wasn’t recursive. I was loading the same object into my session as part of the validation, causing the error.

Where have you encountered this problem? Did merge work for you or did you need another solution? Do you prefer to always use merge, or prefer to use it only as needed for specific cases

Check if checkbox is NOT checked on click - jQuery

$(document).ready(function() {
        $("#check1").click(function() {
            var checked = $(this).is(':checked');
            if (checked) {
            } else {

getting only name of the class Class.getName()

Here is the Groovy way of accessing object properties:

this.class.simpleName    # returns the simple name of the current class

Intro to GPU programming

If you use MATLAB, it becomes pretty simple to use GPU's for technical computing (matrix computations and heavy math/number crunching). I find it useful for uses of GPU cards outside of gaming. Check out the link below:

Selecting multiple columns with linq query and lambda expression

using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;

as Name = Fname + " " + LName;

See my below code which is working as expected; hope this is useful;

Myentity objMyEntity = new Myentity
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact

no need to declare the 'contact'

Displaying the Error Messages in Laravel after being Redirected from controller

Below input field I include additional view:

@include('input-errors', ['inputName' => 'inputName']) #For your case it would be 'email'


@foreach ($errors->get($inputName) as $message)
    <span class="input-error">{{ $message }}</span>

CSS - adds red color to the message.

.input-error {
    color: #ff5555;

How do I enter a multi-line comment in Perl?

I found it. Perl has multi-line comments:


use strict;

use warnings;

=for comment

Example of multiline comment.

Example of multiline comment.


print "Multi Line Comment Example \n";

Sharing a URL with a query string on Twitter

Use tweet web intent, this is the simple link:<?=urlencode($url)?>

more variables at

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

jQuery set checkbox checked

      <input id="IsActive" name="IsActive" type="checkbox" value="false">

    $('#IsActive').change(function () {
         var chk = $("#IsActive")
         var IsChecked = chk[0].checked
         if (IsChecked) {
          chk.attr('checked', 'checked')
         else {
          chk.attr('value', IsChecked)

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:

Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Can you have if-then-else logic in SQL?

--Similar answer as above for the most part. Code included to test

CREATE TABLE table1 (project int, customer int, company int, product int, price money)
INSERT INTO table1 VALUES (1,0,50, 100, 40),(1,0,20, 200, 55),(1,10,30,300, 75),(2,10,30,300, 75)
        , price
        , CASE WhereFound WHEN 1 THEN 'Project'
                WHEN 2 THEN 'Customer'
                WHEN 3 THEN 'Company'
            ELSE 'No Match'
            END AS Source
     SELECT product, price, 1 as WhereFound FROM table1 where project = 11
     SELECT product, price, 2 FROM table1 where customer = 0
     SELECT product, price, 3 FROM table1 where company = 30
    ) AS tbl

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

As he didn't specify which version of SQL server he uses (date type isn't available in 2005), one could also use

SELECT CONVERT(VARCHAR(10),date_column,112),SUM(num_col) AS summed
FROM table_name
GROUP BY CONVERT(VARCHAR(10),date_column,112)

Android Service needs to run always (Never pause or stop)

A simple solution is to restart the service when the system stops it.

I found this very simple implementation of this method:

How to make android service unstoppable

How do you get a timestamp in JavaScript?

If it is for logging purposes, you can use ISOString

new Date().toISOString()


Twitter Bootstrap Datepicker within modal window

For Bootstrap 3.x and Ace Template wrapbootstrap

Datepicker and Timepicker inside a Modal

    body.modal-open .datepicker {
        z-index: 1050 !important;
    body.modal-open .bootstrap-timepicker-widget {
        z-index: 1050 !important;

Must issue a STARTTLS command first


props.put("mail.smtp.starttls.enable", "true");

solved my problem ;)

My problem was :

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. u186sm7971862pfu.82 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(
at com.sun.mail.smtp.SMTPTransport.mailFrom(
at com.sun.mail.smtp.SMTPTransport.sendMessage(
at javax.mail.Transport.send0(
at javax.mail.Transport.send(
at com.example.sendmail.SendEmailExample2.main(

How to get the parent dir location


Should give you the path to a.

But if is the file that is currently executed, then you can achieve the same by just doing

os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    reader.readAsDataURL( file );

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

If you are debugging a web project, just make sure IIS Express is running either in 32 or 64 bits depending on your project settings.


Tools > Options > Projects and Solutions > Web Projects

and from there check (or uncheck) the 'Use 64 bit version of IIS Express...'

Text on image mouseover?

For people coming from the future, you can now do this purely in CSS.

.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; 
  margin: 5rem;

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  width: 120px;
  bottom: 100%;
  left: 50%;
  margin-left: -60px;

  position: absolute;
  z-index: 1;

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>

JQuery create a form and add elements to it programmatically

You need to append form itself to body too:

$form = $("<form></form>");
$form.append('<input type="button" value="button">');

how to change any data type into a string in python

Be careful if you really want to "change" the data type. Like in other cases (e.g. changing the iterator in a for loop) this might bring up unexpected behaviour:

>> dct = {1:3, 2:1}
>> len(str(dct))
>> print(str(dct))
{1: 31, 2: 0}
>> l = ["all","colours"]
>> len(str(l))

How to add 10 days to current time in Rails

days, years, etc., are part of Active Support, So this won't work in irb, but it should work in rails console.

Defining a HTML template to append using JQuery

Other alternative: Pure

I use it and it has helped me a lot. An example shown on their website:


<div class="who">


  "who": "Hello Wrrrld"


<div class="who">
  Hello Wrrrld

Can you animate a height change on a UITableViewCell when selected?

reloadData is no good because there's no animation...

This is what I'm currently trying:

NSArray* paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];

It almost works right. Almost. I'm increasing the height of the cell, and sometimes there's a little "hiccup" in the table view as the cell is replaced, as if some scrolling position in the table view is being preserved, the new cell (which is the first cell in the table) ends up with its offset too high, and the scrollview bounces to reposition it.

Entity Framework. Delete all rows in table

There are several issues with pretty much all the answers here:

1] Hard-coded sql. Will brackets work on all database engines?
2] Entity framework Remove and RemoveRange calls. This loads all entities into memory affected by the operation. Yikes.
3] Truncate table. Breaks with foreign key references and may not work accross all database engines.

Use, they handle the cross database platform stuff, translate the delete into the correct sql statement and don't load entities into memory, and the library is free and open source.

Disclaimer: I am not affiliated with the nuget package. They do offer a paid version that does even more stuff.

Mod in Java produces negative numbers

If you need n % m then:

int i = (n < 0) ? (m - (abs(n) % m) ) %m : (n % m);

mathematical explanation:

n = -1 * abs(n)
-> n % m = (-1 * abs(n) ) % m
-> (-1 * (abs(n) % m) ) % m
-> m - (abs(n) % m))

Change the default base url for axios

  1. Create .env.development, .env.production files if not exists and add there your API endpoint, for example: VUE_APP_API_ENDPOINT =''
  2. In main.js file, add this line after imports: axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT

And that's it. Axios default base Url is replaced with build mode specific API endpoint. If you need specific baseURL for specific request, do it like this:

this.$axios({ url: 'items', baseURL: '' })

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

jQuery Upload Progress and AJAX file upload

Here are some options for using AJAX to upload files:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

How to force composer to reinstall a library?

As user @aaracrr pointed out in a comment on another answer probably the best answer is to re-require the package with the same version constraint.


composer require vendor/package

or specifying a version constraint

composer require vendor/package:^1.0.0

jQuery - on change input text

That is working for me. Could be a browser issue as mentioned, or maybe jQuery isn't registered properly, or perhaps the real issue is more complicated (that you made a simpler version to ask this). PS - did have to click out of the text box to make it fire.