Programs & Examples On #Pkcs#1

PKCS #1 is a standard that defines the RSA algorithm and padding schemes.

Converting PKCS#12 certificate into PEM using OpenSSL

If you can use Python, it is even easier if you have the pyopenssl module. Here it is:

from OpenSSL import crypto

# May require "" for empty password depending on version

with open("push.p12", "rb") as file:
    p12 = crypto.load_pkcs12(, "my_passphrase")

# PEM formatted private key
print crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())

# PEM formatted certificate
print crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_certificate())

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

This is possible with a bit of format conversion.

To extract the private key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa

To convert the private key to a public key:

openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8

To extract the public key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8

Java HTTPS client certificate authentication

There is a better way than having to manually navigate to https://url , knowing what button to click in what browser, knowing where and how to save the "certificate" file and finally knowing the magic incantation for the keytool to install it locally.

Just do this:

  1. Save code below to
  2. Open command line and execute: javac
  3. Run like: java InstallCert <host>[:port] [passphrase] (port and passphrase are optional)

Here is the code for InstallCert, note the year in header, will need to modify some parts for "later" versions of java:

 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.




public class InstallCert {

    public static void main(String[] args) throws Exception {
  String host;
  int port;
  char[] passphrase;
  if ((args.length == 1) || (args.length == 2)) {
      String[] c = args[0].split(":");
      host = c[0];
      port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
      String p = (args.length == 1) ? "changeit" : args[1];
      passphrase = p.toCharArray();
  } else {
      System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");

  File file = new File("jssecacerts");
  if (file.isFile() == false) {
      char SEP = File.separatorChar;
      File dir = new File(System.getProperty("java.home") + SEP
        + "lib" + SEP + "security");
      file = new File(dir, "jssecacerts");
      if (file.isFile() == false) {
    file = new File(dir, "cacerts");
  System.out.println("Loading KeyStore " + file + "...");
  InputStream in = new FileInputStream(file);
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(in, passphrase);

  SSLContext context = SSLContext.getInstance("TLS");
  TrustManagerFactory tmf =
  X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
  SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  context.init(null, new TrustManager[] {tm}, null);
  SSLSocketFactory factory = context.getSocketFactory();

  System.out.println("Opening connection to " + host + ":" + port + "...");
  SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
  try {
      System.out.println("Starting SSL handshake...");
      System.out.println("No errors, certificate is already trusted");
  } catch (SSLException e) {

  X509Certificate[] chain = tm.chain;
  if (chain == null) {
      System.out.println("Could not obtain server certificate chain");

  BufferedReader reader =
    new BufferedReader(new InputStreamReader(;

  System.out.println("Server sent " + chain.length + " certificate(s):");
  MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  MessageDigest md5 = MessageDigest.getInstance("MD5");
  for (int i = 0; i < chain.length; i++) {
      X509Certificate cert = chain[i];
        (" " + (i + 1) + " Subject " + cert.getSubjectDN());
      System.out.println("   Issuer  " + cert.getIssuerDN());
      System.out.println("   sha1    " + toHexString(sha1.digest()));
      System.out.println("   md5     " + toHexString(md5.digest()));

  System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
  String line = reader.readLine().trim();
  int k;
  try {
      k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
  } catch (NumberFormatException e) {
      System.out.println("KeyStore not changed");

  X509Certificate cert = chain[k];
  String alias = host + "-" + (k + 1);
  ks.setCertificateEntry(alias, cert);

  OutputStream out = new FileOutputStream("jssecacerts");, passphrase);

    ("Added certificate to keystore 'jssecacerts' using alias '"
    + alias + "'");

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
  StringBuilder sb = new StringBuilder(bytes.length * 3);
  for (int b : bytes) {
      b &= 0xff;
      sb.append(HEXDIGITS[b >> 4]);
      sb.append(HEXDIGITS[b & 15]);
      sb.append(' ');
  return sb.toString();

    private static class SavingTrustManager implements X509TrustManager {

  private final X509TrustManager tm;
  private X509Certificate[] chain;

  SavingTrustManager(X509TrustManager tm) { = tm;

  public X509Certificate[] getAcceptedIssuers() {
      throw new UnsupportedOperationException();

  public void checkClientTrusted(X509Certificate[] chain, String authType)
    throws CertificateException {
      throw new UnsupportedOperationException();

  public void checkServerTrusted(X509Certificate[] chain, String authType)
    throws CertificateException {
      this.chain = chain;
      tm.checkServerTrusted(chain, authType);


Python locale error: unsupported locale setting

For those deploying a docker image and using a locale that isn't shown in the locale -a command, add this line to your Dockerfile
RUN apt-get install -y locales

This should add all locales to your image, I used de_DE which is not part of AWS default Ubuntu server.

How set background drawable programmatically in Android

Inside the app/res/your_xml_layout_file.xml

  1. Assign a name to your parent layout.
  2. Go to your MainActivity and find your RelativeLayout by calling the findViewById("given_name").
  3. Use the layout as a classic Object, by calling the method setBackgroundColor().

Finding all the subsets of a set

It's very simple to do this recursively. The basic idea is that for each element, the set of subsets can be divided equally into those that contain that element and those that don't, and those two sets are otherwise equal.

  • For n=1, the set of subsets is {{}, {1}}
  • For n>1, find the set of subsets of 1,...,n-1 and make two copies of it. For one of them, add n to each subset. Then take the union of the two copies.

Edit To make it crystal clear:

  • The set of subsets of {1} is {{}, {1}}
  • For {1, 2}, take {{}, {1}}, add 2 to each subset to get {{2}, {1, 2}} and take the union with {{}, {1}} to get {{}, {1}, {2}, {1, 2}}
  • Repeat till you reach n

<code> vs <pre> vs <samp> for inline and block code snippets

Consider TextArea

People finding this via Google and looking for a better way to manage the display of their snippets should also consider <textarea> which gives a lot of control over width/height, scrolling etc. Noting that @vsync mentioned the deprecated tag <xmp>, I find <textarea readonly> is an excellent substitute for displaying HTML without the need to escape anything inside it (except where </textarea> might appear within).

For example, to display a single line with controlled line wrapping, consider <textarea rows=1 cols=100 readonly> your html or etc with any characters including tabs and CrLf's </textarea>.

<textarea rows=5 cols=100 readonly>Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_

To compare all...

<h2>Compared: TEXTAREA, XMP, PRE, SAMP, CODE</h2>_x000D_
<p>Note that CSS can be used to override default fixed space fonts in each or all these.</p>_x000D_
<textarea rows=5 cols=100 readonly>TEXTAREA: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>displayed natively</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;</textarea>_x000D_
<xmp>XMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>displayed natively</b>._x000D_
    However, note that &amp; (&) will not act as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
<pre>PRE: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>are interpreted, not displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
<samp>SAMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>are interpreted, not displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
<code>CODE: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>are interpreted, not displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_

Show a PDF files in users browser via PHP/Perl

You can also use fpdf class available at: It gives options for both outputting to a file and displaying on browser.

Twitter Bootstrap onclick event on buttons-radio

For Bootstrap 3 the default radio/button-group structure is :

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option1"> Option 1
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option2"> Option 2
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option3"> Option 3

And you can select the active one like this:

$('.btn-primary').on('click', function(){

Convert char to int in C and C++

I was having problems converting a char array like "7c7c7d7d7d7d7c7c7c7d7d7d7d7c7c7c7c7c7c7d7d7c7c7c7c7d7c7d7d7d7c7c2e2e2e" into its actual integer value that would be able to be represented by `7C' as one hexadecimal value. So, after cruising for help I created this, and thought it would be cool to share.

This separates the char string into its right integers, and may be helpful to more people than just me ;)

unsigned int* char2int(char *a, int len)
    int i,u;
    unsigned int *val = malloc(len*sizeof(unsigned long));

            if(a[i] <= 57)
                val[u] = (a[i]-50)<<4;
                val[u] = (a[i]-55)<<4;
            if(a[i] <= 57)
                val[u] += (a[i]-50);
                val[u] += (a[i]-55);
    return val;

Hope it helps!

SQL Row_Number() function in Where Clause

 select salary from (
 select  Salary, ROW_NUMBER() over (order by Salary desc) rn from Employee 
 ) t where t.rn = 2

List file names based on a filename pattern and file content?

Assume LMN2011* files are inside /home/me but skipping anything in /home/me/temp or below:

find /home/me -name 'LMN2011*' -not -path "/home/me/temp/*" -print | xargs grep 'LMN20113456'

How do you clear a slice in Go?

It all depends on what is your definition of 'clear'. One of the valid ones certainly is:

slice = slice[:0]

But there's a catch. If slice elements are of type T:

var slice []T

then enforcing len(slice) to be zero, by the above "trick", doesn't make any element of


eligible for garbage collection. This might be the optimal approach in some scenarios. But it might also be a cause of "memory leaks" - memory not used, but potentially reachable (after re-slicing of 'slice') and thus not garbage "collectable".

Twitter bootstrap scrollable modal

In case of using .modal {overflow-y: auto;}, would create additional scroll bar on the right of the page, when body is already overflowed.

The work around for this is to remove overflow from the body tag temporarily and set modal overflow-y to auto.


$('.myModalSelector').on('', function () {

        // Store initial body overflow value
        _initial_body_overflow = $('body').css('overflow');

        // Let modal be scrollable
        $(this).css('overflow-y', 'auto');
        $('body').css('overflow', 'hidden');

    }).on('', function () {

        // Reverse previous initialization
        $(this).css('overflow-y', 'hidden');
        $('body').css('overflow', _initial_body_overflow);

iOS: UIButton resize according to text length


The important thing here is when will you call the .sizeToFit() , it should be after setting the text to display so it can read the size needed, if you later update text, then call it again.

var button = UIButton()
button.setTitle("Length of this text determines size", forState: UIControlState.Normal)

How to schedule a periodic task in Java?

Have you tried Spring Scheduler using annotations ?

@Scheduled(cron = "0 0 0/8 ? * * *")
public void scheduledMethodNoReturnValue(){
    //body can be another method call which returns some value.

you can do this with xml as well.

   <task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"

jQuery ajax upload file in mvc

You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.

Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.

Fragments within Fragments

If you find your nested fragment not being removed or being duplicated (eg. on Activity restart, on screen rotate) try changing:

transaction.add(, newFragment);


transaction.replace(, newFragment);

If above doesn't help, try:

Fragment f = getChildFragmentManager().findFragmentById(;

FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

if (f == null) {
    Log.d(TAG, "onCreateView: fragment doesn't exist");
    newFragment= new MyFragmentType();
    transaction.add(, newFragment);
} else {
    Log.d(TAG, "onCreateView: fragment already exists");
    transaction.replace(, f);

Learnt here

From a Sybase Database, how I can get table description ( field names and types)?

Here a different approach to get meta data. This very helpful SQL command returns you the table / view definition as text:

SELECT text FROM syscomments WHERE id = OBJECT_ID('MySchema.MyTable') ORDER BY number, colid2, colid

Enjoy Patrick

How do I find out what version of WordPress is running?

The easiest way would be to use the readme.html file that comes with every WordPress installation (unless you deleted it).

Note: it looks like the readme.html file no longer outputs the current WordPress version. So, there is no way, for now, to see the current WordPress version without logging into the dashboard.

How do I copy a folder from remote to local using scp?

scp -r [email protected]:/path/to/foo /home/user/Desktop/

By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.

From man scp (See online manual)

-r Recursively copy entire directories

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");

        } catch (Exception e) {

How to get the instance id from within an ec2 instance?

For PHP:

$instance = json_decode(file_get_contents(';
$id = $instance['instanceId'];

Edit per @John

The response content cannot be parsed because the Internet Explorer engine is not available, or

It is sure because the Invoke-WebRequest command has a dependency on the Internet Explorer assemblies and are invoking it to parse the result as per default behaviour. As Matt suggest, you can simply launch IE and make your selection in the settings prompt which is popping up at first launch. And the error you experience will disappear.

But this is only possible if you run your powershell scripts as the same windows user as whom you launched the IE with. The IE settings are stored under your current windows profile. So if you, like me run your task in a scheduler on a server as the SYSTEM user, this will not work.

So here you will have to change your scripts and add the -UseBasicParsing argument, as ijn this example: $WebResponse = Invoke-WebRequest -Uri $url -TimeoutSec 1800 -ErrorAction:Stop -Method:Post -Headers $headers -UseBasicParsing

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

I would make two changes:

<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
  1. Use the onclick handler instead of onchange - you're changing the "checked state" of the radio input, not the value, so there's not a change event happening.
  2. Use a single function, and pass this as a parameter, that will make it easy to check which value is currently selected.

ETA: Along with your handleClick() function, you can track the original / old value of the radio in a page-scoped variable. That is:

var currentValue = 0;
function handleClick(myRadio) {
    alert('Old value: ' + currentValue);
    alert('New value: ' + myRadio.value);
    currentValue = myRadio.value;

var currentValue = 0;_x000D_
function handleClick(myRadio) {_x000D_
    alert('Old value: ' + currentValue);_x000D_
    alert('New value: ' + myRadio.value);_x000D_
    currentValue = myRadio.value;_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />

How to select data from 30 days?

Short version for easy use:

FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.

Best algorithm for detecting cycles in a directed graph

The simplest way to do it is to do a depth first traversal (DFT) of the graph.

If the graph has n vertices, this is a O(n) time complexity algorithm. Since you will possibly have to do a DFT starting from each vertex, the total complexity becomes O(n^2).

You have to maintain a stack containing all vertices in the current depth first traversal, with its first element being the root node. If you come across an element which is already in the stack during the DFT, then you have a cycle.

MySQL and PHP - insert NULL rather than empty string

For some reason, radhoo's solution wouldn't work for me. When I used the following expression:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')?"NULL":("'".$val1."'")) . ", ".
    (($val2=='')?"NULL":("'".$val2."'")) . 

'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')? :("'".$val1."'")) . ", ".
    (($val2=='')? :("'".$val2."'")) . 

The blank resulted in the correct null (unquoted) being inserted into the query.

How can I exclude one word with grep?

I've a directory with a bunch of files. I want to find all the files that DO NOT contain the string "speedup" so I successfully used the following command:

grep -iL speedup *

How to check for null/empty/whitespace values with a single test?

SELECT column_name from table_name
WHERE RTRIM(ISNULL(column_name, '')) LIKE ''

ISNULL(column_name, '') will return '' if column_name is NULL, otherwise it will return column_name.


In Oracle, you can use NVL to achieve the same results.

SELECT column_name from table_name
WHERE RTRIM(NVL(column_name, '')) LIKE ''

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

It says it all IsNullOrEmpty() does not include white spacing while IsNullOrWhiteSpace() does!

IsNullOrEmpty() If string is:

IsNullOrWhiteSpace() If string is:
-Contains White Spaces Only

Sort a List of Object in VB.NET

To sort by a property in the object, you have to specify a comparer or a method to get that property.

Using the List.Sort method:

theList.Sort(Function(x, y) x.age.CompareTo(y.age))

Using the OrderBy extension method:

theList = theList.OrderBy(Function(x) x.age).ToList()

jQuery event for images loaded

If you want to check for not all images, but a specific one (eg. an image that you replaced dynamically after DOM is already complete) you can use this:

$('#myImage').attr('src', 'image.jpg').on("load", function() {  
  alert('Image Loaded');  

How to print variable addresses in C?

You want to use %p to print a pointer. From the spec:

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

And don't forget the cast, e.g.


Erase the current printed console line

Just found this old thread, looking for some kind of escape sequence to blank the actual line.

It's quite funny no one came to the idea (or I have missed it) that printf returns the number of characters written. So just print '\r' + as many blank characters as printf returned and you will exactly blank the previuosly written text.

int BlankBytes(int Bytes)
                char strBlankStr[16];

                sprintf(strBlankStr, "\r%%%is\r", Bytes);

                return 0;

int main(void)
                int iBytesWritten;
                double lfSomeDouble = 150.0;

                iBytesWritten = printf("test text %lf", lfSomeDouble);


                return 0;

As I cant use VT100, it seems I have to stick with that solution

Android ListView not refreshing after notifyDataSetChanged

If the adapter is already set, setting it again will not refresh the listview. Instead first check if the listview has a adapter and then call the appropriate method.

I think its not a very good idea to create a new instance of the adapter while setting the list view. Instead, create an object.

BuildingAdapter adapter = new BuildingAdapter(context);

    if(getListView().getAdapter() == null){ //Adapter not set yet.
    else{ //Already has an adapter

Also you might try to run the refresh list on UI Thread:

activity.runOnUiThread(new Runnable() {         
        public void run() {
              //do your modifications here

              // for example    
              adapter.add(new Object());

How to filter rows in pandas by regex

Use contains instead:

In [10]: df.b.str.contains('^f')
0    False
1     True
2     True
3    False
Name: b, dtype: bool

How can I style the border and title bar of a window in WPF?

You need to set

WindowStyle="None", AllowsTransparency="True" and optionally ResizeMode="NoResize"
and then set the Style property of the window to your custom window style, where you design the appearance of the window (title bar, buttons, border) to anything you want and display the window contents in a ContentPresenter.

This seems to be a good article on how you can achieve this, but there are many other articles on the internet.

How to get all keys with their values in redis

Tried the given example, but over VPN and with 400k+ keys it was too slow for me. Also it did not give me the key objects.

I wrote a small Python called tool redis-mass-get to combine KEYS and MGET requests against Redis:

# installation:
pip install redis-mass-get

# pipeline example CSV:
redis-mass-get -f csv -och redis://my.redis.url product:* | less

# write to json-file example with progress indicator:
redis-mass-get -d results.json -jd redis://my.redis.url product:*

It supports JSON, CSV and TXT output to file or stdout for usage in pipes. More info can be found at: Reading multiple key/values from Redis.

Who sets response content-type in Spring MVC (@ResponseBody)

if none of the above worked for you try to make ajax requests on "POST" not "GET" , that worked for me nicely ... none of the above did. I also have the characterEncodingFilter.

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices

For more information on the format models you can use with TO_CHAR on a date, see

How to escape a single quote inside awk

This maybe what you're looking for:

awk 'BEGIN {FS=" ";} {printf "'\''%s'\'' ", $1}'

That is, with '\'' you close the opening ', then print a literal ' by escaping it and finally open the ' again.

How do I edit $PATH (.bash_profile) on OSX?

In Macbook, step by step:

  1. First of all open terminal and write it: cd ~/
  2. Create your bash file: touch .bash_profile

You created your ".bash_profile" file but if you would like to edit it, you should write it;

  1. Edit your bash profile: open -e .bash_profile

After you can save from top-left corner of screen: File > Save


True/False vs 0/1 in MySQL

Bit is also an option if tinyint isn't to your liking. A few links:

Not surprisingly, more info about numeric types is available in the manual.

One more link:

And a quote from the comment section of the article above:

  • TINYINT(1) isn’t a synonym for bit(1).
  • TINYINT(1) can store -9 to 9.
  • BIT(1): 0, 1. (Bit, literally).

Edit: This edit (and answer) is only remotely related to the original question...

Additional quotes by Justin Rovang and the author maclochlainn (comment section of the linked article).

Excuse me, seems I’ve fallen victim to substr-ism: TINYINT(1): -128-+127 TINYINT(1) UNSIGNED: 0-255 (Justin Rovang 25 Aug 11 at 4:32 pm)

True enough, but the post was about what PHPMyAdmin listed as a Boolean, and there it only uses 0 or 1 from the entire wide range of 256 possibilities. (maclochlainn 25 Aug 11 at 11:35 pm)

how to set JAVA_OPTS for Tomcat in Windows?


set JAVA_OPTS=%JAVA_OPTS% -Xms512M -Xmx1024M

Select a Column in SQL not in Group By

The columns in the result set of a select query with group by clause must be:

  • an expression used as one of the group by criteria , or ...
  • an aggregate function , or ...
  • a literal value

So, you can't do what you want to do in a single, simple query. The first thing to do is state your problem statement in a clear way, something like:

I want to find the individual claim row bearing the most recent creation date within each group in my claims table


create table dbo.some_claims_table
  claim_id     int      not null ,
  group_id     int      not null ,
  date_created datetime not null ,

  constraint some_table_PK primary key ( claim_id                ) ,
  constraint some_table_AK01 unique    ( group_id , claim_id     ) ,
  constraint some_Table_AK02 unique    ( group_id , date_created ) ,


The first thing to do is identify the most recent creation date for each group:

select group_id ,
       date_created = max( date_created )
from dbo.claims_table
group by group_id

That gives you the selection criteria you need (1 row per group, with 2 columns: group_id and the highwater created date) to fullfill the 1st part of the requirement (selecting the individual row from each group. That needs to be a virtual table in your final select query:

select *
from dbo.claims_table t
join ( select group_id ,
       date_created = max( date_created )
       from dbo.claims_table
       group by group_id
      ) x on x.group_id     = t.group_id
         and x.date_created = t.date_created

If the table is not unique by date_created within group_id (AK02), you you can get duplicate rows for a given group.

Send Mail to multiple Recipients in java

InternetAddress.Parse is going to be your friend! See the worked example below:

String to = "[email protected], [email protected], [email protected]";
String toCommaAndSpaces = "[email protected] [email protected], [email protected]";
  1. Parse a comma-separated list of email addresses. Be strict. Require comma separated list.
  2. If strict is true, many (but not all) of the RFC822 syntax rules for emails are enforced.

    InternetAddress.parse(to, true));
  3. Parse comma/space-separated list. Cut some slack. We allow spaces seperated list as well, plus invalid email formats.

    InternetAddress.parse(toCommaAndSpaces, false));

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

Raising a number to a power in Java

^ in java does not mean to raise to a power. It means XOR.

You can use java's Math.pow()

And you might want to consider using double instead of int—that is:

double height;
double weight;

Note that 199/100 evaluates to 1.

Cheap way to search a large text file for a string

I like the solution of Javier. I did not try it, but it sounds cool!

For reading through a arbitary large text and wanting to know it a string exists, replace it, you can use Flashtext, which is faster than Regex with very large files.


From the developer page:

>>> from flashtext import KeywordProcessor
>>> keyword_processor = KeywordProcessor()
>>> # keyword_processor.add_keyword(<unclean name>, <standardised name>)
>>> keyword_processor.add_keyword('Big Apple', 'New York')
>>> keyword_processor.add_keyword('Bay Area')
>>> keywords_found = keyword_processor.extract_keywords('I love Big Apple and Bay Area.')
>>> keywords_found
>>> # ['New York', 'Bay Area']

Or when extracting the offset:

>>> from flashtext import KeywordProcessor
>>> keyword_processor = KeywordProcessor()
>>> keyword_processor.add_keyword('Big Apple', 'New York')
>>> keyword_processor.add_keyword('Bay Area')
>>> keywords_found = keyword_processor.extract_keywords('I love big Apple and Bay Area.', span_info=True)
>>> keywords_found
>>> # [('New York', 7, 16), ('Bay Area', 21, 29)]

Center Plot title in ggplot2

From the release news of ggplot 2.2.0: "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title argument in ?theme: "left-aligned by default".

As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5)) to center the title.

ggplot() +
  ggtitle("Default in 2.2.0 is left-aligned")

enter image description here

ggplot() +
  ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
  theme(plot.title = element_text(hjust = 0.5))

enter image description here

Save ArrayList to SharedPreferences

As @nirav said, best solution is store it in sharedPrefernces as a json text by using Gson utility class. Below sample code:

//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson

//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString("key", jsonText);

How to compare DateTime in C#?

MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.

The conventional operators

are available for DateTime since .NET Framework 1.1. Also, addition and subtraction of DateTime objects are also possible using conventional operators + and -.

One example from MSDN:

System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);

// areEqual gets false.
bool areEqual = april19 == otherDate;

otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;

Other operators can be used likewise.

Here is the list all operators available for DateTime.

IE8 issue with Twitter Bootstrap 3

Don't forget to place your css links in the <head> as respond.js takes only those.

How to restart VScode after editing extension's config?

Execute the workbench.action.reloadWindow command.

There are some ways to do so:

  1. Open the command palette (Ctrl + Shift + P) and execute the command:

    >Reload Window    
  2. Define a keybinding for the command (for example CTRL+F5) in keybindings.json:

        "key": "ctrl+f5",
        "command": "workbench.action.reloadWindow",
        "when": "editorTextFocus"

Font-awesome, input type 'submit'

With multiple submits, when you need the value of the submit selected, this can be done quite easily. Just create a hidden field in your form and change its value depending on what button is clicked. For example, in the form, say you have:

<input type="hidden" id="Clicked" name="Clicked" value="" />
<button type="submit" class="btn btn-success ClickCheck" id="Create"> <i class="fa fa-file-pdf-o"> Create Bill</i></button>
<button type="submit" class="btn btn-success ClickCheck" id="Reset"> <i class="fa fa-times"> Reset</i></button>
<button type="submit" class="btn btn-success ClickCheck" id="StoreData"> <i class="fa fa-archive"> Save</i></button>

Using jQuery:

<script type="text/javascript">
            var ButtonID = $(this).attr('id');

Then you can retrieve the value of the button clicked in the "Clicked" post variable

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

Have a reloadData for a UITableView animate when changing

Have more freedom using CATransition class.

It isn't limited to fading, but can do movements as well..

For example:

(don't forget to import QuartzCore)

CATransition *transition = [CATransition animation];
transition.type = kCATransitionPush;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.fillMode = kCAFillModeForwards;
transition.duration = 0.5;
transition.subtype = kCATransitionFromBottom;

[[self.tableView layer] addAnimation:transition forKey:@"UITableViewReloadDataAnimationKey"];

Change the type to match your needs, like kCATransitionFade etc.

Implementation in Swift:

let transition = CATransition()
transition.type = kCATransitionPush
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.fillMode = kCAFillModeForwards
transition.duration = 0.5
transition.subtype = kCATransitionFromTop
self.tableView.layer.addAnimation(transition, forKey: "UITableViewReloadDataAnimationKey")
// Update your data source here

Reference for CATransition

Swift 5:

let transition = CATransition()
transition.type = CATransitionType.push
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
transition.fillMode = CAMediaTimingFillMode.forwards
transition.duration = 0.5
transition.subtype = CATransitionSubtype.fromTop
self.tableView.layer.add(transition, forKey: "UITableViewReloadDataAnimationKey")
// Update your data source here

How do I use namespaces with TypeScript external modules?

OP I'm with you man. again too, there is nothing wrong with that answer with 300+ up votes, but my opinion is:

  1. what is wrong with putting classes into their cozy warm own files individually? I mean this will make things looks much better right? (or someone just like a 1000 line file for all the models)

  2. so then, if the first one will be achieved, we have to import import import... import just in each of the model files like man, srsly, a model file, a .d.ts file, why there are so many *s in there? it should just be simple, tidy, and that's it. Why I need imports there? why? C# got namespaces for a reason.

  3. And by then, you are literally using "filenames.ts" as identifiers. As identifiers... Come on its 2017 now and we still do that? Ima go back to Mars and sleep for another 1000 years.

So sadly, my answer is: nop, you cannot make the "namespace" thing functional if you do not using all those imports or using those filenames as identifiers (which I think is really silly). Another option is: put all of those dependencies into a box called filenameasidentifier.ts and use

export namespace(or module) boxInBox {} .

wrap them so they wont try to access other classes with same name when they are just simply trying to get a reference from the class sit right on top of them.

How to create a foreign key in phpmyadmin

You can do it the old fashioned way... with an SQL statement that looks something like this

ALTER TABLE table_name
    ADD CONSTRAINT fk_foreign_key_name
    FOREIGN KEY (foreign_key_name)
    REFERENCES target_table(target_key_name);

This assumes the keys already exist in the relevant table

Find size and free space of the filesystem containing a given file

If you just need the free space on a device, see the answer using os.statvfs() below.

If you also need the device name and mount point associated with the file, you should call an external program to get this information. df will provide all the information you need -- when called as df filename it prints a line about the partition that contains the file.

To give an example:

import subprocess
df = subprocess.Popen(["df", "filename"], stdout=subprocess.PIPE)
output = df.communicate()[0]
device, size, used, available, percent, mountpoint = \

Note that this is rather brittle, since it depends on the exact format of the df output, but I'm not aware of a more robust solution. (There are a few solutions relying on the /proc filesystem below that are even less portable than this one.)

How to pass an ArrayList to a varargs method parameter?

In Java 8:

List<WorldLocation> locations = new ArrayList<>();


Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

What is the command for cut copy paste a file from one directory to other directory

mv in unix-ish systems, move in dos/windows.


C:\> move c:\users\you\somefile.txt   c:\temp\newlocation.txt


$ mv /home/you/somefile.txt /tmp/newlocation.txt

Convert seconds into days, hours, minutes and seconds

Based on the answer by Julian Moreno, but changed to give the response as a string (not an array), only include the time intervals required and not assume the plural.

The difference between this and the highest voted answer is:

For 259264 seconds, this code would give

3 days, 1 minute, 4 seconds

For 259264 seconds, the highest voted answer (by Glavic) would give

3 days, 0 hours, 1 minutes and 4 seconds

function secondsToTime($inputSeconds) {
    $secondsInAMinute = 60;
    $secondsInAnHour = 60 * $secondsInAMinute;
    $secondsInADay = 24 * $secondsInAnHour;

    // Extract days
    $days = floor($inputSeconds / $secondsInADay);

    // Extract hours
    $hourSeconds = $inputSeconds % $secondsInADay;
    $hours = floor($hourSeconds / $secondsInAnHour);

    // Extract minutes
    $minuteSeconds = $hourSeconds % $secondsInAnHour;
    $minutes = floor($minuteSeconds / $secondsInAMinute);

    // Extract the remaining seconds
    $remainingSeconds = $minuteSeconds % $secondsInAMinute;
    $seconds = ceil($remainingSeconds);

    // Format and return
    $timeParts = [];
    $sections = [
        'day' => (int)$days,
        'hour' => (int)$hours,
        'minute' => (int)$minutes,
        'second' => (int)$seconds,

    foreach ($sections as $name => $value){
        if ($value > 0){
            $timeParts[] = $value. ' '.$name.($value == 1 ? '' : 's');

    return implode(', ', $timeParts);

I hope this helps someone.

What is the difference between Document style and RPC style communication?

In WSDL definition, bindings contain operations, here comes style for each operation.

Document : In WSDL file, it specifies types details either having inline Or imports XSD document, which describes the structure(i.e. schema) of the complex data types being exchanged by those service methods which makes loosely coupled. Document style is default.

  • Advantage:
    • Using this Document style, we can validate SOAP messages against predefined schema. It supports xml datatypes and patterns.
    • loosely coupled.
  • Disadvantage: It is a little bit hard to get understand.

In WSDL types element looks as follows:

  <xsd:import schemaLocation="http://localhost:9999/ws/hello?xsd=1" namespace=""/>

The schema is importing from external reference.

RPC :In WSDL file, it does not creates types schema, within message elements it defines name and type attributes which makes tightly coupled.

<message name="getHelloWorldAsString">  
<part name="arg0" type="xsd:string"/>  
<message name="getHelloWorldAsStringResponse">  
<part name="return" type="xsd:string"/>  
  • Advantage: Easy to understand.
  • Disadvantage:
    • we can not validate SOAP messages.
    • tightly coupled

RPC : No types in WSDL
Document: Types section would be available in WSDL

Searching for file in directories recursively

Using EnumerateFiles to get files in nested directories. Use AllDirectories to recurse throught directories.

using System;
using System.IO;

class Program
    static void Main()
    // Call EnumerateFiles in a foreach-loop.
    foreach (string file in Directory.EnumerateFiles(@"c:\files",
        // Display file path.

How to draw circle by canvas in Android?

If you are using your own CustomView extending View class, you need to call canvas.invalidate() method which will internally call onDraw method. You can use default API for canvas to draw a circle. The x, y cordinate define the center of the circle. You can also define color and styling in paint & pass the paint object.

public class CustomView extends View {

    public CustomView(Context context,  AttributeSet attrs) {
        super(context, attrs);

Define default paint settings and canvas (Initialise paint in constructor so that you can reuse the same object everywhere and change only specific settings wherever required)

private Paint drawPaint;

// Setup paint with color and stroke styles
private void setupPaint() {
    drawPaint = new Paint();

And initialise canvas object

private Canvas canvas;

protected void onDraw(Canvas canvas) {
    this.canvas = canvas;
    canvas.drawCircle(xCordinate, yCordinate, RADIUS, drawPaint);

And finally, for every view refresh or new draw on the screen, you need to call invalidate method. Remember your entire view is redrawn, hence this is an expensive call. Make sure you do only the necessary operations in onDraw


For more details on canvas drawing refer

How can one check to see if a remote file exists using PHP?

You could use the following:

$file = '';
$file_exists = (@fopen($file, "r")) ? true : false;

Worked for me when trying to check if an image exists on the URL

Extracting specific selected columns to new DataFrame as a copy

columns by index:

# selected column index: 1, 6, 7
new = old.iloc[: , [1, 6, 7]].copy() 

Best way to stress test a website

For web service testing, soap rest or WCF (including WebHttpBinding), try out SOA Cleaner. Can be downloded from: There is a free version, and it doesn't require any installation. It can also perform load tests.

How to Use -confirm in PowerShell

-Confirm is a switch in most PowerShell cmdlets that forces the cmdlet to ask for user confirmation. What you're actually looking for is the Read-Host cmdlet:

$confirmation = Read-Host "Are you Sure You Want To Proceed:"
if ($confirmation -eq 'y') {
    # proceed

or the PromptForChoice() method of the host user interface:

$title    = 'something'
$question = 'Are you sure you want to proceed?'

$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))

$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
    Write-Host 'confirmed'
} else {
    Write-Host 'cancelled'


As M-pixel pointed out in the comments the code could be simplified further, because the choices can be passed as a simple string array.

$title    = 'something'
$question = 'Are you sure you want to proceed?'
$choices  = '&Yes', '&No'

$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
    Write-Host 'confirmed'
} else {
    Write-Host 'cancelled'

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

There are some modules and packages only necessary for development, which are not needed in production. Like it says it in the documentation:

If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use. In this case, it's best to list these additional items in a devDependencies hash.

How do I create an Android Spinner as a popup?

You can create your own custom Dialog. It's fairly easy. If you want to dismiss it with a selection in the spinner, then add an OnItemClickListener and add

int n = mSpinner.getSelectedItemPosition();

as in the OnClickListener for the OK button. There's one caveat, though, and it's that the onclick listener does not fire if you reselect the default option. You need the OK button also.

Start with the layout:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:hint="Please select an option" 

Then, create the class:


public class SpinnerDialog extends Dialog {
    private ArrayList<String> mList;
    private Context mContext;
    private Spinner mSpinner;

   public interface DialogListener {
        public void ready(int n);
        public void cancelled();

    private DialogListener mReadyListener;

    public SpinnerDialog(Context context, ArrayList<String> list, DialogListener readyListener) {
        mReadyListener = readyListener;
        mContext = context;
        mList = new ArrayList<String>();
        mList = list;

    public void onCreate(Bundle savedInstanceState) {

        mSpinner = (Spinner) findViewById (;
        ArrayAdapter<String> adapter = new ArrayAdapter<String> (mContext, android.R.layout.simple_spinner_dropdown_item, mList);

        Button buttonOK = (Button) findViewById(;
        Button buttonCancel = (Button) findViewById(;
        buttonOK.setOnClickListener(new android.view.View.OnClickListener(){
            public void onClick(View v) {
                int n = mSpinner.getSelectedItemPosition();
        buttonCancel.setOnClickListener(new android.view.View.OnClickListener(){
            public void onClick(View v) {

Finally, use it as:

mSpinnerDialog = new SpinnerDialog(this, mTimers, new SpinnerDialog.DialogListener() {
  public void cancelled() {
    // do your code here
  public void ready(int n) {
    // do your code here

Plotting a 2D heatmap with Matplotlib

Seaborn takes care of a lot of the manual work and automatically plots a gradient at the side of the chart etc.

import numpy as np
import seaborn as sns
import matplotlib.pylab as plt

uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, linewidth=0.5)

enter image description here

Or, you can even plot upper / lower left / right triangles of square matrices, for example a correlation matrix which is square and is symmetric, so plotting all values would be redundant anyway.

corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True,  cmap="YlGnBu")

enter image description here

Selecting multiple classes with jQuery

I use $('.myClass.myOtherClass').removeClass('theclass');

How to use jQuery in AngularJS

This should be working. Please have a look at this fiddle.

$(function() {
   $( "#slider" ).slider();
});//Links to jsfiddle must be accompanied by code

Make sure you're loading the libraries in this order: jQuery, jQuery UI CSS, jQuery UI, AngularJS.

Get total of Pandas column

Similar to getting the length of a dataframe, len(df), the following worked for pandas and blaze:

Total = sum(df['MyColumn'])

or alternatively

Total = sum(df.MyColumn)
print Total

How to close a JavaFX application on window close?

For me only following is working:

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    public void handle(WindowEvent event) {


        Thread start = new Thread(new Runnable() {
            public void run() {
                //TODO Auto-generated method stub


How to reload a div without reloading the entire page?

jQuery.load() is probably the easiest way to load data asynchronously using a selector, but you can also use any of the jquery ajax methods (get, post, getJSON, ajax, etc.)

Note that load allows you to use a selector to specify what piece of the loaded script you want to load, as in

$("#mydiv").load(location.href + " #mydiv");

Note that this technically does load the whole page and jquery removes everything but what you have selected, but that's all done internally.

Is there a way to specify which pytest tests to run from a file?

According to the doc about Run tests by node ids

since you have all node ids in foo.txt, just run

pytest `cat foo.txt | tr '\n' ' '`

this is same with below command (with file content in the question)

pytest tests_directory/ tests_directory/

How to determine if a type implements an interface with C# reflection

If you have a type or an instance you can easily check if they support a specific interface.

To test if an object implements a certain interface:

if(myObject is IMyInterface) {
  // object myObject implements IMyInterface

To test if a type implements a certain interface:

if(typeof(IMyInterface).IsAssignableFrom(typeof(MyType))) {
  // type MyType implements IMyInterface

If you got a generic object and want to do a cast as well as a check if the interface you cast to is implemented the code is:

 var myCastedObject = myObject as IMyInterface;

    if(myCastedObject != null) {
      // object myObject implements IMyInterface

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

changing name of /bootstrap/cache/config.php to config.php.old doesn't work for me neither clearing cache with the commands artisan

  1. php artisan config:clear
  2. php artisan cache:clear
  3. php artisan config:cache

And for some weird reason I can't change permission for the owner on the directories, so my solution was running my IDE (Visual Studio Code) as admin, and everything works.

My project is in an F:/ path of another disk.

c++ custom compare function for std::sort()

std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

std::vector<pair<K,V>> items; 
std::sort(items.begin(), items.end()); 

If you really need to provide your own comparison function, then you need something along the lines of

template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
  return lhs.first < rhs.first;

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

Insert line break inside placeholder attribute of a textarea?

I liked the work of Jason Gennaro and Denis Golomazov, but I wanted something that would be more globally useful. I have modified the concept so that it can be added to any page without repercussion.

<h1>Demo: 5 different textarea placeholder behaviors from a single JS</h1>

<h2>Modified behaviors</h2>

<!-- To get simulated placeholder with New Lines behavior,
     add the placeholdernl attribute -->

<textarea placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address' placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<h2>Standard behaviors</h2>

<textarea placeholder='Address'>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address'></textarea>

The javascript is very simple

var handleFocus = function(){
    var $this = $(this);
    if($this.val() === $this.attr('placeholdernl')){
        $this.attr('value', '');
        $this.css('color', '');

var handleBlur = function(){
    var $this = $(this);
    if($this.val() == ''){
        $this.attr('value', $this.attr('placeholdernl'))
        $this.css('color', 'gray');

    var $this = $(this),
        value = $this.attr('value'),
        placeholder = $this.attr('placeholder');
    $this.attr('placeholdernl', value ? value : placeholder);
    $this.attr('value', '');

Ruby combining an array into one string

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(" ")

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

Oracle SQL Developer spool output?

I have found that if I save my query(spool_script_file.sql) and call it using this

@c:\client\queries\spool_script_file.sql as script(F5)

My output now is just the results with out the commands at the top.

I found this solution on the oracle forums.

Easiest way to compare arrays in C#

For .NET 4.0 and higher you can compare elements in array or tuples via using StructuralComparisons type:

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };

Console.WriteLine (a1 == a2);        // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2));  // False (because arrays is reference types)

IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer)); 

pandas three-way joining multiple dataframes on columns

You could try this if you have 3 dataframes

# Merge multiple dataframes
df1 = pd.DataFrame(np.array([
    ['a', 5, 9],
    ['b', 4, 61],
    ['c', 24, 9]]),
    columns=['name', 'attr11', 'attr12'])
df2 = pd.DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22'])
df3 = pd.DataFrame(np.array([
    ['a', 15, 49],
    ['b', 4, 36],
    ['c', 14, 9]]),
    columns=['name', 'attr31', 'attr32'])


alternatively, as mentioned by cwharland


No connection could be made because the target machine actively refused it (PHP / WAMP)

following steps worked for me.

  1. Go to wamp\apps\phpmyadmin
  2. search
  3. search and replace with "localhost".

MVC4 input field placeholder

I did so

Field in model:

[Display(Name = "User name")]
public string UserName { get; set; }


  @Html.TextBoxFor(m => m.UserName, new { placeholder = Html.DisplayNameFor(n => n.UserName)})

How to get URI from an asset File?

Worked for me Try this code

   uri = Uri.fromFile(new File("//assets/testdemo.txt"));
   String testfilepath = uri.getPath();
    File f = new File(testfilepath);
    if (f.exists() == true) {
    Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
    } else {
   Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

Simple explanation about what a Index out of bound exception is:

Just think one train is there its compartments are D1,D2,D3. One passenger came to enter the train and he have the ticket for D4. now what will happen. the passenger want to enter a compartment that does not exist so obviously problem will arise.

Same scenario: whenever we try to access an array list, etc. we can only access the existing indexes in the array. array[0] and array[1] are existing. If we try to access array[3], it's not there actually, so an index out of bound exception will arise.

Android Button setOnClickListener Design

I think you can usually do what you need in a loop, which is much better than many onClick methods if it can be done.

Check out this answer for a demonstration of how to use a loop for a similar problem. How you construct your loop will depend on the needs of your onClick functions and how similar they are to one another. The end result is much less repetitive code that is easier to maintain.

How do you get the current project directory from C# code when creating a custom MSBuild task?


var pathRegex = new Regex(@"\\bin(\\x86|\\x64)?\\(Debug|Release)$", RegexOptions.Compiled);
var directory = pathRegex.Replace(Directory.GetCurrentDirectory(), String.Empty);

This is solution different from the others does also take into account possible x86 or x64 build.

How to repeat last command in python interpreter shell?

On Ubuntu 16.04, I had the same problem after upgrading Python from the preloaded 3.5 to version 3.7 from source code. As @erewok suggested, I did

sudo apt-get install libncurses-dev libreadline-dev

followed by: sudo make install After that, the arrow-up key worked. Not sure which module is required to fix the problem or both, but without "make install", none would work. During initial make, there were some red-flag errors, but ignored and completed the build. This time, there didn't seem to have any errors.

Pandas: Convert Timestamp to

As of pandas 0.20.3, use .to_pydatetime() to convert any pandas.DateTimeIndex instances to Python datetime.datetime.

self referential struct definition?

Lets go through basic definition of typedef. typedef use to define an alias to an existing data type either it is user defined or inbuilt.

typedef <data_type> <alias>;

for example

typedef int scores;

scores team1 = 99;

Confusion here is with the self referential structure, due to a member of same data type which is not define earlier. So In standard way you can write your code as :-

//View 1
typedef struct{ bool isParent; struct Cell* child;} Cell;

//View 2
typedef struct{
  bool isParent;
  struct Cell* child;
} Cell;

//Other Available ways, define stucture and create typedef
struct Cell {
  bool isParent;
  struct Cell* child;

typedef struct Cell Cell;

But last option increase some extra lines and words with usually we don't want to do (we are so lazy you know ;) ) . So prefer View 2.

How to use a dot "." to access members of dictionary?

Derive from dict and and implement __getattr__ and __setattr__.

Or you can use Bunch which is very similar.

I don't think it's possible to monkeypatch built-in dict class.

What is the difference between a "line feed" and a "carriage return"?

Both of these are primary from the old printing days.

Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r.

Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.

For more sundry details, the mighty wikipedia to the rescue.

ASP.NET - How to write some html in the page? With Response.Write?

Use a literal control and write your html like this:

literal1.text = "<h2><p>Notify:</p> alert</h2>";

ActiveMQ connection refused

Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.

You can try using: netstat -a to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp

On mac you will start your activemq using:

$ACTMQ_HOME/bin/activemq start 

Or if your config file (activemq.xml ) if located in another location you can use:

$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}

In your case the executable is under: bin/macosx/activemq so you need to use: $ACTMQ_HOME/bin/macosx/activemq start

Saving an Excel sheet in a current directory with VBA

VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.

MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"

This assumes that the sheet you want to save has never been saved and you want to define the file name in code.

Plot two histograms on single chart with matplotlib

The accepted answers gives the code for a histogram with overlapping bars, but in case you want each bar to be side-by-side (as I did), try the variation below:

import numpy as np
import matplotlib.pyplot as plt'seaborn-deep')

x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
bins = np.linspace(-10, 10, 30)

plt.hist([x, y], bins, label=['x', 'y'])
plt.legend(loc='upper right')

enter image description here


EDIT [2018/03/16]: Updated to allow plotting of arrays of different sizes, as suggested by @stochastic_zeitgeist

Summing elements in a list

def sumoflist(l):    
    total = 0    
    for i in l:
        total +=i
    return total

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

PHP json_encode json_decode UTF-8

if you get "unexpected Character" error you should check if there is a BOM (Byte Order Marker saved into your utf-8 json. You can either remove the first character or save if without BOM.

Printing object properties in Powershell

My solution to this problem was to use the $() sub-expression block.

Add-Type -Language CSharp @"
public class Thing{
    public string Name;

$x = New-Object Thing

$x.Name = "Bill"

Write-Output "My name is $($x.Name)"
Write-Output "This won't work right: $x.Name"


My name is Bill
This won't work right: Thing.Name

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

Here's how you can mock your FileConnection

Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
              .Throws(new IOException());

Then instantiate your Transfer class and use the mock in your method call

Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);


First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.

Since you are setting those properties using another dependency, I would write it like this:

public class Transfer
    public Transfer(IInternalConfig internalConfig)
        source = internalConfig.GetFileConnection("source");
        destination = internalConfig.GetFileConnection("destination");

    //you should consider making these private or protected fields
    public virtual IFileConnection source { get; set; }
    public virtual IFileConnection destination { get; set; }

    public virtual void GetFile(IFileConnection connection, 
        string remoteFilename, string localFilename)
        connection.Get(remoteFilename, localFilename);

    public virtual void PutFile(IFileConnection connection, 
        string localFilename, string remoteFilename)
        connection.Get(remoteFilename, localFilename);

    public virtual void TransferFiles(string sourceName, string destName)
        var tempName = Path.GetTempFileName();
        GetFile(source, sourceName, tempName);
        PutFile(destination, tempName, destName);

This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.

form_for but to post to a different action

I have done it like that

<%= form_for :user, url: {action: "update", params: {id:}} do |f| %>

Note the optional parameter id set to user instance id attribute.

How to set menu to Toolbar in Android

just override onCreateOptionsMenu like this in your

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(, menu);
    return true;

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

Regarding to netbeans, you could set max heap size to solve the problem.

Go to 'Run', then --> 'Set Project Configuration' --> 'Customise' --> 'run' of its popped up window --> 'VM Option' --> fill in '-Xms2048m -Xmx2048m'.

Why is NULL undeclared?

NULL isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef> or #include <stddef.h> should be sufficient.

The definition of NULL is guaranteed to be available if you include cstddef or stddef.h. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.

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

@John-Skeet gave me the clue to fix my own issue around this. As a younger programmer this small issue is easy to miss and hard to diagnose. So Im sharing it in the hopes it will help someone.

My issue was that I wanted to parse the following string contraining a time stamp from a JSON I have no influence over and put it in more useful variables. But I kept getting errors.

So given the following (pay attention to the string parameter inside ofPattern();

String str = "20190927T182730.000Z"

LocalDateTime fin;
fin = LocalDateTime.parse( str, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss.SSSZ") );


Exception in thread "main" java.time.format.DateTimeParseException: Text 
'20190927T182730.000Z' could not be parsed at index 19

The problem? The Z at the end of the Pattern needs to be wrapped in 'Z' just like the 'T' is. Change "yyyyMMdd'T'HHmmss.SSSZ" to "yyyyMMdd'T'HHmmss.SSS'Z'" and it works.

Removing the Z from the pattern alltogether also led to errors.

Frankly, I'd expect a Java class to have anticipated this.

Pretty printing XML with javascript

Or just print out the special HTML characters?

Ex: <xmlstuff>&#10; &#09;<node />&#10;</xmlstuff>   

&#09;   Horizontal tab  
&#10;   Line feed

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

I get the same error when I try to set the index_col reading a file into a Panda's data-frame:

df = pd.read_csv('my_file.tsv', sep='\t', header=0, index_col=['0'])  ## or same with the following
df = pd.read_csv('my_file.tsv', sep='\t', header=0, index_col=[0])

I have never encountered such an error previously. I still am trying to figure out the reason behind this (using @Eric Leschinski explanation and others).

Anyhow, the following approach solves the problem for now until I figure the reason out:

df = pd.read_csv('my_file.tsv', sep='\t', header=0)  ## not setting the index_col
df.set_index(['0'], inplace=True)

I will update this as soon as I figure out the reason for such behavior.

What is href="#" and why is it used?

Unordered lists are often created with the intent of using them as a menu, but an li list item is text. Because the list li item is text, the mouse pointer will not be an arrow, but an "I cursor". Users are accustomed to seeing a pointing finger for a mouse pointer when something is clickable. Using an anchor tag a inside of the li tag causes the mouse pointer to change to a pointing finger. The pointing finger is a lot better for using the list as a menu.

<ul id="menu">
   <li><a href="#">Menu Item 1</a></li>
   <li><a href="#">Menu Item 2</a></li>
   <li><a href="#">Menu Item 3</a></li>
   <li><a href="#">Menu Item 4</a></li>

If the list is being used for a menu, and doesn't need a link, then a URL doesn't need to be designated. But the problem is that if you leave out the href attribute, text in the <a> tag is seen as text, and therefore the mouse pointer is back to an I-cursor. The I-cursor might make the user think that the menu item is not clickable. Therefore, you still need an href, but you don't need a link to anywhere.

You could use lots of div or p tags for a menu list, but the mouse pointer would be an I-cursor for them also.

You could use lots of buttons stacked on top of each other for a menu list, but the list seems to be preferable. And that's probably why the href="#" that points to nowhere is used in anchor tags inside of list tags.

You can set the pointer style in CSS, so that is another option. The href="#" to nowhere might just be the lazy way to set some styling.

Configure Log4net to write to multiple files

Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:

    <level value="ALL" />
    <appender-ref ref="File1Appender" />
<logger name="SomeName">
    <level value="ALL" />
    <appender-ref ref="File1Appender2" />

This is how I have done it in the past. Then something like this for the other log:

private static readonly ILog otherLog = LogManager.GetLogger("SomeName");

And you can get your normal logger as follows:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Read the loggers and appenders section of the documentation to understand how this works.

How to get the size of a varchar[n] field in one SQL statement?

This will work on SQL SERVER...

SELECT COL_LENGTH('Table', 'Column')

How to skip to next iteration in jQuery.each() util?

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Razor-based view doesn't see referenced assemblies

in spacename models, yourClassModel, add public before name class

public class yourClassModel{

Performance of FOR vs FOREACH in PHP

My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy... The time difference is going to be minimal in most cases.

The big thing to watch for is:

for ($i = 0; $i < count($array); $i++) {

That's an expensive loop, since it calls count on every single iteration. So long as you're not doing that, I don't think it really matters...

As for the reference making a difference, PHP uses copy-on-write, so if you don't write to the array, there will be relatively little overhead while looping. However, if you start modifying the array within the array, that's where you'll start seeing differences between them (since one will need to copy the entire array, and the reference can just modify inline)...

As for the iterators, foreach is equivalent to:

while ($it->valid()) {
    $key = $it->key();     // If using the $key => $value syntax
    $value = $it->current();

    // Contents of loop in here


As far as there being faster ways to iterate, it really depends on the problem. But I really need to ask, why? I understand wanting to make things more efficient, but I think you're wasting your time for a micro-optimization. Remember, Premature Optimization Is The Root Of All Evil...

Edit: Based upon the comment, I decided to do a quick benchmark run...

$a = array();
for ($i = 0; $i < 10000; $i++) {
    $a[] = $i;

$start = microtime(true);
foreach ($a as $k => $v) {
    $a[$k] = $v + 1;
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {
    $v = $v + 1;
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}    
echo "Completed in ", microtime(true) - $start, " Seconds\n";

And the results:

Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you're modifying the array in the loop, it's several times faster to use references...

And the overhead for just the reference is actually less than copying the array (this is on 5.3.2)... So it appears (on 5.3.2 at least) as if references are significantly faster...

Get the first key name of a JavaScript object

you can put your elements into an array and hash at the same time.

var value = [1,2,3];
ahash = {"one": value};

array can be used to get values by their order and hash could be used to get values by their key. just be be carryfull when you remove and add elements.

How do you rotate a two dimensional array?

@dagorym: Aw, man. I had been hanging onto this as a good "I'm bored, what can I ponder" puzzle. I came up with my in-place transposition code, but got here to find yours pretty much identical to mine...ah, well. Here it is in Ruby.

require 'pp'
n = 10
a = []
n.times { a << (1..n).to_a }

pp a

0.upto(n/2-1) do |i|
  i.upto(n-i-2) do |j|
    tmp             = a[i][j]
    a[i][j]         = a[n-j-1][i]
    a[n-j-1][i]     = a[n-i-1][n-j-1]
    a[n-i-1][n-j-1] = a[j][n-i-1]
    a[j][n-i-1]     = tmp

pp a

git pull keeping local changes

To answer the question : if you want to exclude certain files of a checkout, you can use sparse-checkout

  1. In .git/info/sparse-checkout, define what you want to keep. Here, we want all (*) but (note the exclamation mark) config.php :

    /* !/config.php

  2. Tell git you want to take sparse-checkout into account

    git config core.sparseCheckout true

  3. If you already have got this file locally, do what git does on a sparse checkout (tell it it must exclude this file by setting the "skip-worktree" flag on it)

    git update-index --skip-worktree config.php

  4. Enjoy a repository where your config.php file is yours - whatever changes are on the repository.

Please note that configuration values SHOULDN'T be in source control :

  • It is a potential security breach
  • It causes problems like this one for deployment

This means you MUST exclude them (put them in .gitignore before first commit), and create the appropriate file on each instance where you checkout your app (by copying and adapting a "template" file)

Note that, once a file is taken in charge by git, .gitignore won't have any effect.

Given that, once the file is under source control, you only have two choices () :

  • rebase all your history to remove the file (with git filter-branch)

  • create a commit that removes the file. It is like fighting a loosing battle, but, well, sometimes you have to live with that.

fs.writeFile in a promise, asynchronous-synchronous stuff

What worked for me was fs.promises.

Example One:

const fs = require("fs")

  .writeFile(__dirname + '/test.json', "data", { encoding: 'utf8' })
  .then(() => {
    // Do whatever you want to do.

Example Two. Using Async-Await:

const fs = require("fs")

async function writeToFile() {
  await fs.promises.writeFile(__dirname + '/test-22.json', "data", {
    encoding: 'utf8'



How to cancel a local git commit

Use --soft instead of --hard flag:

git reset --soft HEAD^

How do I compile and run a program in Java on my Mac?

You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)

From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.

MySQL delete multiple rows in one query conditions unique to each row

Took a lot of googling but here is what I do in Python for MySql when I want to delete multiple items from a single table using a list of values.

#create some empty list
values = []
#continue to append the values you want to delete to it
#BUT you must ensure instead of a string it's a single value tuple
values.append(([Your Variable],))
#Then once your array is loaded perform an execute many
cursor.executemany("DELETE FROM YourTable WHERE ID = %s", values)

bundle install returns "Could not locate Gemfile"

You must be in the same directory of Gemfile

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

I was getting the same pathspec error on git-bash. I used Tortoise git on windows to switch/checkout the branch.

How can I parse a YAML file in Python

To access any element of a list in a YAML file like this:

    url: dtr-:5000/
  dbConnectionString: jdbc:oracle:thin:@x.x.x.x:1521:abcd

You can use following python script:

import yaml

with open("/some/path/to/yaml.file", 'r') as f:
    valuesYaml = yaml.load(f, Loader=yaml.FullLoader)


ImportError: No module named 'google'

  1. Close Anaconda/Spyder
  2. Open command prompt and run the below command
  3. conda update --all
  4. Start the app again and this time it should work.

Note - You need not have to uninstall/reinstall anything.

Pass a password to ssh in pure bash

Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:

"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage

which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh "thought" that it is run in the regular terminal and since it may be accomplished by simple posix functions, it is beyond what simple bash offers.

Modular multiplicative inverse function in Python

As of 3.8 pythons pow() function can take a modulus and a negative integer. See here. Their case for how to use it is

>>> pow(38, -1, 97)
>>> 23 * 38 % 97 == 1

How to resize images proportionally / keeping the aspect ratio?

actually i have just run into this problem and the solution I found was strangely simple and weird

$("#someimage").css({height:<some new height>})

and miraculously the image is resized to the new height and conserving the same ratio!

How to use UTF-8 in resource properties with ResourceBundle

We create a resources.utf8 file that contains the resources in UTF-8 and have a rule to run the following:

native2ascii -encoding utf8 resources.utf8

Python Checking a string's first and last character

You are testing against the string minus the last character:

>>> '"xxx"'[:-1]

Note how the last character, the ", is not part of the output of the slice.

I think you wanted just to test against the last character; use [-1:] to slice for just the last element.

However, there is no need to slice here; just use str.startswith() and str.endswith() directly.

Submit form after calling e.preventDefault()

In my case there was a race, as I needed the ajax response to fill a hidden field and send the form after it's filled. I fixed it with putting e.preventDefault() into a condition.

var all_is_done=false;
function do_the_stuf(){
  //do stuff

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Post an object as data using Jquery Ajax

[object Object] This means somewhere the object is being converted to a string.

Converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};
JSON.stringify(product + ''); 

Not converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};

Beamer: How to show images as step-by-step images


The % is important. This will keep all the images fixed.

Unable to resolve host "<URL here>" No address associated with host name

It is WiFi bug due to wifi disable or not properly connected.

Simply Reconnect the wifi will solve the issue.

How do you add an SDK to Android Studio?

I had opened a ticket also with Google's support, and received the solution. Instead of choosing the sdk/platform/android-16 folder, if you select the top-level "sdk" folder instead, you'll then be asked to choose which SDK you want to add. This worked!

enter image description here

enter image description here

How to kill all active and inactive oracle sessions for user

The KILL SESSION command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.

Check the status to confirm:

SELECT sid, serial#, status, username FROM v$session;

You could also use IMMEDIATE clause:


The IMMEDIATE clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.

Update If you want to kill all the sessions, you could just prepare a small script.

SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;

Spool the above to a .sql file and execute it, or, copy paste the output and run it.

Swift - encode URL

Swift 5 You can try .afURLQueryAllowed option if you want to encode string like below

let testString = "6hAD9/RjY+SnGm&B" let escodedString = testString.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) print(escodedString!)

//encoded string will be like en6hAD9%2FRjY%2BSnGm%26B

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

How to get the request parameters in Symfony 2?

Try this, it works

$this->request = $this->container->get('request_stack')->getCurrentRequest();


How to download Google Play Services in an Android emulator?

I know this is an old question, but I got here because I had a similar problem as everyone above. I solved it by just reading a little closer!

I hadn't noticed there were 2 possible system Images I could choose from, one that contained Google APIs and one that didn't (on my laptop the menu was too small for me to read the (with Google APIs) text appended.

It's a stupid thing to miss, but someone else might have a small screen like I did, and miss this :D

What is the difference between Class.getResource() and ClassLoader.getResource()?

To answer the question whether there is any caching going on.

I investigated this point further by running a stand-alone Java application that continuously loaded a file from disk using the getResourceAsStream ClassLoader method. I was able to edit the file, and the changes were reflected immediately, i.e., the file was reloaded from disk without caching.

However: I'm working on a project with several maven modules and web projects that have dependencies on each other. I'm using IntelliJ as my IDE to compile and run the web projects.

I noticed that the above seemed to no longer hold true, the reason being that the file that I was being loaded is now baked into a jar and deployed to the depending web project. I only noticed this after trying to change the file in my target folder, to no avail. This made it seem as though there was caching going on.

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).


And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length

How can I change the thickness of my <hr> tag

height attribute has been deprecated in html 5. What I would do is create a border around the hr and increase the thickness of the border as such: hr style="border:solid 2px black;"


In standard SQL this type of update looks like:

update a
   set a.firstfield ='BIT OF TEXT' + b.something
  from file1 a
  join file2 b
    on substr(a.firstfield,10,20) = 
 where a.firstfield like 'BLAH%' 

With minor syntactic variations this type of thing will work on Oracle or SQL Server and (although I don't have a DB/2 instance to hand to test) will almost certainly work on DB/2.

How do I test if a string is empty in Objective-C?

You should better use this category:

@implementation NSString (Empty)

    - (BOOL) isWhitespace{
        return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);


Copying files using rsync from remote server to local machine

If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.

scp user@host:/path/file /localpath/file

Wild card characters are supported, so

scp user@host:/path/folder/* /localpath/folder

will copy all of the remote files in that folder.If copying more then one directory.

note -r will copy all sub-folders and content too.

jQuery Set Cursor Position in Text Area

In IE to move cursor on some position this code is enough:

var range = elt.createTextRange();
range.move('character', pos);;

python requests file upload

If upload_file is meant to be the file, use:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r =, files=files, data=values)

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

The filename will be included in the mime header for the specific field:

>>> import requests
>>> open('file.txt', 'wb')  # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', '', files=files).prepare().body.decode('ascii'))
Content-Disposition: form-data; name="upload_file"; filename="file.txt"


Note the filename="file.txt" parameter.

You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:

files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}

This sets an alternative filename and content type, leaving out the optional headers.

If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.

VBA: Conditional - Is Nothing

Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.

Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.

Sub test()

Dim dict As Object
Set dict = CreateObject("scripting.dictionary")

If Not dict Is Nothing Then
    MsgBox "Dict is something!"  '<--- This shows
    MsgBox "Dict is nothing!"
End If

End Sub

However if you declare an object but never create it, it's nothing.

Sub test()

Dim temp As Object

If Not temp Is Nothing Then
    MsgBox "Temp is something!"
    MsgBox "Temp is nothing!" '<---- This shows
End If

End Sub

How to convert integers to characters in C?

Casting the integer to a char will do what you want.

char theChar=' ';
int theInt = 97;
theChar=(char) theInt;


There is no difference between 'a' and 97 besides the way you interperet them.

Git merge without auto commit

I prefer this way so I don't need to remember any rare parameters.

git merge branch_name

It will then say your branch is ahead by "#" commits, you can now pop these commits off and put them into the working changes with the following:

git reset @~#

For example if after the merge it is 1 commit ahead, use:

git reset @~1

Note: On Windows, quotes are needed. (As Josh noted in comments) eg:

git reset "@~1"

What is managed or unmanaged code in programming?

In as few words as possible:

  • managed code = .NET programs
  • unmanaged code = "normal" programs

Hidden features of Windows batch files

The FOR command! While I hate writing batch files, I'm thankful for it.

FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k

would parse each line in myfile.txt, ignoring lines that begin with a semicolon, passing the 2nd and 3rd token from each line to the for body, with tokens delimited by commas and/or spaces. Notice the for body statements reference %i to get the 2nd token, %j to get the 3rd token, and %k to get all remaining tokens after the 3rd.

You can also use this to iterate over directories, directory contents, etc...

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

Inner join of DataTables in C#

I tried to do this in next way

public static DataTable JoinTwoTables(DataTable innerTable, DataTable outerTable)
            DataTable resultTable = new DataTable();
            var innerTableColumns = new List<string>();
            foreach (DataColumn column in innerTable.Columns)

            var outerTableColumns = new List<string>();
            foreach (DataColumn column in outerTable.Columns)
                if (!innerTableColumns.Contains(column.ColumnName))

            for (int i = 0; i < innerTable.Rows.Count; i++)
                var row = resultTable.NewRow();
                innerTableColumns.ForEach(x =>
                    row[x] = innerTable.Rows[i][x];
                outerTableColumns.ForEach(x => 
                    row[x] = outerTable.Rows[i][x];
            return resultTable;

How do you detect the clearing of a "search" HTML5 input?

It made sense to me that clicking the X should count as a change event. I already had the onChange event all setup to do what I needed it to do. So for me, the fix was to simply do this jQuery line:

$('#search').click(function(){ $(this).change(); });

Rebasing a Git merge commit

  • From your merge commit
  • Cherry-pick the new change which should be easy
  • copy your stuff
  • redo the merge and resolve the conflicts by just copying the files from your local copy ;)

Why is the <center> tag deprecated in HTML?

For text and images you can use text-align:

<div style="text-align: center;">
    I'm centered.

Jinja2 shorthand conditional

Alternative way (but it's not python style. It's JS style)

{{ files and 'Update' or 'Continue' }}

Best Python IDE on Linux

Probably the new PyCharm from the makers of IntelliJ and ReSharper.

Easy way to print Perl array? (with a little formatting)

Also, you may want to try Data::Dumper. Example:

use Data::Dumper;

# simple procedural interface
print Dumper($foo, $bar);

Using PHP Replace SPACES in URLS with %20

I think you must use rawurlencode() instead urlencode() for your purpose.


$image = 'some images.jpg';
$url   = ''

With urlencode($str) will result

echo $url.urlencode($image); //

its not change to %20 at all

but with rawurlencode($image) will produce

echo $url.rawurlencode(basename($image)); //

Android: How to turn screen on and off programmatically?

     WakeLock screenLock =    ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(


//User Manifest file

How can I convert the "arguments" object to an array in JavaScript?

 function x(){
   var rest = [...arguments]; console.log(rest);return     

I tried simple destructing technique

How do I change a tab background color when using TabLayout?

After some messing around this is how I got the desired look (at least in the emulator) and it keeps the ripple effect.

tab layout with tab selector with color argument

    app:tabTextColor="@drawable/tab_selector" />

And the @drawable/tab_selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
    <item android:color="@color/colorPrimary" android:drawable="@color/colorPrimaryDark" android:state_selected="true" />
    <item android:color="@color/colorPrimaryDark" android:drawable="@color/colorPrimary" />

FYI: This is what the emulator showed before I added the color argument to @drawable/tab_selector:

tab layout with tab selector without color argument

Inserting a Python datetime.datetime object into MySQL

You are most likely getting the TypeError because you need quotes around the datecolumn value.


now = datetime.datetime(2009, 5, 5)

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
               ("name", 4, now))

With regards to the format, I had success with the above command (which includes the milliseconds) and with:

now.strftime('%Y-%m-%d %H:%M:%S')

Hope this helps.

Convert pandas Series to DataFrame

Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:

pd.DataFrame({'email':sf.index, 'list':sf.values})

There are lots of ways to construct a df, see the docs

How to get size of mysql database?

If you want the list of all database sizes sorted, you can use :

FROM   (SELECT table_schema AS `DB Name`, 
           ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) AS `DB Size in MB`
        FROM   information_schema.tables 
        GROUP  BY `DB Name`) AS tmp_table 
ORDER  BY `DB Size in MB` DESC; 

Clear input fields on form submit

By this way, you hold a form by his ID and throw all his content. This technic is fastiest.


Uninstall old versions of Ruby gems

Try something like gem uninstall rjb --version 1.3.4.

HashSet vs. List performance

Just thought I'd chime in with some benchmarks for different scenarios to illustrate the previous answers:

  1. A few (12 - 20) small strings (length between 5 and 10 characters)
  2. Many (~10K) small strings
  3. A few long strings (length between 200 and 1000 characters)
  4. Many (~5K) long strings
  5. A few integers
  6. Many (~10K) integers

And for each scenario, looking up values which appear:

  1. In the beginning of the list ("start", index 0)
  2. Near the beginning of the list ("early", index 1)
  3. In the middle of the list ("middle", index count/2)
  4. Near the end of the list ("late", index count-2)
  5. At the end of the list ("end", index count-1)

Before each scenario I generated randomly sized lists of random strings, and then fed each list to a hashset. Each scenario ran 10,000 times, essentially:

(test pseudocode)

for X times
    exists = list.Contains(lookup);

for X times
    exists = hashset.Contains(lookup);

Sample Output

Tested on Windows 7, 12GB Ram, 64 bit, Xeon 2.8GHz

---------- Testing few small strings ------------
Sample items: (16 total)
vgnwaloqf diwfpxbv tdcdc grfch icsjwk

1: hashset: late -- 100.00 % -- [Elapsed: 0.0018398 sec]
2: hashset: middle -- 104.19 % -- [Elapsed: 0.0019169 sec]
3: hashset: end -- 108.21 % -- [Elapsed: 0.0019908 sec]
4: list: early -- 144.62 % -- [Elapsed: 0.0026607 sec]
5: hashset: start -- 174.32 % -- [Elapsed: 0.0032071 sec]
6: list: middle -- 187.72 % -- [Elapsed: 0.0034536 sec]
7: list: late -- 192.66 % -- [Elapsed: 0.0035446 sec]
8: list: end -- 215.42 % -- [Elapsed: 0.0039633 sec]
9: hashset: early -- 217.95 % -- [Elapsed: 0.0040098 sec]
10: list: start -- 576.55 % -- [Elapsed: 0.0106073 sec]

---------- Testing many small strings ------------
Sample items: (10346 total)
dmnowa yshtrxorj vthjk okrxegip vwpoltck

1: hashset: end -- 100.00 % -- [Elapsed: 0.0017443 sec]
2: hashset: late -- 102.91 % -- [Elapsed: 0.0017951 sec]
3: hashset: middle -- 106.23 % -- [Elapsed: 0.0018529 sec]
4: list: early -- 107.49 % -- [Elapsed: 0.0018749 sec]
5: list: start -- 126.23 % -- [Elapsed: 0.0022018 sec]
6: hashset: early -- 134.11 % -- [Elapsed: 0.0023393 sec]
7: hashset: start -- 372.09 % -- [Elapsed: 0.0064903 sec]
8: list: middle -- 48,593.79 % -- [Elapsed: 0.8476214 sec]
9: list: end -- 99,020.73 % -- [Elapsed: 1.7272186 sec]
10: list: late -- 99,089.36 % -- [Elapsed: 1.7284155 sec]

---------- Testing few long strings ------------
Sample items: (19 total)

1: list: early -- 100.00 % -- [Elapsed: 0.0018266 sec]
2: list: start -- 115.76 % -- [Elapsed: 0.0021144 sec]
3: list: middle -- 143.44 % -- [Elapsed: 0.0026201 sec]
4: list: late -- 190.05 % -- [Elapsed: 0.0034715 sec]
5: list: end -- 193.78 % -- [Elapsed: 0.0035395 sec]
6: hashset: early -- 215.00 % -- [Elapsed: 0.0039271 sec]
7: hashset: end -- 248.47 % -- [Elapsed: 0.0045386 sec]
8: hashset: start -- 298.04 % -- [Elapsed: 0.005444 sec]
9: hashset: middle -- 325.63 % -- [Elapsed: 0.005948 sec]
10: hashset: late -- 431.62 % -- [Elapsed: 0.0078839 sec]

---------- Testing many long strings ------------
Sample items: (5000 total)

1: list: early -- 100.00 % -- [Elapsed: 0.0016211 sec]
2: list: start -- 132.73 % -- [Elapsed: 0.0021517 sec]
3: hashset: start -- 231.26 % -- [Elapsed: 0.003749 sec]
4: hashset: end -- 368.74 % -- [Elapsed: 0.0059776 sec]
5: hashset: middle -- 385.50 % -- [Elapsed: 0.0062493 sec]
6: hashset: late -- 406.23 % -- [Elapsed: 0.0065854 sec]
7: hashset: early -- 421.34 % -- [Elapsed: 0.0068304 sec]
8: list: middle -- 18,619.12 % -- [Elapsed: 0.3018345 sec]
9: list: end -- 40,942.82 % -- [Elapsed: 0.663724 sec]
10: list: late -- 41,188.19 % -- [Elapsed: 0.6677017 sec]

---------- Testing few ints ------------
Sample items: (16 total)
7266092 60668895 159021363 216428460 28007724

1: hashset: early -- 100.00 % -- [Elapsed: 0.0016211 sec]
2: hashset: end -- 100.45 % -- [Elapsed: 0.0016284 sec]
3: list: early -- 101.83 % -- [Elapsed: 0.0016507 sec]
4: hashset: late -- 108.95 % -- [Elapsed: 0.0017662 sec]
5: hashset: middle -- 112.29 % -- [Elapsed: 0.0018204 sec]
6: hashset: start -- 120.33 % -- [Elapsed: 0.0019506 sec]
7: list: late -- 134.45 % -- [Elapsed: 0.0021795 sec]
8: list: start -- 136.43 % -- [Elapsed: 0.0022117 sec]
9: list: end -- 169.77 % -- [Elapsed: 0.0027522 sec]
10: list: middle -- 237.94 % -- [Elapsed: 0.0038573 sec]

---------- Testing many ints ------------
Sample items: (10357 total)
370826556 569127161 101235820 792075135 270823009

1: list: early -- 100.00 % -- [Elapsed: 0.0015132 sec]
2: hashset: end -- 101.79 % -- [Elapsed: 0.0015403 sec]
3: hashset: early -- 102.08 % -- [Elapsed: 0.0015446 sec]
4: hashset: middle -- 103.21 % -- [Elapsed: 0.0015618 sec]
5: hashset: late -- 104.26 % -- [Elapsed: 0.0015776 sec]
6: list: start -- 126.78 % -- [Elapsed: 0.0019184 sec]
7: hashset: start -- 130.91 % -- [Elapsed: 0.0019809 sec]
8: list: middle -- 16,497.89 % -- [Elapsed: 0.2496461 sec]
9: list: end -- 32,715.52 % -- [Elapsed: 0.4950512 sec]
10: list: late -- 33,698.87 % -- [Elapsed: 0.5099313 sec]

Access IP Camera in Python OpenCV

To access an Ip Camera, first, I recommend you to install it like you are going to use for the standard application, without any code, using normal software.

After this, you have to know that for different cameras, we have different codes. There is a website where you can see what code you can use to access them:

But be careful, for my camera (Intelbras S3020) it does not work. The right way is to ask the company of your camera, and if they are a good company they will provide it.

When you know your code just add it like:

cap = cv2.VideoCapture("http://LOGIN:PASSWORD@IP/cgi-bin/mjpg/video.cgi?&subtype=1")

Instead LOGIN you will put your login, and instead PASSWORD you will put your password.

To find out camera's IP address there is many softwares that you can download and provide the Ip address to you. I use the software from Intelbras, but I also recommend EseeCloud because they work for almost all cameras that I've bought:

In this example, it shows the protocol http to access the Ip camera, but you can also use rstp, it depends on the camera, as I said.

If you have any further questions just let me know.

How to program a fractal?

I would start with something simple, like a Koch Snowflake. It's a simple process of taking a line and transforming it, then repeating the process recursively until it looks neat-o.

Something super simple like taking 2 points (a line) and adding a 3rd point (making a corner), then repeating on each new section that's created.

fractal(p0, p1){
    Pmid = midpoint(p0,p1) + moved some distance perpendicular to p0 or p1;
    fractal(Pmid, p1);

Set Focus After Last Character in Text Box

This is the easy way to do it. If you're going backwards, just add $("#Prefix").val($("#Prefix").val()); after you set the focus

This is the more proper (cleaner) way:

function SetCaretAtEnd(elem) {
        var elemLen = elem.value.length;
        // For IE Only
        if (document.selection) {
            // Set focus
            // Use IE Ranges
            var oSel = document.selection.createRange();
            // Reset position to 0 & then set at end
            oSel.moveStart('character', -elemLen);
            oSel.moveStart('character', elemLen);
            oSel.moveEnd('character', 0);
        else if (elem.selectionStart || elem.selectionStart == '0') {
            // Firefox/Chrome
            elem.selectionStart = elemLen;
            elem.selectionEnd = elemLen;
        } // if
    } // SetCaretAtEnd()

Creating NSData from NSString in Swift

To create not optional data I recommend using it:

let key = "1234567"
let keyData = Data(key.utf8)

gradlew command not found?

For Ubuntu(linux) users: doing "bash ./gradlew build " works but "./gradlew build " doesnot work.

For me the issue was it was on NTFS file system, linux does not let execute a script from NTFS. Try moving the code from NTFS to a linux partition. then ./gradlew build should work

"Auth Failed" error with EGit and GitHub

For you who, like me, already did setup you ssh-keys but still get the errors:

Make sure you did setup a push remote. It worked for me when I got both the Cannot get remote repository refs-problems ("... Passphrase for..." and "Auth fail" in the "Push..." dialog).

Provided that you already:

  1. Setup your SSH keys with Github (Window > Preferences > General > Network Connections > SSH2)

  2. Setup your local repository (you can follow this guide for that)

  3. Created a Github repository (same guide)

... here's how you do it:

  • Go to the Git Repositories view (Window > Show View > Other > Git Repositories)
  • Expand your Repository and right click Remotes --> "Create Remote"
  • "Remote Name": origin, "Configure push": checked --> click "OK"
  • Click the "Change..." button
  • Paste your git URI and select protocol ssh --> click "Finish"
  • Now, click "Save and Push" and NOW you should get a password prompt --> enter the public key passphrase here (provided that you DID (and you should) setup a passphrase to your public key) --> click "OK"
  • Now you should get a confirmation window saying "Pushed to YourRepository - origin" --> click "OK"
  • Push to upstream, but this time use "Configured remote repository" as your Destination Git repository
  • Go get yourself a well earned cup of coffee!

How to do constructor chaining in C#

I hope following example shed some light on constructor chaining.
my use case here for example, you are expecting user to pass a directory to your constructor, user doesn't know what directory to pass and decides to let you assign default directory. you step up and assign a default directory that you think will work.

BTW, I used LINQPad for this example in case you are wondering what *.Dump() is.

void Main()

    CtorChaining ctorNoparam = new CtorChaining();
    //Result --> BaseDir C:\Program Files (x86)\Default\ 

    CtorChaining ctorOneparam = new CtorChaining("c:\\customDir");
    //Result --> BaseDir c:\customDir 

public class CtorChaining
    public string BaseDir;
    public static string DefaultDir = @"C:\Program Files (x86)\Default\";

    public CtorChaining(): this(null) {}

    public CtorChaining(string baseDir): this(baseDir, DefaultDir){}

    public CtorChaining(string baseDir, string defaultDir)
        //if baseDir == null, this.BaseDir = @"C:\Program Files (x86)\Default\"
        this.BaseDir = baseDir ?? defaultDir;

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

Reverse engineering from an APK file to a project

Not really. There are a number of dex disassembler/decompiler suites out there such as smali, or dex2jar that will generate semi-humanreadable output (in the case of dex2jar, you can get java code through the use of something like JD-GUI but the process is not perfect and it is very unlikely that you'll be able to 100% recreate your source code. However, it could potentially give you a place to start rebuilding your source tree.

How to change the integrated terminal in visual studio code or VSCode

Probably it is too late but the below thing worked for me:

  1. Open Settings --> this will open settings.json
  2. type
  3. Click on {} at the top right corner -- this will open an editor where this setting can be over ridden.
  4. Set the value as C:\\Users\\<user_name>\\Softwares\\Git\\bin\\bash.exe
  5. Click Ctrl + S

Try to open new terminal. It should open in bash editor in integrated mode.

MS Excel showing the formula in a cell instead of the resulting value

If you are using Excel 2013 Than do the following File > Option > Advanced > Under Display options for this worksheet: uncheck the checkbox before Show formulas in cells instead of their calculated results This should resolve the issue.

How do I clear all options in a dropdown box?

function removeOptions(obj) {
    while (obj.options.length) {

Where does Chrome store cookies?

The answer is due to the fact that Google Chrome uses an SQLite file to save cookies. It resides under:

C:\Users\<your_username>\AppData\Local\Google\Chrome\User Data\Default\

inside Cookies file. (which is an SQLite database file)

So it's not a file stored on hard drive but a row in an SQLite database file which can be read by a third party program such as: SQLite Database Browser

EDIT: Thanks to @Chexpir, it is also good to know that the values are stored encrypted.

Is there a way to force npm to generate package-lock.json?

By default, package-lock.json is updated whenever you run npm install. However, this can be disabled globally by setting package-lock=false in ~/.npmrc.

When the global package-lock=false setting is active, you can still force a project’s package-lock.json file to be updated by running:

npm install --package-lock

This command is the only surefire way of forcing a package-lock.json update.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

After a long struggle, I found the solution.

Solution: Add a reference to System.Net.Http.Formatting.dll. This assembly is also available in the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies folder.

The method ReadAsAsync is an extension method declared in the class HttpContentExtensions, which is in the namespace System.Net.Http in the library System.Net.Http.Formatting.

Reflector came to rescue!