Programs & Examples On #Gambit

Questions about the Gambit-C implementation of the Scheme programming language.

Going to a specific line number using Less in Unix

To open at a specific line straight from the command line, use:

less +320123 filename

If you want to see the line numbers too:

less +320123 -N filename

You can also choose to display a specific line of the file at a specific line of the terminal, for when you need a few lines of context. For example, this will open the file with line 320123 on the 10th line of the terminal:

less +320123 -j 10 filename

javascript object max size limit

you have to put this in web.config :

        <jsonSerialization maxJsonLength="50000000" />

White space at top of page

This particular answer shows that h1 elements have an implicit margin-top that can cause the whitespace

The suggestion to remove it is helpful, and certainly eye opening to how this is happening

h1 { margin-top: 0; }

Using Node.JS, how do I read a JSON file into (server) memory?

Using fs-extra package is quite simple:


const fs = require('fs-extra')

const packageObj = fs.readJsonSync('./package.json')


const fs = require('fs-extra')

const packageObj = await fs.readJson('./package.json')

What is the difference between new/delete and malloc/free?

The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.

There are other differences:

  • new is type-safe, malloc returns objects of type void*

  • new throws an exception on error, malloc returns NULL and sets errno

  • new is an operator and can be overloaded, malloc is a function and cannot be overloaded

  • new[], which allocates arrays, is more intuitive and type-safe than malloc

  • malloc-derived allocations can be resized via realloc, new-derived allocations cannot be resized

  • malloc can allocate an N-byte chunk of memory, new must be asked to allocate an array of, say, char types

Looking at the differences, a summary is malloc is C-esque, new is C++-esque. Use the one that feels right for your code base.

Although it is legal for new and malloc to be implemented using different memory allocation algorithms, on most systems new is internally implemented using malloc, yielding no system-level difference.

Difference between a script and a program?

IMO Script - is the kind of instruction that program supposed to run Program - is kind of instruction that hardware supposed to run

Though i guess .NET/JAVA byte codes are scripts by this definition

What does the 'standalone' directive mean in XML?

The intent of the standalone=yes declaration is to guarantee that the information inside the document can be faithfully retrieved based only on the internal DTD, i.e. the document can "stand alone" with no external references. Validating a standalone document ensures that non-validating processors will have all of the information available to correctly parse the document.

The standalone declaration serves no purpose if a document has no external DTD, and the internal DTD has no parameter entity references, as these documents are already implicitly standalone.

The following are the actual effects of using standalone=yes.

  • Forces processors to throw an error when parsing documents with an external DTD or parameter entity references, if the document contains references to entities not declared in the internal DTD (with the exception of replacement text of parameter entities as non-validating processors are not required to parse this); amp, lt, gt, apos, and quot are the only exceptions

  • When parsing a document not declared as standalone, a non-validating processor is free to stop parsing the internal DTD as soon as it encounters a parameter entity reference. Declaring a document as standalone forces non-validating processors to parse markup declarations in the internal DTD even after they ignore one or more parameter entity references.

  • Forces validating processors to throw an error if any of the following are found in the document, and their respective declarations are in the external DTD or in parameter entity replacement text:

    • attributes with default values, if they do not have their value explicitly provided
    • entity references (other than amp, lt, gt, apos, and quot)
    • attributes with tokenized types, if the value of the attribute would be modified by normalization
    • elements with element content, if any white space occurs in their content

A non-validating processor might consider retrieving the external DTD and expanding all parameter entity references for documents that are not standalone, even though it is under no obligation to do so, i.e. setting standalone=yes could theoretically improve performance for non-validating processors (spoiler alert: it probably won't make a difference).

The other answers here are either incomplete or incorrect, the main misconception is that

The standalone declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.

standalone="yes" means that the XML processor must use the DTD for validation only.

Quite the opposite, declaring a document as standalone will actually force a non-validating processor to parse internal declarations it must normally ignore (i.e. those after an ignored parameter entity reference). Non-validating processors must still use the info in the internal DTD to provide default attribute values and normalize tokenized attributes, as this is independent of validation.

Convert a String to a byte array and then back to the original String

import; import;

public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream

public static byte[] read(InputStream is) throws Exception
    String path = /* type in the absolute path for the '' */;

    // must need a Byte buffer

    byte[] buf = new byte[1024 * 16]

    // we will use 16 kilobytes

    int len = 0;

    // we need a new input stream

    FileInputStream is = new FileInputStream(path);

    // use the buffer to update our "MessageDigest" instance

        len =;
        if(len < 0) break;
        md.update(buf, 0, len);

    // close the input stream


    // call the "digest" method for obtaining the final hash-result

    byte[] ret = md.digest();

    System.out.println("Length of Hash: " + ret.length);

    for(byte b : ret)
        System.out.println(b + ", ");

    String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

    String verification = Hex.encodeHexString(ret);




    System.out.println("Equals? " + verification.equals(compare));



Use Device Login on Smart TV / Console

Facebook login for smarttv/devices without facebook sdk is possible throught code , check the documentation here :

Change multiple files

I'm using find for similar task. It is quite simple: you have to pass it as an argument for sed like this:

sed -i 's/EXPRESSION/REPLACEMENT/g' `find -name "FILE.REGEX"`

This way you don't have to write complex loops, and it is simple to see, which files you are going to change, just run find before you run sed.

How do I check if a cookie exists?

regexObject.test( String ) is faster than string.match( RegExp ).

The MDN site describes the format for document.cookie, and has an example regex to grab a cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");). Based on that, I'd go for this:


The question seems to ask for a solution which returns false when the cookie is set, but empty. In that case:



function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table({return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));

Test results (Chrome 55.0.2883.87)

Wait until boolean value changes it state

public Boolean test() throws InterruptedException {
    BlockingQueue<Boolean> booleanHolder = new LinkedBlockingQueue<>();
    new Thread(() -> {
        try {
        } catch (InterruptedException e) {
    return booleanHolder.poll(4, TimeUnit.SECONDS);

Saving a select count(*) value to an integer (SQL Server)

select @myInt = COUNT(*) from myTable

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

When you want to create an external_table, all field's name must be written in UPPERCASE.


Node.js getaddrinfo ENOTFOUND

I fixed this error with this

$ npm info express --verbose
# Error message: npm info retry will retry, error on last attempt: Error: getaddrinfo ENOTFOUND
$ nslookup

Non-authoritative answer:  canonical name =    canonical name =
$ sudo vim /etc/hosts 
# Add "` to hosts file
$ npm info express --verbose
# Works now!

Original source:

What is the difference between Builder Design pattern and Factory Design pattern?

Both are Creational patterns, to create Object.

1) Factory Pattern - Assume, you have one super class and N number of sub classes. The object is created depends on which parameter/value is passed.

2) Builder pattern - to create complex object.

Ex: Make a Loan Object. Loan could be house loan, car loan ,
    education loan ..etc. Each loan will have different interest rate, amount ,  
    duration ...etc. Finally a complex object created through step by step process.

How to check the value given is a positive or negative integer?

if(values >= 0) {
 // as zero is more likely positive than negative
} else {


How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

Core jQuery doesn't have anything special for touch events, but you can easily build your own using the following events

  • touchstart
  • touchmove
  • touchend
  • touchcancel

For example, the touchmove

document.addEventListener('touchmove', function(e) {
    var touch = e.touches[0];
    alert(touch.pageX + " - " + touch.pageY);
}, false);

This works in most WebKit based browsers (incl. Android).

Here is some good documentation.

How can I position my div at the bottom of its container?

The flexbox approach!

In supported browsers, you can use the following:

Example Here

.parent {
  display: flex;
  flex-direction: column;
.child {
  margin-top: auto;

.parent {_x000D_
  height: 100px;_x000D_
  border: 5px solid #000;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
.child {_x000D_
  height: 40px;_x000D_
  width: 100%;_x000D_
  background: #f00;_x000D_
  margin-top: auto;_x000D_
<div class="parent">_x000D_
  <div class="child">Align to the bottom</div>_x000D_

The solution above is probably more flexible, however, here is an alternative solution:

Example Here

.parent {
  display: flex;
.child {
  align-self: flex-end;

.parent {_x000D_
  height: 100px;_x000D_
  border: 5px solid #000;_x000D_
  display: flex;_x000D_
.child {_x000D_
  height: 40px;_x000D_
  width: 100%;_x000D_
  background: #f00;_x000D_
  align-self: flex-end;_x000D_
<div class="parent">_x000D_
  <div class="child">Align to the bottom</div>_x000D_

As a side note, you may want to add vendor prefixes for additional support.

How do I mock an autowired @Value field in Spring with Mockito?

I'd like to suggest a related solution, which is to pass the @Value-annotated fields as parameters to the constructor, instead of using the ReflectionTestUtils class.

Instead of this:

public class Foo {

    private String foo;


public class FooTest {

    private Foo foo;

    public void setUp() {
        ReflectionTestUtils.setField(Foo.class, "foo", "foo");

    public void testFoo() {
        // stuff

Do this:

public class Foo {

    private String foo;

    public Foo(@Value("${foo}") String foo) { = foo;


public class FooTest {

    private Foo foo;

    public void setUp() {
        foo = new Foo("foo");

    public void testFoo() {
        // stuff

Benefits of this approach: 1) we can instantiate the Foo class without a dependency container (it's just a constructor), and 2) we're not coupling our test to our implementation details (reflection ties us to the field name using a string, which could cause a problem if we change the field name).

Adding the "Clear" Button to an iPhone UITextField

On Xcode 8 (8A218a):


textField.clearButtonMode = UITextField.ViewMode.whileEditing;

The "W" went from capital to non-cap "w".

How to delete files recursively from an S3 bucket

In case using AWS-SKD for ruby V2.

s3.list_objects(bucket: bucket_name, prefix: "foo/").contents.each do |obj|
  next if obj.key == "foo/" 
  resp = s3.delete_object({
    bucket: bucket_name,
    key: obj.key,

attention please, all "foo/*" under bucket will delete.

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop

How do I dump the data of some SQLite3 tables?

You're not saying what you wish to do with the dumped file.

I would use the following to get a CSV file, which I can import into almost everything

.mode csv 
-- use '.separator SOME_STRING' for something other than a comma.
.headers on 
.out file.csv 
select * from MyTable;

If you want to reinsert into a different SQLite database then:

.mode insert <target_table_name>
.out file.sql 
select * from MyTable;

how to draw a rectangle in HTML or CSS?



<div id="rectangle"></div>



I strongly suggest you read about CSS selectors and the basics of HTML.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb version/

    Replace with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9


    gpg --hkp://keyserver --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
  3. Install the new version

     sudo apt-get install r-base-dev
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Swift addsubview and remove it

I've a view inside my custom CollectionViewCell, and embedding a graph on that view. In order to refresh it, I've to check if there is already a graph placed on that view, remove it and then apply new. Here's the solution

graph.tag = 10

now, in code block where you want to remove it (in your case gestureRecognizerFunction)

if let removable = cell.cellView.viewWithTag(10){

to embed it again

graph.tag = 10

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Creating/writing into a new file in Qt

Your code is perfectly fine, you are just not looking at the right location to find your file. Since you haven't provided absolute path, your file will be created relative to the current working folder (more precisely in the current working folder in your case).

Your current working folder is set by Qt Creator. Go to Projects >> Your selected build >> Press the 'Run' button (next to 'Build) and you will see what it is on this page which of course you can change as well.

enter image description here

Can local storage ever be considered secure?


localStorage is accessible by any webpage, and if you have the key, you can change whatever data you want.

That being said, if you can devise a way to safely encrypt the keys, it doesn't matter how you transfer the data, if you can contain the data within a closure, then the data is (somewhat) safe.

What is

Often, a Python program is run by naming a .py file on the command line:

$ python

You can also create a directory or zipfile full of code, and include a Then you can simply name the directory or zipfile on the command line, and it executes the automatically:

$ python my_program_dir
$ python
# Or, if the program is accessible as a module
$ python -m my_program

You'll have to decide for yourself whether your application could benefit from being executed like this.

Note that a __main__ module usually doesn't come from a file. It can, but it usually doesn't. When you run a script like python, the script will run as the __main__ module instead of the my_program module. This also happens for modules run as python -m my_module, or in several other ways.

If you saw the name __main__ in an error message, that doesn't necessarily mean you should be looking for a file.

Find which version of package is installed with pip

There's also a tool called pip-check which gives you a quick overview of all installed packages and their update status:

enter image description here

Haven't used it myself; just stumbled upon it and this SO question in quick succession, and since it wasn't mentioned...

How do I iterate through children elements of a div using jQuery?

It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:

$('input', $('#mydiv')).each(function () {
    console.log($(this)); //log every element found to console output

The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.

How to index into a dictionary?

Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use d.keys()[i] and d.values()[i] or d.items()[i]. (Note that these methods create a list of all keys, values or items in Python 2.x. So if you need them more then once, store the list in a variable to improve performance.)

If you do care about the order of the entries, starting with Python 2.7 you can use collections.OrderedDict. Or use a list of pairs

l = [("blue", "5"), ("red", "6"), ("yellow", "8")]

if you don't need access by key. (Why are your numbers strings by the way?)

In Python 3.7, normal dictionaries are ordered, so you don't need to use OrderedDict anymore (but you still can – it's basically the same type). The CPython implementation of Python 3.6 already included that change, but since it's not part of the language specification, you can't rely on it in Python 3.6.

Add a user control to a wpf window

You probably need to add the namespace:

<Window x:Class="UserControlTest.Window1"
    Title="User Control Test" Height="300" Width="300">
    <local:UserControl1 />

Contains case insensitive

Use a RegExp:

if (!/ral/i.test(referrer)) {

Or, use .toLowerCase():

if (referrer.toLowerCase().indexOf("ral") == -1)

How to copy data from another workbook (excel)?

Would you be happy to make "my file.xls" active if it didn't affect the screen? Turning off screen updating is the way to achieve this, it also has performance improvements (significant if you are doing looping while switching around worksheets / workbooks).

The command to do this is:

    Application.ScreenUpdating = False

Don't forget to turn it back to True when your macros is finished.

Add CSS3 transition expand/collapse

I did not modify your code for this solution, I wrote my own instead. My solution isn't quite what you asked for, but maybe you could build on it with existing knowledge. I commented the code as well so you know what exactly I'm doing with the changes.

As a solution to "avoid setting the height in JavaScript", I just made 'maxHeight' a parameter in the JS function called toggleHeight. Now it can be set in the HTML for each div of class expandable.

I'll say this up front, I'm not super experienced with front-end languages, and there's an issue where I need to click the 'Show/hide' button twice initially before the animation starts. I suspect it's an issue with focus.

The other issue with my solution is that you can actually figure out what the hidden text is without pressing the show/hide button just by clicking in the div and dragging down, you can highlight the text that's not visible and paste it to a visible space.

My suggestion for a next step on top of what I've done is to make it so that the show/hide button changes dynamically. I think you can figure out how to do that with what you already seem to know about showing and hiding text with JS.

When should I use GC.SuppressFinalize()?

If a class, or anything derived from it, might hold the last live reference to an object with a finalizer, then either GC.SuppressFinalize(this) or GC.KeepAlive(this) should be called on the object after any operation that might be adversely affected by that finalizer, thus ensuring that the finalizer won't run until after that operation is complete.

The cost of GC.KeepAlive() and GC.SuppressFinalize(this) are essentially the same in any class that doesn't have a finalizer, and classes that do have finalizers should generally call GC.SuppressFinalize(this), so using the latter function as the last step of Dispose() may not always be necessary, but it won't be wrong.

How to leave/exit/deactivate a Python virtualenv

I had the same problem while working on an installer script. I took a look at what the bin/ did and reversed it.


#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys

# Path to virtualenv
venv_path = os.path.join('/home', 'sixdays', '.virtualenvs', 'test32')

# Save old values
old_os_path = os.environ['PATH']
old_sys_path = list(sys.path)
old_sys_prefix = sys.prefix

def deactivate():
    # Change back by setting values to starting values
    os.environ['PATH'] = old_os_path
    sys.prefix = old_sys_prefix
    sys.path[:0] = old_sys_path

# Activate the virtualenvironment
activate_this = os.path.join(venv_path, 'bin/')
execfile(activate_this, dict(__file__=activate_this))

# Print list of pip packages for virtualenv for example purpose
import pip
print str(pip.get_installed_distributions())

# Unload pip module
del pip

# Deactivate/switch back to initial interpreter

# Print list of initial environment pip packages for example purpose
import pip
print str(pip.get_installed_distributions())

I am not 100% sure if it works as intended. I may have missed something completely.

HTML5 <video> element on Android

HTML5 is supported on both Google (android) phones such as Galaxy S, and iPhone. iPhone however doesn't support Flash, which Google phones do support.

Java String split removed empty values

String[] split = data.split("\\|",-1);

This is not the actual requirement in all the time. The Drawback of above is show below:

Scenerio 1:
When all data are present:
    String data = "5|6|7||8|9|10|";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 7
    System.out.println(splt.length); //output: 8

When data is missing:

Scenerio 2: Data Missing
    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output: 8

Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.

    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output:7

What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.

json_decode() expects parameter 1 to be string, array given

  • Make an object

    $obj = json_decode(json_encode($need_to_json));

  • Show data from this $obj



HTTP 401 - what's an appropriate WWW-Authenticate header value?

When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

if (xhr.status == 204) 
    dropdown.innerHTML = xhr.responseText;

Here is the Reload() function:

function Reload() {
    var oForm = document.createElement("form");

How do I get the current GPS location programmatically in Android?

Get location of gps by -

LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

LocationListener locationListener = new LocationListener() 

            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub


            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub


            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub


            public void onLocationChanged(Location location) {
                // TODO Auto-generated method stub
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                double speed = location.getSpeed(); //spedd in meter/minute
                speed = (speed*3600)/1000;      // speed in km/minute               Toast.makeText(GraphViews.this, "Current speed:" + location.getSpeed(),Toast.LENGTH_SHORT).show();

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);


Bash script and /bin/bash^M: bad interpreter: No such file or directory

I have seen this issue when creating scripts in Windows env and then porting over to run on a Unix environment.

Try running dos2unix on the script:

Or just rewrite the script in your Unix env using vi and test.

Unix uses different line endings so can't read the file you created on Windows. Hence it is seeing ^M as an illegal character.

If you want to write a file on Windows and then port over, make sure your editor is set to create files in UNIX format.

In notepad++ in the bottom right of the screen, it tells you the document format. By default, it will say Dos\Windows. To change it go to

  • settings->preferences
  • new document / default directory tab
  • select the format as unix and close
  • create a new document

Output of git branch in tree like fashion

The following example shows commit parents as well:

git log --graph --all \
--format='%C(cyan dim) %p %Cred %h %C(white dim) %s %Cgreen(%cr)%C(cyan dim) <%an>%C(bold yellow)%d%Creset'

How do I prevent and/or handle a StackOverflowException?

With .NET 4.0 You can add the HandleProcessCorruptedStateExceptions attribute from System.Runtime.ExceptionServices to the method containing the try/catch block. This really worked! Maybe not recommended but works.

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;

namespace ExceptionCatching
    public class Test
        public void StackOverflow()

        public void CustomException()
            throw new Exception();

        public unsafe void AccessViolation()
            byte b = *(byte*)(8762765876);

    class Program
        static void Main(string[] args)
            Test test = new Test();
            try {

            Console.WriteLine("End of program");



SQL Server table creation date query

In case you also want Schema:


FROM sys.tables st


GROUP BY ic.TABLE_SCHEMA,, st.create_date, st.modify_date

ORDER BY st.create_date

PHP: cannot declare class because the name is already in use

you want to use include_once() or require_once(). The other option would be to create an additional file with all your class includes in the correct order so they don't need to call includes themselves:


include 'database.php';
include 'parent.php';
include 'child1.php';
include 'child2.php';

Then you just need:


How do I pick randomly from an array?

class String

  def black
    return "\e[30m#{self}\e[0m"

  def red
    return "\e[31m#{self}\e[0m"

  def light_green
    return "\e[32m#{self}\e[0m"

  def purple
    return "\e[35m#{self}\e[0m"

  def blue_dark
    return "\e[34m#{self}\e[0m"

  def blue_light
    return "\e[36m#{self}\e[0m"

  def white
    return "\e[37m#{self}\e[0m"

  def randColor
    array_color = [
      "\e[37m#{self}\e[0m" ]

      return array_color[rand(0..array_color.size)]

puts "black".black
puts "red".red
puts "light_green".light_green
puts "purple".purple
puts "dark blue".blue_dark
puts "light blue".blue_light
puts "white".white
puts "random color".randColor

How to convert a color integer to a hex String in Android?

I believe i have found the answer, This code converts the integer to a hex string an removes the alpha.

Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);

Note only use this code if you are sure that removing the alpha would not affect anything.

Reading JSON from a file?

You can use pandas library to read the JSON file.

import pandas as pd
df = pd.read_json('strings.json',lines=True)

How to convert java.util.Date to java.sql.Date?

Method for comparing 2 dates ( or

 public static boolean isSameDay(Date a, Date b) {
    Calendar calA = new GregorianCalendar();

    Calendar calB = new GregorianCalendar();

    final int yearA = calA.get(Calendar.YEAR);
    final int monthA = calA.get(Calendar.MONTH);
    final int dayA = calA.get(Calendar.DAY_OF_YEAR);

    final int yearB = calB.get(Calendar.YEAR);
    final int monthB = calB.get(Calendar.MONTH);
    final int dayB = calB.get(Calendar.DAY_OF_YEAR);

    return yearA == yearB && monthA == monthB && dayA == dayB;

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause


How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

How to get every first element in 2 dimensional list

use zip

columns = zip(*rows) #transpose rows to columns
print columns[0] #print the first column
#you can also do more with the columns
print columns[1] # or print the second column
columns.append([7,7,7]) #add a new column to the end
backToRows = zip(*columns) # now we are back to rows with a new column
print backToRows

you can also use numpy

a = numpy.array(a)
print a[:,0]

Edit: zip object is not subscriptable. It need to be converted to list to access as list:

column = list(zip(*row))

Regex to validate JSON

As was written above, if the language you use has a JSON-library coming with it, use it to try decoding the string and catch the exception/error if it fails! If the language does not (just had such a case with FreeMarker) the following regex could at least provide some very basic validation (it's written for PHP/PCRE to be testable/usable for more users). It's not as foolproof as the accepted solution, but also not that scary =):


short explanation:

// we have two possibilities in case the string is JSON
// 1. the string passed is "just" a JSON object, e.g. {"item": [], "anotheritem": "content"}
// this can be matched by the following regex which makes sure there is at least a {" at the
// beginning of the string and a } at the end of the string, whatever is inbetween is not checked!


// OR (character "|" in the regex pattern)
// 2. the string passed is a JSON array, e.g. [{"item": "value"}, {"item": "value"}]
// which would be matched by the second part of the pattern above


// the s modifier is used to make "." also match newline characters (can happen in prettyfied JSON)

if I missed something that would break this unintentionally, I'm grateful for comments!

Change color inside strings.xml

If you want to support text formatting from within your strings.xml file, you have to escape the tags – or use a CDATA section.. Otherwise Android simply ignores them when reading the resource file.


<string name="hello_world">
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>


String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);

Unable to run Java code with Intellij IDEA

Last resort option when nothing else seems to work: close and reopen IntelliJ.

My issue was with reverting a Git commit, which happened to change the Java SDK configured for the Project to a no longer installed version of the JDK. But fixing that back still didn't allow me to run the program. Restarting IntelliJ fixed this

PowerShell: Store Entire Text File Contents in Variable

One more approach to reading a file that I happen to like is referred to variously as variable notation or variable syntax and involves simply enclosing a filespec within curly braces preceded by a dollar sign, to wit:

$content = ${C:file.txt}

This notation may be used as either an L-value or an R-value; thus, you could just as easily write to a file with something like this:

 ${D:\path\to\file.txt} = $content

Another handy use is that you can modify a file in place without a temporary file and without sub-expressions, for example:

${C:file.txt} = ${C:file.txt} | select -skip 1

I became fascinated by this notation initially because it was very difficult to find out anything about it! Even the PowerShell 2.0 specification mentions it only once showing just one line using it--but with no explanation or details of use at all. I have subsequently found this blog entry on PowerShell variables that gives some good insights.

One final note on using this: you must use a drive designation, i.e. ${drive:filespec} as I have done in all the examples above. Without the drive (e.g. ${file.txt}) it does not work. No restrictions on the filespec on that drive: it may be absolute or relative.

Is there a RegExp.escape function in JavaScript?

The functions in the other answers are overkill for escaping entire regular expressions (they may be useful for escaping parts of regular expressions that will later be concatenated into bigger regexps).

If you escape an entire regexp and are done with it, quoting the metacharacters that are either standalone (., ?, +, *, ^, $, |, \) or start something ((, [, {) is all you need:

String.prototype.regexEscape = function regexEscape() {
  return this.replace(/[.?+*^$|({[\\]/g, '\\$&');

And yes, it's disappointing that JavaScript doesn't have a function like this built-in.

WAMP/XAMPP is responding very slow over localhost

I've just fixed such an issue on my laptop running windows 10. Suddenly wamp became super slow - a request to load a page was taking 2 minutes.

After trying numerous things, what it turned out to fix the problem was disabling windows defender. All worked like a charm after that.

p.s. I'd suggest you add your apache root dir to the exceptions list and not actually disable defender completely.

Sending a notification from a service in Android

If none of these work, try getBaseContext(), instead of context or this.

How to default to other directory instead of home directory

If you type this command: echo cd d:/some/path >> ~/.bashrc

Appends the line cd d:/some/path to .bashrc. The >> creates a file if it doesn’t exist and then appends.

MVC 4 Razor File Upload

Clarifying it. Model:

public class ContactUsModel
    public string FirstName { get; set; }             
    public string LastName { get; set; }              
    public string Email { get; set; }                 
    public string Phone { get; set; }                 
    public HttpPostedFileBase attachment { get; set; }

Post Action

public virtual ActionResult ContactUs(ContactUsModel Model)
 if (Model.attachment.HasFile())
   //save the file

   //Send it as an attachment 
    Attachment messageAttachment = new Attachment(Model.attachment.InputStream,       Model.attachment.FileName);

Finally the Extension method for checking the hasFile

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AtlanticCMS.Web.Common
     public static class ExtensionMethods 
         public static bool HasFile(this HttpPostedFileBase file)
             return file != null && file.ContentLength > 0;

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

From IEEE floating-point exceptions in C++ :

This page will answer the following questions.

  • My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
  • How can I tell if a number is really a number and not a NaN or an infinity?
  • How can I find out more details at runtime about kinds of NaNs and infinities?
  • Do you have any sample code to show how this works?
  • Where can I learn more?

These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.

Debugging 1.#IND, 1.#INF, nan, and inf

If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.

Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.

In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.

Angular 2 execute script after template render

Actually ngAfterViewInit() will initiate only once when the component initiate.

If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()

jQuery ajax post file field

File uploads can not be done this way, no matter how you break it down. If you want to do an ajax/async upload, I would suggest looking into something like Uploadify, or Valums

jQuery: checking if the value of a field is null (empty)

I would also trim the input field, cause a space could make it look like filled

if ($.trim($('#person_data[document_type]').val()) != '')


Not able to launch IE browser using Selenium2 (Webdriver) with Java

I was not able to modify the protected mode settings manually on my system since they were disabled. But the below VBA snippet for updating the registry values did the trick for me.(Please be cautious about any restrictions on your organization on modifying registry, before trying this)

Const HKEY_CURRENT_USER = &H80000001
strComputer = "."

Set ScriptMe=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
    strComputer & "\root\default:StdRegProv")

'Disable protected mode for local intranet'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue

'Disable protected mode for trusted pages'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue

'Disable protected mode for internet'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue

'Disable protected mode for restricted sites'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue

msgbox "Protected Mode Settings are updated"

Just copy paste the above code into notepad and save it with .vbs extension and double click it!

Now try running your automation script again

HTML.ActionLink vs Url.Action in ASP.NET Razor

@HTML.ActionLink generates a HTML anchor tag. While @Url.Action generates a URL for you. You can easily understand it by;

// 1. <a href="/ControllerName/ActionMethod">Item Definition</a>
@HTML.ActionLink("Item Definition", "ActionMethod", "ControllerName")

// 2. /ControllerName/ActionMethod
@Url.Action("ActionMethod", "ControllerName")

// 3. <a href="/ControllerName/ActionMethod">Item Definition</a>
<a href="@Url.Action("ActionMethod", "ControllerName")"> Item Definition</a>

Both of these approaches are different and it totally depends upon your need.

What is the best way to extract the first word from a string in Java?

The simple one I used to do is

str.contains(" ") ? str.split(" ")[0] : str

Where str is your string or text bla bla :). So, if

  1. str is having empty value it returns as it is.
  2. str is having one word, it returns as it is.
  3. str is multiple words, it extract the first word and return.

Hope this is helpful.

rename the columns name after cbind the data

It's easy just add the name which you want to use in quotes before adding vector

a_matrix <- cbind(b_matrix,'Name-Change'= c_vector)

Pytorch tensor to numpy array

I believe you also have to use .detach(). I had to convert my Tensor to a numpy array on Colab which uses CUDA and GPU. I did it like the following:

# this is just my embedding matrix which is a Torch tensor object
embedding = learn.model.u_weight

embedding_list = list(range(0, 64382))

input = torch.cuda.LongTensor(embedding_list)
tensor_array = embedding(input)
# the output of the line below is a numpy array

Powershell script to check if service is started, if not then start it

Trying to do things as smooth as possible - I here suggest modifying GuyWhoLikesPowershell's suggestion slightly.

I replaced the if and until with one while - and I check for "Stopped", since I don't want to start if status is "starting" or " Stopping".

$Service = 'ServiceName'
while ((Get-Service $Service).Status -eq 'Stopped') 
    Start-Service $Service -ErrorAction SilentlyContinue
    Start-Sleep 10
Return "$($Service) has STARTED"

What is this date format? 2011-08-12T20:17:46.384Z

You can use the following example.

    String date = "2011-08-12T20:17:46.384Z";

    String inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

    String outputPattern = "yyyy-MM-dd HH:mm:ss";

    LocalDateTime inputDate = null;
    String outputDate = null;

    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);

    inputDate = LocalDateTime.parse(date, inputFormatter);
    outputDate = outputFormatter.format(inputDate);

    System.out.println("inputDate: " + inputDate);
    System.out.println("outputDate: " + outputDate);

QUERY syntax using cell reference

To make it work with both text and numbers:

Exact match:

=query(D:E,"select * where D like '"&C1&"'", 0)

Convert search string to lowercase:

=query(D:E,"select * where D like lower('"&C1&"')", 0)

Convert to lowercase and contain part of the search string:

=query(D:E,"select * where D like lower('%"&C1&"%')", 0)

enter image description here

A1                = query/formula
yellow / A:B  = result area
green / C1    = search area
blue / D:E     = data area

If you get error when the input is text and not numbers; move the data and delete the (now empty) columns. Then move the data back.

How to retrieve unique count of a field using Kibana + Elastic Search

For Kibana 4 go to this answer

This is easy to do with a terms panel:

Adding a terms panel to Kibana

If you want to select the count of distinct IP that are in your logs, you should specify in the field clientip, you should put a big enough number in length (otherwise, it will join different IP under the same group) and specify in the style table. After adding the panel, you will have a table with IP, and the count of that IP:

Table with IP and count

Searching in a ArrayList with custom objects for certain strings

Use Apache CollectionUtils:

CollectionUtils.find(myList, new Predicate() {
   public boolean evaluate(Object o) {
      return name.equals(((MyClass) o).getName());

How to deal with "data of class uneval" error from ggplot2?

Another cause is accidentally putting the data=... inside the aes(...) instead of outside:

ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

In particular this can happen when you prototype your plot command with qplot(), which doesn't use an explicit aes(), then edit/copy-and-paste it into a ggplot()

qplot(data=..., x=...,y=..., ...)

ggplot(data=..., aes(x=...,y=...,...))

It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.

Removing empty rows of a data file in R

Here are some dplyr options:

# sample data
df <- data.frame(a = c('1', NA, '3', NA), b = c('a', 'b', 'c', NA), c = c('e', 'f', 'g', NA))


# remove rows where all values are NA:
df %>% filter_all(any_vars(!
df %>% filter_all(any_vars(complete.cases(.)))  

# remove rows where only some values are NA:
df %>% filter_all(all_vars(!
df %>% filter_all(all_vars(complete.cases(.)))  

# or more succinctly:
df %>% filter(complete.cases(.))  
df %>% na.omit

# dplyr and tidyr:
df %>% drop_na

How to invoke a Linux shell command from Java

exec does not execute a command in your shell


Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});


EDIT:: I don't have csh on my system so I used bash instead. The following worked for me

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});

How to write super-fast file-streaming code in C#?

The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:

NLS_NUMERIC_CHARACTERS setting for decimal

Jaanna, the session parameters in Oracle SQL Developer are dependent on your client computer, while the NLS parameters on PL/SQL is from server.

For example the NLS_NUMERIC_CHARACTERS on client computer can be ',.' while it's '.,' on server.

So when you run script from PL/SQL and Oracle SQL Developer the decimal separator can be completely different for the same script, unless you alter session with your expected NLS_NUMERIC_CHARACTERS in the script.

One way to easily test your session parameter is to do:

select to_number(5/2) from dual;

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

git pull fails "unable to resolve reference" "unable to update local ref"

I had same issue. i follow following steps

1)switch your branch which having issue to other branch

2) delete that branch

3) checkout again.

Note:- You can stash you uncommitted changes and put it back again.

Saving awk output to variable

I think the $() syntax is easier to read...

variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')

But the real issue is probably that $12 should not be qouted with ""

Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef is and what is expected in variable.

delete all from table

You can also use truncate.

truncate table table_name;

PHP Session timeout


if (time()<$_SESSION['time']+10){
$_SESSION['time'] = time();
echo "welcome old user";

$_SESSION['time'] = time();
echo "welcome new user";

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<td><form><input type=submit value="click me" style="width:100%"></form></td>

Printf width specifier to maintain precision of floating-point value

To my knowledge, there is a well diffused algorithm allowing to output to the necessary number of significant digits such that when scanning the string back in, the original floating point value is acquired in dtoa.c written by Daniel Gay, which is available here on Netlib (see also the associated paper). This code is used e.g. in Python, MySQL, Scilab, and many others.

Best way to check if MySQL results returned in PHP?

$result = $mysqli->query($query);
    perform action

this is how i do it, you could also throw an else there with a die...

Rerender view on browser resize with React

For this reason better is if you use this data from CSS or JSON file data, and then with this data setting new state with this.state({width: "some value",height:"some value" }); or writing code who use data of width screen data in self work if you wish responsive show images

Tuple unpacking in for loops

Enumerate basically gives you an index to work with in the for loop. So:

for i,a in enumerate([4, 5, 6, 7]):
    print i, ": ", a

Would print:

0: 4
1: 5
2: 6
3: 7

Google Gson - deserialize list<class> object? (generic type)

Method to deserialize generic collection:

import java.lang.reflect.Type;


Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);

Since several people in the comments have mentioned it, here's an explanation of how the TypeToken class is being used. The construction new TypeToken<...>() {}.getType() captures a compile-time type (between the < and >) into a runtime java.lang.reflect.Type object. Unlike a Class object, which can only represent a raw (erased) type, the Type object can represent any type in the Java language, including a parameterized instantiation of a generic type.

The TypeToken class itself does not have a public constructor, because you're not supposed to construct it directly. Instead, you always construct an anonymous subclass (hence the {}, which is a necessary part of this expression).

Due to type erasure, the TypeToken class is only able to capture types that are fully known at compile time. (That is, you can't do new TypeToken<List<T>>() {}.getType() for a type parameter T.)

For more information, see the documentation for the TypeToken class.

IOError: [Errno 32] Broken pipe: Python

Closes should be done in reverse order of the opens.

How to send a JSON object over Request with Android?

HttpPost is deprecated by Android Api Level 22. So, Use HttpUrlConnection for further.

public static String makeRequest(String uri, String json) {
    HttpURLConnection urlConnection;
    String url;
    String data = json;
    String result = null;
    try {
        urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");

        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {

        result = sb.toString();

    } catch (UnsupportedEncodingException e) {
    } catch (IOException e) {
    return result;

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

Sometimes, you have to send message from another Thread to UI thread. This type of scenario occurs when you can't execute Network/IO operations on UI thread.

Below example handles that scenario.

  1. You have UI Thread
  2. You have to start IO operation and hence you can't run Runnable on UI thread. So post your Runnable to handler on HandlerThread
  3. Get the result from Runnable and send it back to UI thread and show a Toast message.


  1. Create a HandlerThread and start it
  2. Create a Handler with Looper from HandlerThread:requestHandler
  3. Create a Handler with Looper from Main Thread: responseHandler and override handleMessage method
  4. post a Runnable task on requestHandler
  5. Inside Runnable task, call sendMessage on responseHandler
  6. This sendMessage result invocation of handleMessage in responseHandler.
  7. Get attributes from the Message and process it, update UI

Sample code:

    /* Handler thread */

    HandlerThread handlerThread = new HandlerThread("HandlerThread");
    Handler requestHandler = new Handler(handlerThread.getLooper());

    final Handler responseHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            //txtView.setText((String) msg.obj);
                    "Runnable on HandlerThread is completed and got result:"+(String)msg.obj,

    for ( int i=0; i<5; i++) {
        Runnable myRunnable = new Runnable() {
            public void run() {
                try {

                    /* Add your business logic here and construct the 
                       Messgae which should be handled in UI thread. For 
                       example sake, just sending a simple Text here*/

                    String text = "" + (++rId);
                    Message msg = new Message();

                    msg.obj = text.toString();

                } catch (Exception err) {

Useful articles:



MS Access - execute a saved query by name in VBA

You should investigate why VBA can't find queryname.

I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute.

CurrentDb.Execute "qryAddLoginfoRow"

My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.

Edit: You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute line.

Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name

The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb to Execute.

Difference between Eclipse Europa, Helios, Galileo

The Eclipse (software) page on Wikipedia summarizes it pretty well:


Since 2006, the Eclipse Foundation has coordinated an annual Simultaneous Release. Each release includes the Eclipse Platform as well as a number of other Eclipse projects. Until the Galileo release, releases were named after the moons of the solar system.

So far, each Simultaneous Release has occurred at the end of June.

Release         Main Release   Platform version      Projects
Photon          27 June 2018     4.8
Oxygen          28 June 2017     4.7                 
Neon            22 June 2016     4.6                 
Mars            24 June 2015     4.5                 Mars Projects
Luna            25 June 2014     4.4                 Luna Projects
Kepler          26 June 2013     4.3                 Kepler Projects
Juno            27 June 2012     4.2                 Juno Projects
Indigo          22 June 2011     3.7                 Indigo projects
Helios          23 June 2010     3.6                 Helios projects
Galileo         24 June 2009     3.5                 Galileo projects
Ganymede        25 June 2008     3.4                 Ganymede projects
Europa          29 June 2007     3.3                 Europa projects
Callisto        30 June 2006     3.2                 Callisto projects
Eclipse 3.1     28 June 2005     3.1  
Eclipse 3.0     28 June 2004     3.0  

To summarize, Helios, Galileo, Ganymede, etc are just code names for versions of the Eclipse platform (personally, I'd prefer Eclipse to use traditional version numbers instead of code names, it would make things clearer and easier). My suggestion would be to use the latest version, i.e. Eclipse Oxygen (4.7) (in the original version of this answer, it said "Helios (3.6.1)").

On top of the "platform", Eclipse then distributes various Packages (i.e. the "platform" with a default set of plugins to achieve specialized tasks), such as Eclipse IDE for Java Developers, Eclipse IDE for Java EE Developers, Eclipse IDE for C/C++ Developers, etc (see this link for a comparison of their content).

To develop Java Desktop applications, the Helios release of Eclipse IDE for Java Developers should suffice (you can always install "additional plugins" if required).

jQuery .val change doesn't change input value

This is just a possible scenario which happened to me. Well if it helps someone then great: I wrote a complicated app which somewhere along the code I used a function to clear all textboxes values before showing them. Sometime later I tried to set a textbox value using jquery val('value') but I did'nt notice that right after that I invoked the ClearAllInputs method.. so, this could also happen.

Why do we need the "finally" clause in Python?

I was trying to run a code where i wanted to read excel sheets. Issue was, if there is a file which has no sheet named say : SheetSum I am not able to move it to error location!! Code i wrote was:

def read_file(data_file):
    # data_file = '\rr\ex.xlsx'
    sheets = {}
        print("Reading file: "+data_file)
        sheets['df_1'] = pd.read_excel(open(data_file,'rb'), 'SheetSum')
    except Exception as excpt:
        print("Exception occurred", exc_info=True)
    return sheets

shutil.move( file, dirpath +'\\processed_files')

Giving Error :

[WinError 32] The process cannot access the file because it is being used by another process

I had to add full try except with finally block and tell finally i need to close the file in any case like:

def read_file(data_file):
    # data_file = '\rr\ex.xlsx'
    sheets = {}
        print("Reading file: "+data_file)
        sheets_file = open(data_file,'rb')
        sheets['df_1'] = pd.read_excel(sheets_file, 'SheetSum')
    except Exception as excpt:
        print("Exception occurred", exc_info=True)
    return sheets

shutil.move( file, dirpath +'\\processed_files')

Otherwise, file still remains open is the background.

If finally is present, it specifies a cleanup handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception.

..More Here

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

Webpack 4 Chunks and Hashes with Uglification by TerserPlugin

This can occur when Webpack uses chunks and hashes with minification and unglification via TerserPlugin (currently on version 1.2.3). In my case the error was narrowed down to the uglification by the Terser Plugin of my vendors.[contenthash].js bundle which holds my node_modules. Everything worked when not using hashes.

Solution was to exclude the bundle in the uglification options:

optimization: {
  minimizer: [
    new TerserPlugin({
      chunkFilter: (chunk) => {
        // Exclude uglification for the `vendors` chunk
        if ( === 'vendors') {
          return false;
        return true;

More info

Skip download if files exist in wget?

Try the following parameter:

-nc, --no-clobber: skip downloads that would download to existing files.

Sample usage:

wget -nc

Make child visible outside an overflow:hidden parent

For others, if clearfix does not solve this for you, add margins to the non-floated sibling that is/are the same as the width(s) of the floated sibling(s).

Why am I not getting a java.util.ConcurrentModificationException in this example?

One way to handle it it to remove something from a copy of a Collection (not Collection itself), if applicable. Clone the original collection it to make a copy via a Constructor.

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For your specific case, first off, i don't think final is a way to go considering you intend to modify the list past declaration

private static final List<Integer> integerList;

Also consider modifying a copy instead of the original list.

List<Integer> copy = new ArrayList<Integer>(integerList);

for(Integer integer : integerList) {
    if(integer.equals(remove)) {                

How to store .pdf files into MySQL as BLOBs using PHP?

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.

Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'

The ideal way of doing it is with MySQLI/PDO prepared statements.

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
        if ((myStream = theDialog.OpenFile()) != null)
            using (myStream)
                // Insert code to read the stream here.
    catch (Exception ex)
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
                employee = new Employee();
                currEmployeeLine = 1;

            switch (currEmployeeLine)
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                case 2:
                    employee.Name = filelines[a].Trim();
                case 3:
                    employee.Address = filelines[a].Trim();
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());


        //Test to see if it works
        foreach (Employee emp in employeeList)
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);

JavaScript, getting value of a td with id name

If by 'td value' you mean text inside of td, then:


How can I make my string property nullable?

It's been a while when the question has been asked and C# changed not much but became a bit better. Take a look Nullable reference types (C# reference)

string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness

C# as a language a "bit" outdated from modern languages and became misleading.

for instance in typescript, swift there's a "?" to clearly say it's a nullable type, be careful. It's pretty clear and it's awesome. C# doesn't/didn't have this ability, as a result, a simple contract IPerson very misleading. As per C# FirstName and LastName could be null but is it true? is per business logic FirstName/LastName really could be null? the answer is we don't know because C# doesn't have the ability to say it directly.

interface IPerson
  public string FirstName;
  public string LastName;

Spring security CORS Filter

  1. You don't need:


    @EnableWebSecurity already has @Configuration in it, and I cannot imagine why you put @ComponentScan there.

  2. About CORS filter, I would just put this:

    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        return bean;

    Into SecurityConfiguration class and remove configure and configure global methods. You don't need to set allowde orgins, headers and methods twice. Especially if you put different properties in filter and spring security config :)

  3. According to above, your "MyFilter" class is redundant.

  4. You can also remove those:

    final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();

    From Application class.

  5. At the end small advice - not connected to the question. You don't want to put verbs in URI. Instead of http://localhost:8080/getKunden you should use HTTP GET method on http://localhost:8080/kunden resource. You can learn about best practices for design RESTful api here:

Redis command to get all available keys?

If your redis is a cluster,you can use this script

#!/usr/bin/env bash

arr=($(echo "$redis_list" | tr ',' '\n'))

for info in ${arr[@]}; do
  echo "start :${info}"
  redis_info=($(echo "$info" | tr ':' '\n'))
  echo "ip="${ip}",port="${port}
  redis-cli -c -h $ip -p $port set laker$port '?????'
  redis-cli -c -h $ip -p $port keys \*


echo "end"

Combining two expressions (Expression<Func<T, bool>>)

Nothing new here but married this answer with this answer and slightly refactored it so that even I understand what's going on:

public static class ExpressionExtensions
    public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
        ParameterExpression parameter1 = expr1.Parameters[0];
        var visitor = new ReplaceParameterVisitor(expr2.Parameters[0], parameter1);
        var body2WithParam1 = visitor.Visit(expr2.Body);
        return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, body2WithParam1), parameter1);

    private class ReplaceParameterVisitor : ExpressionVisitor
        private ParameterExpression _oldParameter;
        private ParameterExpression _newParameter;

        public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
            _oldParameter = oldParameter;
            _newParameter = newParameter;

        protected override Expression VisitParameter(ParameterExpression node)
            if (ReferenceEquals(node, _oldParameter))
                return _newParameter;

            return base.VisitParameter(node);

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");


Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

Setting a spinner onClickListener() in Android

Whenever you have to perform some action on the click of the Spinner in Android, use the following method.

mspUserState.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
        return false;

One thing to keep in mind is always to return False while using the above method. If you will return True then the dropdown items of the spinner will not be displayed on clicking the Spinner.

Get width in pixels from element with style set with %?

Try jQuery:


Convert a string to int using sql query

You could use CAST or CONVERT:



Static method in a generic class?

Since static variables are shared by all instances of the class. For example if you are having following code

class Class<T> {
  static void doIt(T object) {
    // using T here 

T is available only after an instance is created. But static methods can be used even before instances are available. So, Generic type parameters cannot be referenced inside static methods and variables

Passing a callback function to another class

You have to first declare delegate's type because delegates are strongly typed:

public void MyCallbackDelegate( string str );

public void DoRequest(string request, MyCallbackDelegate callback)
     // do stuff....

Group query results by month and year in postgresql

Postgres has few types of timestamps:

timestamp without timezone - (Preferable to store UTC timestamps) You find it in multinational database storage. The client in this case will take care of the timezone offset for each country.

timestamp with timezone - The timezone offset is already included in the timestamp.

In some cases, your database does not use the timezone but you still need to group records in respect with local timezone and Daylight Saving Time (e.g.

To add timezone you can use this example and replace the timezone offset with yours.

"your_date_column" at time zone '+03'

To add the +1 Summer Time offset specific to DST you need to check if your timestamp falls into a Summer DST. As those intervals varies with 1 or 2 days, I will use an aproximation that does not affect the end of month records, so in this case i can ignore each year exact interval.

If more precise query has to be build, then you have to add conditions to create more cases. But roughly, this will work fine in splitting data per month in respect with timezone and SummerTime when you find timestamp without timezone in your database:

    "id", "Product", "Sale",
        CASE WHEN 
            Extract(month from t."date") > 03 AND
            Extract(day from t."date") > 26 AND
            Extract(hour from t."date") > 3 AND
            Extract(month from t."date") < 10 AND
            Extract(day from t."date") < 29 AND
            Extract(hour from t."date") < 4
            t."date" at time zone '+03' -- Romania TimeZone offset + DST
            t."date" at time zone '+02' -- Romania TimeZone offset 
        END) as "date"
    public."Table" AS t
    AND t."date" >= '01/07/2015 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
    AND t."date" < '01/07/2017 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
GROUP BY date_trunc('month', 
        Extract(month from t."date") > 03 AND
        Extract(day from t."date") > 26 AND
        Extract(hour from t."date") > 3 AND
        Extract(month from t."date") < 10 AND
        Extract(day from t."date") < 29 AND
        Extract(hour from t."date") < 4
        t."date" at time zone '+03' -- Romania TimeZone offset + DST
        t."date" at time zone '+02' -- Romania TimeZone offset 

Controlling Spacing Between Table Cells

Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.


Unable to start MySQL server

I had faced the same problem a few days ago.

I found the solution.

  1. control panel
  2. open administrative tool
  3. services
  4. find mysql80
  5. start the service

also, check the username and password.

Can I disable a CSS :hover effect via JavaScript?

There isn’t a pure JavaScript generic solution, I’m afraid. JavaScript isn’t able to turn off the CSS :hover state itself.

You could try the following alternative workaround though. If you don’t mind mucking about in your HTML and CSS a little bit, it saves you having to reset every CSS property manually via JavaScript.


<body class="nojQuery">


/* Limit the hover styles in your CSS so that they only apply when the nojQuery 
class is present */

body.nojQuery ul#mainFilter a:hover {
    /* CSS-only hover styles go here */


// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.


How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src=""></script>


'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
    }, 1000);

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);


How to find the Center Coordinate of Rectangle?

Center x = x + 1/2 of width

Center y = y + 1/2 of height 

If you know the width and height already then you only need one set of coordinates.

Using npm behind corporate proxy .pac

I solved this problem this way:

1) I run this command:

npm config set strict-ssl false

2) Then set npm to run with http, instead of https:

npm config set registry ""

3) Then install your package

npm install <package name>

Gradle store on local file system

Gradle caches artifacts in USER_HOME/.gradle folder. The compiled scripts are usually in the .gradle folder in your project folder.

If you can't find the cache, maybe it's because you have not cached any artifacts yet. You can always see where Gradle has cached artifacts with a simple script:

apply plugin: 'java'


  compile ''

task showMeCache << {
  configurations.compile.each { println it }

Now if you run gradle showMeCache it should download the deps into cache and print the full path.

Call jQuery Ajax Request Each X Minutes

A bit late but I used jQuery ajax method. But I did not want to send a request every second if I haven't got the response back from the last request, so I did this.

function request(){
            if(response == true){
                // This makes it unable to send a new request 
                // unless you get response from last request
                response = false;
                var req = $.ajax({
                    data:{data:"Hello World"}

                    console.log("Request successful!");

                    // This makes it able to send new request on the next interval
                    response = true;



jQuery animate backgroundColor

ColorBlend plug in does exactly what u want

Here is the my highlight code

    colorList:["white",  "yellow"], 
    cycles: 1,
    duration: 500

Difference between Select Unique and Select Distinct

Unique is a keyword used in the Create Table() directive to denote that a field will contain unique data, usually used for natural keys, foreign keys etc.

For example:

Create Table Employee(   
    Emp_PKey Int Identity(1, 1) Constraint PK_Employee_Emp_PKey Primary Key,  
    Emp_SSN Numeric Not Null Unique,  
    Emp_FName varchar(16),   
    Emp_LName varchar(16) 

i.e. Someone's Social Security Number would likely be a unique field in your table, but not necessarily the primary key.

Distinct is used in the Select statement to notify the query that you only want the unique items returned when a field holds data that may not be unique.

Select Distinct Emp_LName
From Employee

You may have many employees with the same last name, but you only want each different last name.

Obviously if the field you are querying holds unique data, then the Distinct keyword becomes superfluous.

dlib installation on Windows 10

Install Dlib from .whl

Dlib 19.7.0

pip install

You can test it, downloading an example from the site, for example and running it on your machine.

Note: if this message occurs you have to build dlib from source:

dlib-19.7.0-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform

Install Dlib from source (If the solution above doesn't work)

Windows Dlib > 19.7.0

  1. Download the CMake installer and install it:
  2. Add CMake executable path to the Enviroment Variables:

    set PATH="%PATH%;C:\Program Files\CMake\bin"

    note: The path of the executable could be different from C:\Program Files\CMake\bin, just set the PATH accordingly.

    note: The path will be set temporarily, to make the change permanent you have to set it in the “Advanced system settings” ? “Environment Variables” tab.

  3. Restart The Cmd or PowerShell window for changes to take effect.

  4. Download the Dlib source(.tar.gz) from the Python Package Index : extract it and enter into the folder.
  5. Check the Python version: python -V. This is my output: Python 3.7.2 so I'm installing it for Python3.x and not for Python2.x

    note: You can install it for both Python 2 and Python 3, if you have set different variables for different binaries i.e: python2 -V, python3 -V

  6. Run the installation: python install

Linux Dlib 19.17.0

sudo apt-get install cmake


tar -xvzf dlib-19.17.0.tar.gz

cd dlib-19.17.0/

sudo python3 install

note: To install Dlib for Python 2.x use python instead of python3 you can check your python version via python -V

Can I have onScrollListener for a ScrollView?

If you want to know the scroll position of a view, then you can use the following extension function on View class:

fun View?.onScroll(callback: (x: Int, y: Int) -> Unit) {
    var oldX = 0
    var oldY = 0
    this?.viewTreeObserver?.addOnScrollChangedListener {
        if (oldX != scrollX || oldY != scrollY) {
            callback(scrollX, scrollY)
            oldX = scrollX
            oldY = scrollY

Adding Buttons To Google Sheets and Set value to Cells on clicking

Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.

In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.

Back button and refreshing previous activity

The think best way to to it is using

Intent i = new Intent(this.myActivity, SecondActivity.class); 
startActivityForResult(i, 1);

Check if input value is empty and display an alert

Check empty input with removing space(if user enter space) from input using trim

            if($.trim($('#fname').val()) == '')
               $('#fname').css("border-color", "red");

Is there a way to use shell_exec without waiting for the command to complete?

How about adding.

"> /dev/null 2>/dev/null &"

shell_exec('php measurePerformance.php 47 844 [email protected] > /dev/null 2>/dev/null &');

Note this also gets rid of the stdio and stderr.

Generating a random password in php

This is based off another answer on this page,

This answer generates just hex characters, 0-9,a-f. For something that doesn't look like hex, try this:

  • base64_encode returns a wider spread of alphanumeric chars
  • rtrim removes the = sometimes at the end


  • 32eFVfGDg891Be5e7293e54z1D23110M3ZU3FMjb30Z9a740Ej0jz4
  • b280R72b48eOm77a25YCj093DE5d9549Gc73Jg8TdD9Z0Nj4b98760
  • 051b33654C0Eg201cfW0e6NA4b9614ze8D2FN49E12Y0zY557aUCb8
  • y67Q86ffd83G0z00M0Z152f7O2ADcY313gD7a774fc5FF069zdb5b7

This isn't very configurable for creating an interface for users, but for some purposes that's okay. Increase the number of chars to account for the lack of special characters.

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:


It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article:

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

The another reason can be the following:
I changed my Url for Web Api method according to this answer:

Url.Action("MyAction", "MyApiCtrl", new { httproute = "" })

But this method creates link like:


This works correctly with GET and POST requests but not with PUT or DELETE.
So I just replaced it with:


and it fixed the problem.

Mockito - NullpointerException when stubbing Method

As this is the closest I found to the issue I had, it's the first result that comes up and I didn't find an appropriate answer, I'll post the solution here for any future poor souls:

any() doesn't work where mocked class method uses a primitive parameter.

 public Boolean getResult(String identifier, boolean switch)

The above will produce the same exact issue as OP.

Solution, just wrap it:

 public Boolean getResult(String identifier, Boolean switch)

The latter solves the NPE.

Web link to specific whatsapp contact

I tried all combination for swiss numbers on my webpage. Below my results:

Doesn't work for Android and iOS

Works for iOS but doesn't work for Android

Works for Android and iOS:

Hope this information helps somebody!

Change icons of checked and unchecked for Checkbox for Android

Kind of a mix:

Set it in your layout file :-

 <CheckBox android:layout_width="wrap_content"
           android:text="new checkbox"
           android:button="@drawable/checkbox" />

where the @drawable/checkbox will look like:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="">
 <item android:state_checked="true" android:state_focused="true"
  android:drawable="@drawable/checkbox_on_background_focus_yellow" />
 <item android:state_checked="false" android:state_focused="true"
  android:drawable="@drawable/checkbox_off_background_focus_yellow" />
 <item android:state_checked="false"
  android:drawable="@drawable/checkbox_off_background" />
 <item android:state_checked="true"
  android:drawable="@drawable/checkbox_on_background" />

Multiple Buttons' OnClickListener() android

Implement onClick() method in your Activity/Fragment public class MainActivity extends Activity implements View.OnClickListener {

    protected void onCreate(Bundle savedInstanceState) {

    public void onClick(View v) {
 switch (itemId) {

// if you call the fragment with nevigation bar then used.

                fragment = new IntroductionFragment();

// if call activity with nevigation bar then used.

                Intent i = new Intent(MainActivity.this, YoutubeActivity.class);
      // default method for handling onClick Events..

Extract / Identify Tables from PDF python

After many fruitful hours of exploring OCR libraries, bounding boxes and clustering algorithms - I found a solution so simple it makes you want to cry!

I hope you are using Linux;

pdftotext -layout NAME_OF_PDF.pdf


Now you have a nice text file with all the information lined up in nice columns, now it is trivial to format into a csv etc..

It is for times like this that I love Linux, these guys came up with AMAZING solutions to everything, and put it there for FREE!

Appending output of a Batch file To log file

This is not an answer to your original question: "Appending output of a Batch file To log file?"

For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"

(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")


Example (1 second):



Example (1 second):

sleep -m 1000

Alternative methods:

Here's an answer to your 2nd followup question: "Along with the Timestamp?"

Create a date and time stamp in your batch files


echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log

Add ripple effect to my button with button background color?

AppCompat v7+

If you don't prefix with ?android: your app will crash.

You should use "?android:attr/selectableItemBackground" or "?android:attr/selectableItemBackgroundBorderless", based on your preference. I prefer Borderless.

You can put it either in android:background or android:foreground to keep existing properties.

The element must have android:clickable="true" and android:focusable="true" in order for this to work, but many elements, such as buttons, have them true by default.


Programmatically (Java)

TypedValue value = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, value, true);
myView.setFocusable(true); // If needed for view type

Programmatically (Kotlin)

val value = TypedValue()
context.theme.resolveAttribute(android.R.attr.selectableItemBackground, value, true)
myView.setFocusable(true) // If needed for view type

Reusable Kotlin Extension Function


fun View.ripple(): View {
    val value = TypedValue()
    context.theme.resolveAttribute(android.R.attr.selectableItemBackground, value, true)
    isFocusable = true // Required for some view types
    return this

How to integrate SAP Crystal Reports in Visual Studio 2017

Extracted from official SAP site

Item # 3 fixed my installation.

This applies for ANY Patch after SP 21

  1. FlexNet and In-Place Upgrade does not work: Once user receive the update notification from FlexNet server and finish SP21 upgrade, the product will NOT work. User MUST repair CR4VS and CRRuntime64 in Control Panel\Programs. That’s a by design change to installer.

    a. Please notice that we are still facing problems on configuring FlexNet upgrade server, so currently user will NOT receive SP21 notification

  2. Microsoft Windows Update KB2999226 is a prerequisite for SP21.

    a. This is same as BI 4.2 SP4 and BI 4.1 SP10. Please refer to SAP Note 2451830.

  3. For VS2017 integration, user needs use “run as Administrator” by right-clicking setup.exe, even if you are already log on by using Administrator account

  4. As most of CR/RAS .NET Assemblies are now re-versioned from 13.0.2000.0 to 13.0.3500.0, user MUST remove all old CR assemblies from Reference list and add the new version of CR assemblies, then rebuild the application.

    a. For those customer/user who do not wanted to rebuilt their application, there’s workaround to use in app.config/web.config, please see attachment.

  1. For reports using the ADO.Net DB connection, in previous SP's, you could only work under .Net Framework 2.0/3.5, so using in app.config is required. Now in SP21, ADO.Net is only supported on .Net Framework 3.5 or above.

Split string based on a regular expression

The str.split method will automatically remove all white space between items:

>>> str1 = "a    b     c      d"
>>> str1.split()
['a', 'b', 'c', 'd']

Docs are here:

Setting PayPal return URL and making it auto return?

one way i have found:

try to insert this field into your generated form code:

<input type='hidden' name='rm' value='2'>

rm means return method;

2 means (post)

Than after user purchases and returns to your site url, then that url gets the POST parameters as well

p.s. if using php, try to insert var_dump($_POST); in your return url(script),then make a test purchase and when you return back to your site you will see what variables are got on your url.

How do I check if a variable is of a certain type (compare two types) in C?

For that purpose I have written a simple C program for that... It is in github...GitHub Link

Here how it works... First convert your double into a char string named s..

char s[50];
sprintf(s,"%.2f", yo);

Then use my dtype function to determine the type... My function will return a single character...You can use it like this...

char type=dtype(s);
//Return types are :
//i for integer
//f for float or decimals
//c for character...

Then you can use comparison to check it... That's it...

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

This is what I would call a classically Apple Xcode UX design bug.

The error said there is a bunch of stuff YOU DID WRONG LOCALLY.

The error actually meant "we have a new agreement you did not accept online".

After checking and unchecking the Automatic Signing button, I got this agreement error to display

After checking and unchecking the Automatic Signing button I got this agreement error to display:

Signing into the developer portal I was able to see a banner for the agreement update notice

Signing into the developer portal I was able to see a banner for the agreement update notice:

Restarting Xcode 8 then cleared that error and only forced me to reselect the certificate I already had on my machine and tied to the project. Restarting Xcode 8 then cleared that error and only forced me to reselect the certificate I already had on my machine and tied to the project.

This could have been handled in a less confusing implementation, but this is how I fixed it. I am putting it here because it's way different than the steps everyone else gave.

Oh and yeah, having the pre-latest iOS 10 device and latest Xcode (I was on 7.3.1 or something) also threw errors until I updated.

Else clause on Python while statement

The better use of 'while: else:' construction in Python should be if no loop is executed in 'while' then the 'else' statement is executed. The way it works today doesn't make sense because you can use the code below with the same results...

n = 5
while n != 0:
    print n
    n -= 1
print "what the..."

How to compare two tables column by column in oracle

It won't be fast, and there will be a lot for you to type (unless you generate the SQL from user_tab_columns), but here is what I use when I need to compare two tables row-by-row and column-by-column.

The query will return all rows that

  • Exists in table1 but not in table2
  • Exists in table2 but not in table1
  • Exists in both tables, but have at least one column with a different value

(common identical rows will be excluded).

"PK" is the column(s) that make up your primary key. "a" will contain A if the present row exists in table1. "b" will contain B if the present row exists in table2.

select pk
      ,decode(a.rowid, null, null, 'A') as a
      ,decode(b.rowid, null, null, 'B') as b
      ,a.col1, b.col1
      ,a.col2, b.col2
      ,a.col3, b.col3
  from table1 a 
  full outer 
  join table2 b using(pk)
 where decode(a.col1, b.col1, 1, 0) = 0
    or decode(a.col2, b.col2, 1, 0) = 0
    or decode(a.col3, b.col3, 1, 0) = 0
    or ...;

Edit Added example code to show the difference described in comment. Whenever one of the values contains NULL, the result will be different.

with a as(
   select 0    as col1 from dual union all
   select 1    as col1 from dual union all
   select null as col1 from dual
,b as(
   select 1    as col1 from dual union all
   select 2    as col1 from dual union all
   select null as col1 from dual
select a.col1
      ,decode(a.col1, b.col1, 'Same', 'Different') as approach_1
      ,case when a.col1 <> b.col1 then 'Different' else 'Same' end as approach_2       
  from a,b
    by a.col1

col1   col1_1   approach_1  approach_2
====   ======   ==========  ==========
  0        1    Different   Different  
  0        2    Different   Different  
  0      null   Different   Same         <--- 
  1        1    Same        Same       
  1        2    Different   Different  
  1      null   Different   Same         <---
null       1    Different   Same         <---
null       2    Different   Same         <---
null     null   Same        Same       

How to do a newline in output

You can do this all in the block:

Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u' playlist_name, 'w' do |f|
  music.each do |z|
    f.puts z

How to show Alert Message like "successfully Inserted" after inserting to DB using MVC3

Try using TempData:

public ActionResult Create(FormCollection collection) {
  TempData["notice"] = "Successfully registered";
  return RedirectToAction("Index");

Then, in your Index view, or master page, etc., you can do this:

<% if (TempData["notice"] != null) { %>
  <p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>

Or, in a Razor view:

@if (TempData["notice"] != null) {

Quote from MSDN (page no longer exists as of 2014, archived copy here):

An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.

Release generating .pdb files, why?

PDB can be generated for Release as well as for Debug. This is set at (in VS2010 but in VS2005 must be similar):

Project ? Properties ? Build ? Advanced ? Debug Info

Just change it to None.

How to change the data type of a column without dropping the column with query?

ALTER TABLE table_name
MODIFY (column_name data_type);

Converting from longitude\latitude to Cartesian coordinates

I have recently done something similar to this using the "Haversine Formula" on WGS-84 data, which is a derivative of the "Law of Haversines" with very satisfying results.

Yes, WGS-84 assumes the Earth is an ellipsoid, but I believe you only get about a 0.5% average error using an approach like the "Haversine Formula", which may be an acceptable amount of error in your case. You will always have some amount of error unless you're talking about a distance of a few feet and even then there is theoretically curvature of the Earth... If you require a more rigidly WGS-84 compatible approach checkout the "Vincenty Formula."

I understand where starblue is coming from, but good software engineering is often about trade-offs, so it all depends on the accuracy you require for what you are doing. For example, the result calculated from "Manhattan Distance Formula" versus the result from the "Distance Formula" can be better for certain situations as it is computationally less expensive. Think "which point is closest?" scenarios where you don't need a precise distance measurement.

Regarding, the "Haversine Formula" it is easy to implement and is nice because it is using "Spherical Trigonometry" instead of a "Law of Cosines" based approach which is based on two-dimensional trigonometry, therefore you get a nice balance of accuracy over complexity.

A gentleman by the name of Chris Veness has a great website that explains some of the concepts you are interested in and demonstrates various programmatic implementations; this should answer your x/y conversion question as well.

How can I install an older version of a package via NuGet?

As of NuGet 2.8, there is a feature to downgrade a package.

NuGet 2.8 Release Notes


The following command entered into the Package Manager Console will downgrade the Couchbase client to version

Update-Package CouchbaseNetClient -Version


Updating 'CouchbaseNetClient' from version '1.3.3' to '' in project [project name].
Removing 'CouchbaseNetClient 1.3.3' from [project name].
Successfully removed 'CouchbaseNetClient 1.3.3' from [project name].

Something to note as per crimbo below:

This approach doesn't work for downgrading from one prerelease version to other prerelease version - it only works for downgrading to a release version

Move SQL Server 2008 database files to a new folder location

Some notes to complement the ALTER DATABASE process:

1) You can obtain a full list of databases with logical names and full paths of MDF and LDF files:

   USE master SELECT name, physical_name FROM sys.master_files

2) You can move manually the files with CMD move command:

Move "Source" "Destination"


md "D:\MSSQLData"
Move "C:\test\SYSADMIT-DB.mdf" "D:\MSSQLData\SYSADMIT-DB_Data.mdf"
Move "C:\test\SYSADMIT-DB_log.ldf" "D:\MSSQLData\SYSADMIT-DB_log.ldf"

3) You should change the default database path for new databases creation. The default path is obtained from the Windows registry.

You can also change with T-SQL, for example, to set default destination to: D:\MSSQLData

USE [master]


EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\MSSQLData'


EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'D:\MSSQLData'


Extracted from:

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();

PS. There's also ToArray() method that works in other way.

Tomcat is not deploying my web project from Eclipse

I encountered with same error and resolved it with redeployment after removing deployment.

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

SQL Left Join first match only

Depending on the nature of the duplicate rows, it looks like all you want is to have case-sensitivity on those columns. Setting the collation on these columns should be what you're after:

SELECT DISTINCT p.IDNO COLLATE SQL_Latin1_General_CP1_CI_AS, p.FirstName COLLATE SQL_Latin1_General_CP1_CI_AS, p.LastName COLLATE SQL_Latin1_General_CP1_CI_AS
FROM people P

Python Function to test ping

Adding on to the other answers, you can check the OS and decide whether to use "-c" or "-n":

import os, platform
host = ""
os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + host)

This will work on Windows, OS X, and Linux

You can also use sys:

import os, sys
host = ""
os.system("ping " + ("-n 1 " if  sys.platform().lower()=="win32" else "-c 1 ") + host)

Extract every nth element of a vector

a <- 1:120
b <- a[seq(1, length(a), 6)]

Position a div container on the right side

Is this what you wanted? -

Floats on both sides now




<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>

How to reload .bash_profile from the command line?

if the .bash_profile does not exist you can try run the following command:

. ~/.bashrc 


 source ~/.bashrc

instead of .bash_profile. You can find more information about bashrc

Apache: "AuthType not set!" 500 Error

I think that you have a version 2.4.x of Apache.

Have you sure that you load this 2 modules ? - mod_authn_core - mod_authz_core

LoadModule authn_core_module modules/
LoadModule authz_core_module modules/

PS : My recommendation for authorization and rights is (by default) :

LoadModule authn_file_module modules/
LoadModule authn_core_module modules/
LoadModule authz_host_module modules/
LoadModule authz_groupfile_module modules/
LoadModule authz_user_module modules/
LoadModule authz_core_module modules/
LoadModule auth_basic_module modules/
LoadModule auth_digest_module modules/

Laravel form html with PUT method for PUT routes

Just use like this somewhere inside the form


Looking to understand the iOS UIViewController lifecycle

iOS 10,11 (Swift 3.1,Swift 4.0)

According to UIViewController in UIKit developers,

1. loadView()

This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.

2. loadViewIfNeeded()

Loads the view controller's view if it has not already been set.

3. viewDidLoad()

Called after the view has been loaded. For view controllers created in code, this is after -loadView. For view controllers unarchived from a nib, this is after the view is set.

4. viewWillAppear(_ animated: Bool)

Called when the view is about to made visible. Default does nothing

5. viewWillLayoutSubviews()

Called just before the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. Default does nothing.

6. viewDidLayoutSubviews()

Called just after the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. Default does nothing.

7. viewDidAppear(_ animated: Bool)

Called when the view has been fully transitioned onto the screen. Default does nothing

8. viewWillDisappear(_ animated: Bool)

Called when the view is dismissed, covered or otherwise hidden. Default does nothing

9. viewDidDisappear(_ animated: Bool)

Called after the view was dismissed, covered or otherwise hidden. Default does nothing

10. viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)

Called when the view is Transitioning.

11. willMove(toParentViewController parent: UIViewController?)

12. didMove(toParentViewController parent: UIViewController?)

These two methods are public for container subclasses to call when transitioning between child controllers. If they are overridden, the overrides should ensure to call the super.

The parent argument in both of these methods is nil when a child is being removed from its parent; otherwise it is equal to the new parent view controller.

13. didReceiveMemoryWarning()

Called when the parent application receives a memory warning. On iOS 6.0 it will no longer clear the view by default.

How do I create 7-Zip archives with .NET?

I use this code

                string PZipPath = @"C:\Program Files\7-Zip\7z.exe";
                string sourceCompressDir = @"C:\Test";
                string targetCompressName = @"C:\Test\";
                string CompressName = targetCompressName.Split('\\').Last();
                string[] fileCompressList = Directory.GetFiles(sourceCompressDir, "*.*");

                    if (fileCompressList.Length == 0)
                        MessageBox.Show("No file in directory", "Important Message");
                    string filetozip = null;
                    foreach (string filename in fileCompressList)
                        filetozip = filetozip + "\"" + filename + " ";

                    ProcessStartInfo pCompress = new ProcessStartInfo();
                    pCompress.FileName = PZipPath;
                    if (chkRequestPWD.Checked == true)
                        pCompress.Arguments = "a -tzip \"" + targetCompressName + "\" " + filetozip + " -mx=9" + " -p" + tbPassword.Text;
                        pCompress.Arguments = "a -tzip \"" + targetCompressName + "\" \"" + filetozip + "\" -mx=9";
                    pCompress.WindowStyle = ProcessWindowStyle.Hidden;
                    Process x = Process.Start(pCompress);

JavaScript backslash (\) in variables is causing an error

You may want to try the following, which is more or less the standard way to escape user input:

function stringEscape(s) {
    return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
    function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }

This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.

Return rows in random order

The usual method is to use the NEWID() function, which generates a unique GUID. So,


How do I make the text box bigger in HTML/CSS?

If you want to make them a lot bigger, like for multiple lines of input, you may want to use a textarea tag instead of the input tag. This allows you to put in number of rows and columns you want on your textarea without messing with css (e.g. <textarea rows="2" cols="25"></textarea>).

Text areas are resizable by default. If you want to disable that, just use the resize css rule:

#signin textarea {
    resize: none;

A simple solution to your question about default text that disappears when the user clicks is to use the placeholder attribute. This will work for <input> tags as well.

<textarea rows="2" cols="25" placeholder="This is the default text"></textarea>

This text will disappear when the user enters information rather than when they click, but that is common functionality for this kind of thing.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

When I read in various places that hibernate didn't like you to assign to a collection, I assumed that the safest thing to do would obviously be to make it final like this:

class User {
  private final Set<Role> roles = new HashSet<>();

public void setRoles(Set<Role> roles) {

However, this doesn't work, and you get the dreaded "no longer referenced" error, which is actually quite misleading in this case.

It turns out that hibernate calls your setRoles method AND it wants its special collection class installed here, and won't accept your collection class. This had me stumped for a LONG time, despite reading all the warnings about not assigning to your collection in your set method.

So I changed to this:

public class User {
  private Set<Role> roles = null;

  public void setRoles(Set<Role> roles) {
  if (this.roles == null) {
    this.roles = roles;
  } else {

So that on the first call, hibernate installs its special class, and on subsequent calls you can use the method yourself without wrecking everything. If you want to use your class as a bean, you probably need a working setter, and this at least seems to work.

Calling a function in jQuery with click()


Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);

Find length of 2D array Python

You can also use np.size(a,1), 1 here is the axis and this will give you the number of columns

setTimeout in React Native

Classic javascript mistake.

setTimeout(function(){this.setState({timePassed: true})}, 1000)

When setTimeout runs this.setState, this is no longer CowtanApp, but window. If you define the function with the => notation, es6 will auto-bind this.

setTimeout(() => {this.setState({timePassed: true})}, 1000)

Alternatively, you could use a let that = this; at the top of your render, then switch your references to use the local variable.

render() {
  let that = this;
  setTimeout(function(){that.setState({timePassed: true})}, 1000);

If not working, use bind.

  function() {
      this.setState({timePassed: true});

Python RuntimeWarning: overflow encountered in long scalars

Here's an example which issues the same warning:

import numpy as np
A = np.array([10])


RuntimeWarning: overflow encountered in long_scalars

In the example above it happens because a is of dtype int32, and the maximim value storable in an int32 is 2**31-1. Since 10**10 > 2**32-1, the exponentiation results in a number that is bigger than that which can be stored in an int32.

Note that you can not rely on np.seterr(all='warn') to catch all overflow errors in numpy. For example, on 32-bit NumPy

>>> np.multiply.reduce(np.arange(21)+1)

while on 64-bit NumPy:

>>> np.multiply.reduce(np.arange(21)+1)

Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals

In [47]: import math

In [48]: math.factorial(21)
Out[50]: 51090942171709440000L

According to numpy developer, Robert Kern,

Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.

So the burden is on you to choose appropriate dtypes so that no operation overflows.

Facebook Like-Button - hide count?

Facebook now supports hiding the count, use this in the markup:


Today's Date in Perl in MM/DD/YYYY format

Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)

use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "\n";

This gives you:


Spring RestTemplate GET with parameters

I am providing a code snippet of RestTemplate GET method with path param example

public ResponseEntity<String> getName(int id) {
    final String url = "http://localhost:8080/springrestexample/employee/name?id={id}";
    Map<String, String> params = new HashMap<String, String>();
    params.put("id", id);
    HttpHeaders headers = new HttpHeaders();
    HttpEntity request = new HttpEntity(headers);
    ResponseEntity<String> response =, HttpMethod.GET, String.class, params);
    return response;

Creating an iframe with given HTML dynamically

Setting the src of a newly created iframe in javascript does not trigger the HTML parser until the element is inserted into the document. The HTML is then updated and the HTML parser will be invoked and process the attribute as expected.

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
console.log('iframe.contentWindow =', iframe.contentWindow);

Also this answer your question it's important to note that this approach has compatibility issues with some browsers, please see the answer of @mschr for a cross-browser solution.

Moment.js - two dates difference in number of days

Here's how you can get the comprehensive full fledge difference of two dates.

 function diffYMDHMS(date1, date2) {

    let years = date1.diff(date2, 'year');
    date2.add(years, 'years');

    let months = date1.diff(date2, 'months');
    date2.add(months, 'months');

    let days = date1.diff(date2, 'days');
    date2.add(days, 'days');

    let hours = date1.diff(date2, 'hours');
    date2.add(hours, 'hours');

    let minutes = date1.diff(date2, 'minutes');
    date2.add(minutes, 'minutes');

    let seconds = date1.diff(date2, 'seconds');

    console.log(years + ' years ' + months + ' months ' + days + ' days ' + hours + ' 
    hours ' + minutes + ' minutes ' + seconds + ' seconds'); 

    return { years, months, days, hours, minutes, seconds};

Unable to cast object of type 'System.DBNull' to type 'System.String`

String.Concat transforms DBNull and null values to an empty string.

public string GetCustomerNumber(Guid id)
   object accountNumber =  
                                new SqlParameter("@id", id));

    return String.Concat(accountNumber);


However, I think you lose something on code understandability

how to print json data in console.log

{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}

console.dir() will do what you need. It will give you a hierarchical structure of the data.


like so

> Object
  > input_data: Object
      price-row_122: " 35.1 "
      quantity-row_122: "1"
    success: true

I don't think you need console.log(JSON.stringify(data)).

To get the data you can do this without stringify:

console.log(data.success); // true
console.log(data.input_data['quantity-row_122']) // "1"
console.log(data.input_data['price-row_122']) // " 35.1 "


The value from input_data Object will be typeof "1": String, but you can convert to number(Int or Float) using ParseInt or ParseFloat, like so:

 typeof parseFloat(data.input_data['price-row_122'], 10) // "number"
 parseFloat(data.input_data['price-row_122'], 10) // 35.1

Setting width and height

You can override the canvas style width !important ...


  width:1000px !important;
  height:600px !important;



specify responsive:true, property under options..

options: {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
        yAxes: [{
            ticks: {

update under options added : maintainAspectRatio: false,

link :

How to echo xml file in php

Am I oversimplifying this?

$location = "";
print file_get_contents($location);

Some places (like won't allow you to access their site without having a user-agent, in which case you would need to set that with ini_set() prior to running the file_get_contents().

How to use Oracle's LISTAGG function with a unique filter?

select group_id, 
       listagg(name, ',') within group (order by name) as names
       over (partition by group_id)   
from demotable
group by group_id 

Is there an equivalent to background-size: cover and contain for image elements?

There is actually quite a simple css solution which even works on IE8:

.container {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  /* Width and height can be anything. */_x000D_
  width: 50vw;_x000D_
  height: 50vh;_x000D_
img {_x000D_
  position: absolute;_x000D_
  /* Position the image in the middle of its container. */_x000D_
  top: -9999px;_x000D_
  right: -9999px;_x000D_
  bottom: -9999px;_x000D_
  left: -9999px;_x000D_
  margin: auto;_x000D_
  /* The following values determine the exact image behaviour. */_x000D_
  /* You can simulate background-size: cover/contain/etc._x000D_
     by changing between min/max/standard width/height values._x000D_
     These values simulate background-size: cover_x000D_
  min-width: 100%;_x000D_
  min-height: 100%;_x000D_
<div class="container">_x000D_
    <img src="" alt="" />_x000D_

Checking version of angular-cli that's installed?

You can use npm list -global to list all the component versions currently installed on your system.
For viewing specific lists at different levels use --depth.


npm list -global --depth 0

new Image(), how to know if image 100% loaded or not?

Use the load event:

img = new Image();

img.onload = function(){
  // image  has been loaded

img.src = image_url;

Also have a look at:

Conda: Installing / upgrading directly from github

I found a reference to this in condas issues. The following should now work.

name: sample_env
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line


If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Express: How to pass app-instance to routes from a different file?

Let's say that you have a folder named "contollers".

In your app.js you can put this code:

console.log("Loading controllers....");
var controllers = {};

var controllers_path = process.cwd() + '/controllers'

fs.readdirSync(controllers_path).forEach(function (file) {
    if (file.indexOf('.js') != -1) {
        controllers[file.split('.')[0]] = require(controllers_path + '/' + file)

console.log("Controllers loaded..............[ok]");

... and ...


in your controllers forlder you will have the file "ping.js" with this code:

exports.pinging = function(req, res, next){
    console.log("ping ...");

And this is it....