Programs & Examples On #System variable

How to set java_home on Windows 7?

You may wanna look into Windows/System32 folder for the following files: - java.exe - javaw.exe - javaws.exe

Because, the path variable is including these files, you can get a headache trying to figure out why the java -version or javac -version keeps pointing to the old JAVA_HOME: rename those files, take out the extension with an underscore, for instance. And then, you only will have to create the JAVA_HOME variable, add it to the path variable (e.g., %JAVA_HOME%) and append the "\bin" particle. This way you need to only change the JAVA_HOME variable pointing to different JRE or JDK and have multiple installations of java just by setting JAVA_HOME.

This also means that it is better to install Java manually, without an installer, so you are able to toy with it.

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

How to download Google Play Services in an Android emulator?

Check out Setting Up Google Play Services which says:

To develop an app using the Google Play services APIs, you need to set up your project with the Google Play services SDK.

If you haven't installed the Google Play services SDK yet, go get it now by following the guide to Adding SDK Packages.

To test your app when using the Google Play services SDK, you must use either:

  • A compatible Android device that runs Android 2.3 or higher and includes Google Play Store.
  • The Android emulator with an AVD that runs the Google APIs platform based on Android 4.2.2 or higher.

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

If origin points to a bare repository on disk, this error can happen if that directory has been moved (even if you update the working copy's remotes). For example

$ mv /path/to/origin /somewhere/else
$ git remote set-url origin /somewhere/else
$ git diff origin/master
fatal: ambiguous argument 'origin': unknown revision or path not in the working tree.

Pulling once from the new origin solves the problem:

$ git stash
$ git pull origin master
$ git stash pop

Removing the remembered login and password list in SQL Server Management Studio

As gluecks pointed out, no more SqlStudio.bin in Microsoft SQL Server Management Studio 18. I also found this UserSettings.xml in C:\Users\userName\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0. But removing the <Element> containing the credential seems not working, it comes right back on the xml file, if I close and re-open it again.

Turns out, you need to close the SQL Server Management Studio first, then edit the UserSettings.xml file in your favorite editor, e.g. Visual Studio Code. I guess it's cached somewhere in SSMS besides this xml file?! And it's not on Control Panel\All Control Panel Items\Credential Manager\Windows Credentials.

How to make inline functions in C#


You can create anonymous methods or lambda expressions:

Func<string, string> PrefixTrimmer = delegate(string x) {
    return x ?? "";
Func<string, string> PrefixTrimmer = x => x ?? "";

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I found that I was using a selector for my rendorTo div that I was using to render my column highcharts graph. Apparently it adds the selector for you so you just need to pass id.

renderTo: $('#myGraphDiv') to a string 'myGraphDiv' this fixed the error hope this helps someone else out as well.

How do I calculate the date six months from the current date using the datetime Python module?

This doesn't answer the specific question (using datetime only) but, given that others suggested the use of different modules, here there is a solution using pandas.

import datetime as dt
import pandas as pd

date = - \


2019-05-04 00:00:00

Which works as expected in leap years

date = dt.datetime(2019,8,29) - \

2019-02-28 00:00:00

How do I call a dynamically-named method in Javascript?

Try with this:

var fn_name = "Colours",
fn = eval("populate_"+fn_name);

Remove all html tags from php string

$string = <p>Awesome</p><b> Website</b><i> by Narayan</i>. Thanks for visiting enter code here;
$tags = array("p", "i");

echo preg_replace('#<(' . implode( '|', $tags) . ')(?:[^>]+)?>.*?</\1>#s', '', $string);

Try this

How can I add an item to a IEnumerable<T> collection?

Easyest way to do that is simply

IEnumerable<T> items = new T[]{new T("msg")};
List<string> itemsList = new List<string>();
itemsList.AddRange(items.Select(y => y.ToString()));

Then you can return list as IEnumerable also because it implements IEnumerable interface

Spark - SELECT WHERE or filtering?

According to spark documentation "where() is an alias for filter()"

filter(condition) Filters rows using the given condition. where() is an alias for filter().

Parameters: condition – a Column of types.BooleanType or a string of SQL expression.

>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]

>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]

JPA and Hibernate - Criteria vs. JPQL or HQL

Criteria is an object-oriented API, while HQL means string concatenation. That means all of the benefits of object-orientedness apply:

  1. All else being equal, the OO version is somewhat less prone to error. Any old string could get appended into the HQL query, whereas only valid Criteria objects can make it into a Criteria tree. Effectively, the Criteria classes are more constrained.
  2. With auto-complete, the OO is more discoverable (and thus easier to use, for me at least). You don't necessarily need to remember which parts of the query go where; the IDE can help you
  3. You also don't need to remember the particulars of the syntax (like which symbols go where). All you need to know is how to call methods and create objects.

Since HQL is very much like SQL (which most devs know very well already) then these "don't have to remember" arguments don't carry as much weight. If HQL was more different, then this would be more importatnt.

Alternating Row Colors in Bootstrap 3 - No Table

There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type (or :nth-child -- either would work in this case.)

Smallest viewport:

@media (max-width:$smallest-breakpoint) {

  .row div {
     background: #eee;

  .row div:nth-of-type(2n) {
     background: #fff;


Medium viewport:

@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {

  .row div {
    background: #eee;

  .row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
    background: #fff;


Largest viewport:

@media (min-width:$mid-breakpoint) and (max-width:9999px) {

  .row div {
    background: #eee;

  .row div:nth-of-type(6n+4), 
  .row div:nth-of-type(6n+5), 
  .row div:nth-of-type(6n+6) {
      background: #fff;

Working fiddle here

Implicit function declarations in C

To complete the picture, since -Werror might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:


See Make one gcc warning an error?

Regarding general use of -Werror: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.

How to store the hostname in a variable in a .bat file?

Just create a .bat file with the line


in it. That's it. Windows also supports the hostname command.

How do you turn a Mongoose document into a plain object?

In some cases as @JohnnyHK suggested, you would want to get the Object as a Plain Javascript. as described in this Mongoose Documentation there is another alternative to query the data directly as object:

const docs = await Model.find().lean();

In addition if someone might want to conditionally turn to an object,it is also possible as an option argument, see find() docs at the third parameter:

const toObject = true;
const docs = await Model.find({},null,{lean:toObject});

its available on the fonctions: find(), findOne(), findById(), findOneAndUpdate(), and findByIdAndUpdate().

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

Non-const and const reference binding follow different rules

These are the rules of the C++ language:

  • an expression consisting of a literal number (12) is a "rvalue"
  • it is not permitted to create a non-const reference with a rvalue: int &ri = 12; is ill-formed
  • it is permitted to create a const reference with a rvalue: in this case, an unnamed object is created by the compiler; this object will persist as long as the reference itself exist.

You have to understand that these are C++ rules. They just are.

It is easy to invent a different language, say C++', with slightly different rules. In C++', it would be permitted to create a non-const reference with a rvalue. There is nothing inconsistent or impossible here.

But it would allow some risky code where the programmer might not get what he intended, and C++ designers rightly decided to avoid that risk.

Emulator in Android Studio doesn't start

I had a similar problem... Android Emulator doesn't open. You need to discover the reason of this... You could run your emulator from the command line. For this you could copy and paste your command line from "Run" or "AVD" Android Studio console. For example:

"{path}\android-sdk\tools\emulator.exe -avd Default_Nexus_5 -netspeed full -netdelay none"

When you launch it from a command line terminal, It give you a message with the error. In my case it was useful for discover the problem:

..\android-sdk\tools>emulator: ERROR: x86 emulation currently requires hardware acceleration! Please ensure Intel HAXM is properly installed and usable. CPU acceleration status: HAX kernel module is not installed!

  • I needed to activate GPU acceleration with a tool to enable it on my machine. I solved it installing from SDK Manager the tool HAXM...

  • I had another problem... For example i had assigned a bad url for skin path of my virtual device... To solve it I have configured my virtual device with a valid skin from my platform sdk: '{path}\android-sdk\platforms\android-{number}\skins{SCREEN_SIZE}'

Now it is opening fine.

Update 8/8/2019:

For newer version of Android SDK, emulator path should be:


reference (thank you @CoolMind)

How to create a Multidimensional ArrayList in Java?

Wouldn't List<ArrayList<String>> 2dlist = new ArrayList<ArrayList<String>>(); be a better (more efficient) implementation?

When a 'blur' event occurs, how can I find out which element focus went *to*?

You can fix IE with :


It looks like "explicitOriginalTarget" for FF.

Antoine And J

Local dependency in package.json

Actually, as of npm 2.0, there is support now local paths (see here).

Bytes of a string in Java

According to How to convert Strings to and from UTF8 byte arrays in Java:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

Adding elements to an xml file in C#

<Snippet name="abc"> 

name is an attribute, not an element. That's why it's failing. Look into using SetAttribute on the <Snippet> element.

root.SetAttribute("name", "name goes here");

is the code you need with what you have.

Backporting Python 3 open(encoding="utf-8") to Python 2

1. To get an encoding parameter in Python 2:

If you only need to support Python 2.6 and 2.7 you can use instead of open. io is the new io subsystem for Python 3, and it exists in Python 2,6 ans 2.7 as well. Please be aware that in Python 2.6 (as well as 3.0) it's implemented purely in python and very slow, so if you need speed in reading files, it's not a good option.

If you need speed, and you need to support Python 2.6 or earlier, you can use instead. It also has an encoding parameter, and is quite similar to except it handles line-endings differently.

2. To get a Python 3 open() style file handler which streams bytestrings:

open(filename, 'rb')

Note the 'b', meaning 'binary'.

Updating Anaconda fails: Environment Not Writable Error

On Windows, search for Anaconda PowerShell Prompt. Right click the program and select Run as administrator. In the command prompt, execute the following command:

conda update -n base -c defaults conda

Your Anaconda should now update without admin related errors.

Options for HTML scraping?


It's basically jQuery for C#. It depends on HTML Agility Pack for parsing the HTML.

Should __init__() call the parent class's __init__()?

IMO, you should call it. If your superclass is object, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override __init__ itself, for example when it has no (additional) internal state to initialize.

Is it possible to have SSL certificate for IP address, not domain name?

According to this answer, it is possible, but rarely used.

As for how to get it: I would tend to simply try and order one with the provider of your choice, and enter the IP address instead of a domain during the ordering process.

However, running a site on an IP address to avoid the DNS lookup sounds awfully like unnecessary micro-optimization to me. You will save a few milliseconds at best, and that is per visit, as DNS results are cached on multiple levels.

I don't think your idea makes sense from an optimization viewpoint.

How to round a numpy array?

It is worth noting that the accepted answer will round small floats down to zero.

>>> import numpy as np 
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03  4.82011728e-08  1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0.  ,  0.  ,  0.  ]) 

You can use set_printoptions and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:

>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]  

This way, you get the full versatility of format and maintain the full precision of numpy's datatypes.

Also note that this only affects printing, not the actual precision of the stored values used for computation.

VB.Net Properties - Public Get, Private Set

Yes, quite straight forward:

Private _name As String

Public Property Name() As String
        Return _name
    End Get
    Private Set(ByVal value As String)
        _name = value
    End Set
End Property

Add my custom http header to Spring RestTemplate request / extend RestTemplate

Add a "User-Agent" header to your request.

Some servers attempt to block spidering programs and scrapers from accessing their server because, in earlier days, requests did not send a user agent header.

You can either try to set a custom user agent value or use some value that identifies a Browser like "Mozilla/5.0 Firefox/26.0"

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();

headers.add("user-agent", "Mozilla/5.0 Firefox/26.0");
headers.set("user-key", "your-password-123"); // optional - in case you auth in headers
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Game[]> respEntity =, HttpMethod.GET, entity, Game[].class);;

Configure cron job to run every 15 minutes on Jenkins

Your syntax is slightly wrong. Say:

*/15 * * * * command
  |--> `*/15` would imply every 15 minutes.

* indicates that the cron expression matches for all values of the field.

/ describes increments of ranges.

Parsing Json rest api response in C#

Create a C# class that maps to your Json and use Newsoft JsonConvert to Deserialise it.

For example:

public Class MyResponse
    public Meta Meta { get; set; }
    public Response Response { get; set; }

Change / Add syntax highlighting for a language in Sublime 2/3

The "this" is already coloured in Javascript.

View->Syntax-> and choose your language to highlight.

How to 'bulk update' with Django?

IT returns number of objects are updated in table.

update_counts = ModelClass.objects.filter(name='bar').update(name="foo")

You can refer this link to get more information on bulk update and create. Bulk update and Create

Regex to match only uppercase "words" with some exceptions

To some extent, this is going to vary by the "flavour" of RegEx you're using. The following is based on .NET RegEx, which uses \b for word boundaries. In the last example, it also uses negative lookaround (?<!) and (?!) as well as non-capturing parentheses (?:)

Basically, though, if the terms always contain at least one uppercase letter followed by at least one number, you can use


For all-uppercase and numbers (total must be 2 or more):


For all-uppercase and numbers, but starting with at least one letter:


The granddaddy, to return items that have any combination of uppercase letters and numbers, but which are not single letters at the beginning of a line and which are not part of a line that is all uppercase:

(?:(?<!^)[A-Z]\b|(?<!^[A-Z0-9 ]*)\b[A-Z0-9]+\b(?![A-Z0-9 ]$))


The regex starts with (?:. The ?: signifies that -- although what follows is in parentheses, I'm not interested in capturing the result. This is called "non-capturing parentheses." Here, I'm using the paretheses because I'm using alternation (see below).

Inside the non-capturing parens, I have two separate clauses separated by the pipe symbol |. This is alternation -- like an "or". The regex can match the first expression or the second. The two cases here are "is this the first word of the line" or "everything else," because we have the special requirement of excluding one-letter words at the beginning of the line.

Now, let's look at each expression in the alternation.

The first expression is: (?<!^)[A-Z]\b. The main clause here is [A-Z]\b, which is any one capital letter followed by a word boundary, which could be punctuation, whitespace, linebreak, etc. The part before that is (?<!^), which is a "negative lookbehind." This is a zero-width assertion, which means it doesn't "consume" characters as part of a match -- not really important to understand that here. The syntax for negative lookbehind in .NET is (?<!x), where x is the expression that must not exist before our main clause. Here that expression is simply ^, or start-of-line, so this side of the alternation translates as "any word consisting of a single, uppercase letter that is not at the beginning of the line."

Okay, so we're matching one-letter, uppercase words that are not at the beginning of the line. We still need to match words consisting of all numbers and uppercase letters.

That is handled by a relatively small portion of the second expression in the alternation: \b[A-Z0-9]+\b. The \bs represent word boundaries, and the [A-Z0-9]+ matches one or more numbers and capital letters together.

The rest of the expression consists of other lookarounds. (?<!^[A-Z0-9 ]*) is another negative lookbehind, where the expression is ^[A-Z0-9 ]*. This means what precedes must not be all capital letters and numbers.

The second lookaround is (?![A-Z0-9 ]$), which is a negative lookahead. This means what follows must not be all capital letters and numbers.

So, altogether, we are capturing words of all capital letters and numbers, and excluding one-letter, uppercase characters from the start of the line and everything from lines that are all uppercase.

There is at least one weakness here in that the lookarounds in the second alternation expression act independently, so a sentence like "A P1 should connect to the J9" will match J9, but not P1, because everything before P1 is capitalized.

It is possible to get around this issue, but it would almost triple the length of the regex. Trying to do so much in a single regex is seldom, if ever, justfied. You'll be better off breaking up the work either into multiple regexes or a combination of regex and standard string processing commands in your programming language of choice.

Excel VBA - Range.Copy transpose paste

Worksheets("Sheet2").Range("A1").PasteSpecial Transpose:=True

/etc/apt/sources.list" E212: Can't open file for writing

change the permission for the other user for that type setfacl -m u:username:rw filename

How do I make a div full screen?

This is the simplest one.

#divid {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;

using setTimeout on promise chain

To keep the promise chain going, you can't use setTimeout() the way you did because you aren't returning a promise from the .then() handler - you're returning it from the setTimeout() callback which does you no good.

Instead, you can make a simple little delay function like this:

function delay(t, v) {
   return new Promise(function(resolve) { 
       setTimeout(resolve.bind(null, v), t)

And, then use it like this:

    let all_links = (JSON.parse(links));

    return getLinks(globalObj["one"]+".txt");

    // return a promise here that will be chained to prior promise
    return delay(1000).then(function() {
        return getLinks(globalObj["two"]+".txt");

Here you're returning a promise from the .then() handler and thus it is chained appropriately.

You can also add a delay method to the Promise object and then directly use a .delay(x) method on your promises like this:

function delay(t, v) {_x000D_
   return new Promise(function(resolve) { _x000D_
       setTimeout(resolve.bind(null, v), t)_x000D_
Promise.prototype.delay = function(t) {_x000D_
    return this.then(function(v) {_x000D_
        return delay(t, v);_x000D_
Promise.resolve("hello").delay(500).then(function(v) {_x000D_

Or, use the Bluebird promise library which already has the .delay() method built-in.

How to download file from database/folder using php

here is the code to download file with how much % it is downloaded

$ch = curl_init();
$downloadFile = fopen( 'file name here', 'w' );
curl_setopt($ch, CURLOPT_URL, "file link here");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 65536);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'downloadProgress'); 
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt( $ch, CURLOPT_FILE, $downloadFile );

function downloadProgress ($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) {

    $percen= (($downloaded_size/$download_size)*100);
    echo $percen."<br>";



what's the correct way to send a file from REST web service to client?

I don't recommend encoding binary data in base64 and wrapping it in JSON. It will just needlessly increase the size of the response and slow things down.

Simply serve your file data using GET and application/octect-streamusing one of the factory methods of (part of the JAX-RS API, so you're not locked into Jersey):

public Response getFile() {
  File file = ... // Initialize this to the File path you want to serve.
  return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
      .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional

If you don't have an actual File object, but an InputStream, Response.ok(entity, mediaType) should be able to handle that as well.

How to call a function after delay in Kotlin?

A simple example to show a toast after 3 seconds :

fun onBtnClick() {
    val handler = Handler()
    handler.postDelayed({ showToast() }, 3000)

fun showToast(){
    Toast.makeText(context, "Its toast!", Toast.LENGTH_SHORT).show()

Calculate row means on subset of columns

(Another solution using pivot_longer & pivot_wider from latest Tidyr update)

You should try using pivot_longer to get your data from wide to long form Read latest tidyR update on pivot_longer & pivot_wider (


Output here

  ID     mean
  <fct> <dbl>
1 A      3.67
2 B      4.33
3 C      3.33
4 D      4.67
5 E      4.33

Can't install any packages in Node.js using "npm install"

Npm repository is currently down. See issue #2694 on npm github

To use a mirror in the meanwhile:

 npm set registry

you can reset this later with:

 npm set registry


react-router getting this.props.location in child components

If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';

Using this you can export your child class as -

class MyApp extends Component{
    // your code

export default withRouter(MyApp);

And your class with Router -

// your code
      <Route path="/myapp" component={MyApp} />
      // or if you are sending additional fields
      <Route path="/myapp" component={() =><MyApp process={...} />} />

What is the python keyword "with" used for?

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

Java SSLHandshakeException "no cipher suites in common"


import java.util.*;
class Test{
  public static void main(String[] args){
      SSLContext context = SSLContext.getInstance("TLSv1.2");
      SSLServerSocketFactory serverSocketFactory = context.getServerSocketFactory();
      SSLServerSocket server = (SSLServerSocket)serverSocketFactory.createServerSocket(1024);
      SSLSocket socket = (SSLSocket)server.accept();
      DataInputStream in = new DataInputStream(socket.getInputStream());
      DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    }catch(Exception e){e.printStackTrace();}


import java.util.*;
class Test2{
  public static void main(String[] args){
      SSLContext context = SSLContext.getInstance("TLSv1.2");
      SSLSocketFactory socketFactory = context.getSocketFactory();
      SSLSocket socket = (SSLSocket)socketFactory.createSocket("localhost", 1024);
      DataInputStream in = new DataInputStream(socket.getInputStream());
      DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    }catch(Exception e){e.printStackTrace();}

server.setEnabledCipherSuites(server.getSupportedCipherSuites()); socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());

Where is my m2 folder on Mac OS X Mavericks

It's in your home folder but it's hidden by default.

Typing the below commands in the terminal made it visible for me (only the .m2 folder that is, not all the other hidden folders).

> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2         


sklearn: Found arrays with inconsistent numbers of samples when calling

during train test split you might have done a mistake


The above code is correct

You might have done like below which is wrong


Can pm2 run an 'npm start' script

PM2 now supports npm start:

pm2 start npm -- start

To assign a name to the PM2 process, use the --name option:

pm2 start npm --name "app name" -- start

Collapsing Sidebar with Bootstrap

EDIT: I've added one more option for bootstrap sidebars.

There are actually three manners in which you can make a bootstrap 3 sidebar. I tried to keep the code as simple as possible.

Fixed sidebar

Here you can see a demo of a simple fixed sidebar I've developed with the same height as the page

Sidebar in a column

I've also developed a rather simple column sidebar that works in a two or three column page inside a container. It takes the length of the longest column. Here you can see a demo


If you google bootstrap dashboard, you can find multiple suitable dashboard, such as this one. However, most of them require a lot of coding. I've developed a dashboard that works without additional javascript (next to the bootstrap javascript). Here is a demo

For all three examples you off course have to include the jquery, bootstrap css, js and theme.css files.


If you want the sidebar to hide on pressing a button this is also possible with only a little javascript.Here is a demo

What's the difference between primitive and reference types?

these are primitive data types

  • boolean
  • character
  • byte
  • short
  • integer
  • long
  • float
  • double

saved in stack in the memory which is managed memory on the other hand object data type or reference data type stored in head in the memory managed by GC

this is the most important difference

PostgreSQL create table if not exists

There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:

CREATE OR REPLACE FUNCTION prc_create_sch_foo_table() RETURNS VOID AS $$

EXECUTE 'CREATE TABLE /* IF NOT EXISTS add for PostgreSQL 9.1+ */ (
                    id serial NOT NULL, 
                    demo_column varchar NOT NULL, 
                    demo_column2 varchar NOT NULL,
                    CONSTRAINT pk_sch_foo PRIMARY KEY (id));
                   CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column ON;
                   CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column2 ON;'
               WHERE NOT EXISTS(SELECT * FROM information_schema.tables 
                        WHERE table_schema = 'sch' 
                            AND table_name = 'foo');

         EXCEPTION WHEN null_value_not_allowed THEN
           WHEN duplicate_table THEN

END; $$ LANGUAGE plpgsql;

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

From the Help:
IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.
IsEmpty only returns meaningful information for variants.

To check if a cell is empty, you can use cell(x,y) = "".
You might eventually save time by using Range("X:Y").SpecialCells(xlCellTypeBlanks) or xlCellTypeConstants or xlCellTypeFormulas

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

For anyone landing here who is trying to upgrade from MVC 4 to MVC5, I was able to resolve this issue by following the instructions at

I also had to install the "Microsoft.AspNet.WebApi.WebHost" package from nuget. But that's it.

Oh, and I had to create this appSetting: <add key="owin:AutomaticAppStartup" value="false" />


How to parse a CSV file in Bash?

If you want to read CSV file with some lines, so this the solution.

while IFS=, read -ra line
    test $i -eq 1 && ((i=i+1)) && continue
    for col_val in ${line[@]}
        echo -n "$col_val|"                 
done < "$csvFile"

Java 8: merge lists with stream API

Alternative: Stream.concat()


Get the directory from a file path in java (android)

A better way, use getParent() from File Class..

String a="/root/sdcard/Pictures/img0001.jpg"; // A valid file path 
File file = new File(a); 
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null

CSS list item width/height does not work

Declare the a element as display: inline-block and drop the width and height from the li element.

Alternatively, apply a float: left to the li element and use display: block on the a element. This is a bit more cross browser compatible, as display: inline-block is not supported in Firefox <= 2 for example.

The first method allows you to have a dynamically centered list if you give the ul element a width of 100% (so that it spans from left to right edge) and then apply text-align: center.

Use line-height to control the text's Y-position inside the element.

How to save a list to a file and read it as a list type?

pickle and other serialization packages work. So does writing it to a .py file that you can then import.

>>> score = [1,2,3,4,5]
>>> with open('', 'w') as f:
...   f.write('score = %s' % score)
>>> from file import score as my_list
>>> print(my_list)
[1, 2, 3, 4, 5]

Exception : peer not authenticated

This exception will come in case your server is based on JDK 7 and your client is on JDK 6 and using SSL certificates. In JDK 7 sslv2hello message handshaking is disabled by default while in JDK 6 sslv2hello message handshaking is enabled. For this reason when your client trying to connect server then a sslv2hello message will be sent towards server and due to sslv2hello message disable you will get this exception. To solve this either you have to move your client to JDK 7 or you have to use 6u91 version of JDK. But to get this version of JDK you have to get the MOS (My Oracle Support) Enterprise support. This patch is not public.

How do I clear all options in a dropdown box?


Writing File to Temp Folder

For %appdata% take a look to


Showing an image from console in Python

You cannot display images in a console window. You need a graphical toolkit such as Tkinter, PyGTK, PyQt, PyKDE, wxPython, PyObjC or PyFLTK. There are plenty of tutorial how to create siomple windows and loading images iun python.

How to change the color of the axis, ticks and labels for a plot in matplotlib

motivated by previous contributors, this is an example of three axes.

import matplotlib.pyplot as plt




ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax3=fig.add_subplot(111, label="3", frame_on=False)

ax.plot(x_values1, y_values1, color="C0")
ax.set_xlabel("x label 1", color="C0")
ax.set_ylabel("y label 1", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")

ax2.scatter(x_values2, y_values2, color="C1")
ax2.set_xlabel('x label 2', color="C1") 
ax2.xaxis.set_label_position('bottom') # set the position of the second x-axis to bottom
ax2.spines['bottom'].set_position(('outward', 36))
ax2.tick_params(axis='x', colors="C1")
ax2.set_ylabel('y label 2', color="C1")       
ax2.tick_params(axis='y', colors="C1")

ax3.plot(x_values3, y_values3, color="C2")
ax3.set_xlabel('x label 3', color='C2')
ax3.spines['bottom'].set_position(('outward', 72))
ax3.tick_params(axis='x', colors='C2')
ax3.set_ylabel('y label 3', color='C2')
ax3.spines['right'].set_position(('outward', 36))
ax3.tick_params(axis='y', colors='C2')

How do I break out of nested loops in Java?

Use Labels.

INNER:for(int j = 0; j < numbers.length; j++) {
    System.out.println("Even number: " + i + ", break  from INNER label");
    break INNER;

Refer to this article

CSS center content inside div

The problem is that you assigned a fixed width to your .wrap DIV. The DIV itself is centered (you can see that when you add a border to it) but the DIV is just too wide. In other words the content does not fill the whole width of the DIV.

To solve the problem you have to make sure, that the .wrap DIV is only as wide as it's content.

To achieve that you have to remove the floating in the content elements and set the display property of the block levels elements to inline:

#partners .wrap {
 display: inline;

.wrap { margin: 0 auto; position: relative;}

#partners h2 {
color: #A6A5A5;
font-weight: normal;
margin: 2px 15px 0 0;
display: inline;

#partners ul {
display: inline;

#partners li {display: inline}

ul { list-style-position: outside; list-style-type: none; }

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

In my case i was missing trailing / in path.

find /var/opt/gitlab/backups/ -name *.tar

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Stuffs I check to verify logging,

1) Check that there're no older log4j versions.

mvn dependency:tree | grep log ## ./gradlew dependencies | grep log
[INFO] +- com.prayagupd:log-service:jar:1.0:compile
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.6.2:compile
[INFO] +- org.apache.logging.log4j:log4j-core:jar:2.6.2:compile
[INFO] |  \- commons-logging:commons-logging:jar:1.1.1:compile

2) make sure I'm setting log4j2.json properly, which is done with -Dlog4j.configurationFile=???

val logConfig: PropertiesConfiguration = new PropertiesConfiguration("")
System.setProperty("log4j.configurationFile", logConfig.getString("log4j.config.file"))

println("log4j.configurationFile :: " + System.getProperty("log4j.configurationFile"))


Configurator.initialize(null, logConfig.getString("log4j.config.file"));

Also if auto detection is happening make sure the file name is log4j2.* not log4j.*

3) Another check is for parser for log4j2.json. Thanks log4j team for not providing parser within the API.


This might throw an exception if can not find the json parser

[Fatal Error] log4j2.json:1:1: Content is not allowed in prolog.

Adding a column after another column within SQL

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:

ALTER TABLE name ALTER column POSITION new_position

I guess it may work in other cases as well.

How to join (merge) data frames (inner, outer, left, right)

Update on data.table methods for joining datasets. See below examples for each type of join. There are two methods, one from [.data.table when passing second data.table as the first argument to subset, another way is to use merge function which dispatches to fast data.table method.

df1 = data.frame(CustomerId = c(1:6), Product = c(rep("Toaster", 3), rep("Radio", 3)))
df2 = data.frame(CustomerId = c(2L, 4L, 7L), State = c(rep("Alabama", 2), rep("Ohio", 1))) # one value changed to show full outer join


dt1 =
dt2 =
setkey(dt1, CustomerId)
setkey(dt2, CustomerId)
# right outer join keyed data.tables

setkey(dt1, NULL)
setkey(dt2, NULL)
# right outer join unkeyed data.tables - use `on` argument
dt1[dt2, on = "CustomerId"]

# left outer join - swap dt1 with dt2
dt2[dt1, on = "CustomerId"]

# inner join - use `nomatch` argument
dt1[dt2, nomatch=NULL, on = "CustomerId"]

# anti join - use `!` operator
dt1[!dt2, on = "CustomerId"]

# inner join - using merge method
merge(dt1, dt2, by = "CustomerId")

# full outer join
merge(dt1, dt2, by = "CustomerId", all = TRUE)

# see ? arguments for other cases

Below benchmark tests base R, sqldf, dplyr and data.table.
Benchmark tests unkeyed/unindexed datasets. Benchmark is performed on 50M-1 rows datasets, there are 50M-2 common values on join column so each scenario (inner, left, right, full) can be tested and join is still not trivial to perform. It is type of join which well stress join algorithms. Timings are as of sqldf:0.4.11, dplyr:0.7.8, data.table:1.12.0.

# inner
Unit: seconds
   expr       min        lq      mean    median        uq       max neval
   base 111.66266 111.66266 111.66266 111.66266 111.66266 111.66266     1
  sqldf 624.88388 624.88388 624.88388 624.88388 624.88388 624.88388     1
  dplyr  51.91233  51.91233  51.91233  51.91233  51.91233  51.91233     1
     DT  10.40552  10.40552  10.40552  10.40552  10.40552  10.40552     1
# left
Unit: seconds
   expr        min         lq       mean     median         uq        max 
   base 142.782030 142.782030 142.782030 142.782030 142.782030 142.782030     
  sqldf 613.917109 613.917109 613.917109 613.917109 613.917109 613.917109     
  dplyr  49.711912  49.711912  49.711912  49.711912  49.711912  49.711912     
     DT   9.674348   9.674348   9.674348   9.674348   9.674348   9.674348       
# right
Unit: seconds
   expr        min         lq       mean     median         uq        max
   base 122.366301 122.366301 122.366301 122.366301 122.366301 122.366301     
  sqldf 611.119157 611.119157 611.119157 611.119157 611.119157 611.119157     
  dplyr  50.384841  50.384841  50.384841  50.384841  50.384841  50.384841     
     DT   9.899145   9.899145   9.899145   9.899145   9.899145   9.899145     
# full
Unit: seconds
  expr       min        lq      mean    median        uq       max neval
  base 141.79464 141.79464 141.79464 141.79464 141.79464 141.79464     1
 dplyr  94.66436  94.66436  94.66436  94.66436  94.66436  94.66436     1
    DT  21.62573  21.62573  21.62573  21.62573  21.62573  21.62573     1

Be aware there are other types of joins you can perform using data.table:
- update on join - if you want to lookup values from another table to your main table
- aggregate on join - if you want to aggregate on key you are joining you do not have to materialize all join results
- overlapping join - if you want to merge by ranges
- rolling join - if you want merge to be able to match to values from preceeding/following rows by rolling them forward or backward
- non-equi join - if your join condition is non-equal

Code to reproduce:

sapply(c("sqldf","dplyr","data.table"), packageVersion, simplify=FALSE)

n = 5e7
df1 = data.frame(x=sample(n,n-1L), y1=rnorm(n-1L))
df2 = data.frame(x=sample(n,n-1L), y2=rnorm(n-1L))
dt1 =
dt2 =

mb = list()
# inner join
microbenchmark(times = 1L,
               base = merge(df1, df2, by = "x"),
               sqldf = sqldf("SELECT * FROM df1 INNER JOIN df2 ON df1.x = df2.x"),
               dplyr = inner_join(df1, df2, by = "x"),
               DT = dt1[dt2, nomatch=NULL, on = "x"]) -> mb$inner

# left outer join
microbenchmark(times = 1L,
               base = merge(df1, df2, by = "x", all.x = TRUE),
               sqldf = sqldf("SELECT * FROM df1 LEFT OUTER JOIN df2 ON df1.x = df2.x"),
               dplyr = left_join(df1, df2, by = c("x"="x")),
               DT = dt2[dt1, on = "x"]) -> mb$left

# right outer join
microbenchmark(times = 1L,
               base = merge(df1, df2, by = "x", all.y = TRUE),
               sqldf = sqldf("SELECT * FROM df2 LEFT OUTER JOIN df1 ON df2.x = df1.x"),
               dplyr = right_join(df1, df2, by = "x"),
               DT = dt1[dt2, on = "x"]) -> mb$right

# full outer join
microbenchmark(times = 1L,
               base = merge(df1, df2, by = "x", all = TRUE),
               dplyr = full_join(df1, df2, by = "x"),
               DT = merge(dt1, dt2, by = "x", all = TRUE)) -> mb$full

lapply(mb, print) -> nul

PHP, Get tomorrows date from date

 $tomorrow = date("Y-m-d", strtotime('tomorrow'));


  $tomorrow = date("Y-m-d", strtotime("+1 day"));

Help Link: STRTOTIME()

Deserializing JSON data to C# using JSON.NET

You can use:

JsonConvert.PopulateObject(json, obj);

here: json is the json string,obj is the target object. See: example

Note: PopulateObject() will not erase obj's list data, after Populate(), obj's list member will contains its original data and data from json string

JSON.parse unexpected character error

You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify() .

Updated your line below,


or if you have JSON stored in some variable:


SQL Error with Order By in Subquery

Try moving the order by clause outside sub select and add the order by field in sub select


(SELECT COUNT(1) ,refKlinik_id FROM Seanslar WHERE MONTH(tarihi) = 4 GROUP BY refKlinik_id)
as dorduncuay 

ORDER BY refKlinik_id 

NSString with \n or line break

Line breaks character for NSString is \r

correct way to use [NSString StringWithFormat:@"%@\r%@",string1,string2];

\r ----> carriage return

Git - deleted some files locally, how do I get them from a remote repository

If you deleted multiple files locally and did not commit the changes, go to your local repository path, open the git shell and type.

$ git checkout HEAD .

All the deleted files before the last commit will be recovered.

Adding "." will recover all the deleted the files in the current repository, to their respective paths.

For more details checkout the documentation.

Android emulator: How to monitor network traffic?

For OS X you can use Charles, it's simple and easy to use.

For more information, please have a look at Android Emulator and Charles Proxy blog post.

How to detect orientation change in layout in Android?

For loading the layout in layout-land folder means you have two separate layouts then you have to make setContentView in onConfigurationChanged method.

public void onConfigurationChanged(Configuration newConfig) {

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){

If you have only one layout then no necessary to make setContentView in This method. simply

public void onConfigurationChanged(Configuration newConfig) {

Get lengths of a list in a jinja2 template

Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.

{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li>    {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}

Web Service vs WCF Service

This answer is based on an article that no longer exists:

Summary of article:

"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.

You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?

Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."

... later ...

"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"

Using PHP with

Erm, why would you want to? Leave PHP on the backend and NodeJS/Sockets to do its non-blocking thing.

Here is something to get you started:

Personally I have express running with an endpoint that is listening expressly for interaction from PHP.

For example, if I have sent a user an email, I want to display a real-time notification to the user.

Want interaction from to php, well you can just do something like this:

var http = require('http'),
            host = WWW_HOST,
            clen = 'userid=' + userid,
            site = http.createClient(80, host),
            request = site.request("POST", "/modules/nodeim/includes/",  

request.write('userid=' + userid);      

Seriously, PHP is great for doing server side stuff and let it be with the connections it has no place in this domain now. Why do anything long-polling when you have websockets or flashsockets.

Exploitable PHP functions

I guess you won't be able to really find all possible exploits by parsing your source files.

  • also if there are really great lists provided in here, you can miss a function which can be exploitet

  • there still could be "hidden" evil code like this

$myEvilRegex = base64_decode('Ly4qL2U=');

preg_replace($myEvilRegex, $_POST['code']);

  • you could now say, i simply extend my script to also match this

  • but then you will have that mayn "possibly evil code" which additionally is out of it's context

  • so to be (pseudo-)secure, you should really write good code and read all existing code yourself

Checking something isEmpty in Javascript?

A more readable version of @SJ00 answer:

 * Checks if a JavaScript value is empty
 * @example
 *    isEmpty(null); // true
 *    isEmpty(undefined); // true
 *    isEmpty(''); // true
 *    isEmpty([]); // true
 *    isEmpty({}); // true
 * @param {any} value - item to test
 * @returns {boolean} true if empty, otherwise false
function isEmpty(value) {
    return (
        value === null || // check for null
        value === undefined || // check for undefined
        value === '' || // check for empty string
        (Array.isArray(value) && value.length === 0) || // check for empty array
        (typeof value === 'object' && Object.keys(value).length === 0) // check for empty object

mysql error 1364 Field doesn't have a default values

i solved problem changing my.ini file located in data folder. for mysql 5.6 my.ini file moved to data folder rather the bin or mysql installation folder.

Can we instantiate an abstract class directly?

You can't directly instantiate an abstract class, but you can create an anonymous class when there is no concrete class:

public class AbstractTest {
    public static void main(final String... args) {
        final Printer p = new Printer() {
            void printSomethingOther() {
            public void print() {
                printSomethingOther(); // works fine
        //p.printSomethingOther(); // does not work

abstract class Printer {
    public void print() {

This works with interfaces, too.

Tooltips for cells in HTML table (no Javascript)

Yes. You can use the title attribute on cell elements, with poor usability, or you can use CSS tooltips (several existing questions, possibly duplicates of this one).

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

Sorry to revive a dead thread but i solved this on VS2017 by deleting the project template cache and item template cache folders in


Then resetting the visual studio settings via

Tools>Import and export settings>reset all settings

Also ive heard turning off "Lightweight solution load for all projects" can help.

What does this GCC error "... relocation truncated to fit..." mean?

I ran into the exact same issue. After compiling without the -fexceptions build flag, the file compiled with no issue

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

Path of currently executing powershell script

For PowerShell 3.0 users - following works for both modules and script files:

function Get-ScriptDirectory {
    Split-Path -parent $PSCommandPath

Iterating Through a Dictionary in Swift

Arrays are ordered collections but dictionaries and sets are unordered collections. Thus you can't predict the order of iteration in a dictionary or a set.

Read this article to know more about Collection Types: Swift Programming Language

Convert python long/int to fixed size byte array



The 192 is 768 / 4, because OP wanted 768-bit numbers and there are 4 bits in a hex digit. If you need a bigger bytearray use a format string with a higher number. Example:

>>> big_int = 911085911092802609795174074963333909087482261102921406113936886764014693975052768158290106460018649707059449553895568111944093294751504971131180816868149233377773327312327573120920667381269572962606994373889233844814776702037586419
>>> bytearray.fromhex('{:0192x}'.format(big_int))
>>> lepi_int = 0x963b685edb4a8f336f624c9cc2b02d9ea4536a2df669c19e9794854d1d93105c81c289cde061c0448176dfeda9c18370db55f1d0fe5229ce07de704d88cc7f765c1c8d69874e008da8bd5b3cdfaf137a3a48edc229a41e0fa792a7c61686f1f
>>> bytearray.fromhex('{:0192x}'.format(lepi_int))

[My answer had used hex() before. I corrected it with format() in order to handle ints with odd-sized byte expressions. This fixes previous complaints about ValueError.]

Append text to file from command line without using io redirection

If you just want to tack something on by hand, then the sed answer will work for you. If instead the text is in file(s) (say file1.txt and file2.txt):

Using Perl:

perl -e 'open(OUT, ">>", "outfile.txt"); print OUT while (<>);' file*.txt

N.B. while the >> may look like an indication of redirection, it is just the file open mode, in this case "append".

docker command not found even though installed with apt-get

IMPORTANT - on ubuntu package docker is something entirely different ( avoid it ) :

issue following to view what if any packages you have mentioning docker

dpkg -l|grep docker

if only match is following then you do NOT have docker installed below is an unrelated package

docker - System tray for KDE3/GNOME2 docklet applications

if you see something similar to following then you have docker installed

 dpkg -l|grep docker

ii  docker-ce                                  5:19.03.13~3-0~ubuntu-focal         amd64        Docker: the open-source application container engine
ii  docker-ce-cli                              5:19.03.13~3-0~ubuntu-focal         amd64        Docker CLI: the open-source application container engine

NOTE - ubuntu package is not getting updates ( obsolete do NOT use )

Instead do this : install the latest version of docker on linux by executing the following:

  sudo curl -sSL | sh
# sudo curl -sSL | sh  # get dev pipeline version

here is a typical output ( ubuntu 16.04 )

apparmor is enabled in the kernel and apparmor utils were already installed
+ sudo -E sh -c apt-key adv --keyserver hkp:// --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
Executing: /tmp/tmp.rAAGu0P85R/ --keyserver
gpg: requesting key 2C52609D from hkp server
gpg: key 2C52609D: "Docker Release Tool (releasedocker) <[email protected]>" 1 new signature
gpg: Total number processed: 1
gpg:         new signatures: 1
+ break
+ sudo -E sh -c apt-key adv -k 58118E89F3A912897C070ADBF76221572C52609D >/dev/null
+ sudo -E sh -c mkdir -p /etc/apt/sources.list.d
+ dpkg --print-architecture
+ sudo -E sh -c echo deb [arch=amd64] ubuntu-xenial main > /etc/apt/sources.list.d/docker.list
+ sudo -E sh -c sleep 3; apt-get update; apt-get install -y -q docker-engine
Hit:1 precise InRelease
Hit:2 xenial InRelease                                                           
Ign:3 stable InRelease                                                                      
Hit:4 stable Release                                                                        
Hit:5 xenial InRelease                                                                        
Hit:6 xenial InRelease                                                     
Hit:7 xenial-updates InRelease                                             
Hit:8 xenial InRelease                                                 
Ign:9 wheezy/mongodb-org/3.2 InRelease                                                         
Hit:10 xenial-backports InRelease                                          
Hit:11 wheezy/mongodb-org/3.2 Release                                                          
Hit:12 xenial-security InRelease                                           
Hit:14 xenial InRelease                                                                 
Ign:15 wily InRelease                                                                             
Ign:16 stable InRelease                                                                        
Hit:17 stable Release                                                                          
Get:18 wily Release [6,596 B]            
Get:19 ubuntu-xenial InRelease [20.6 kB]    
Ign:20 xenial InRelease                      
Hit:22 xenial Release
Hit:23 stable InRelease
Hit:26 stable InRelease
Get:28 ubuntu-xenial/main amd64 Packages [1,719 B]
Hit:29 jessie InRelease
Fetched 28.9 kB in 1s (17.2 kB/s)
Reading package lists... Done
W: Signature by key 42F3E95A2C4F08279C4960ADD68FA50FEA312927 uses weak digest algorithm (SHA1)
Reading package lists...
Building dependency tree...
Reading state information...
The following additional packages will be installed:
  aufs-tools cgroupfs-mount
The following NEW packages will be installed:
  aufs-tools cgroupfs-mount docker-engine
0 upgraded, 3 newly installed, 0 to remove and 17 not upgraded.
Need to get 14.6 MB of archives.
After this operation, 73.7 MB of additional disk space will be used.
Get:1 xenial/universe amd64 aufs-tools amd64 1:3.2+20130722-1.1ubuntu1 [92.9 kB]
Get:2 xenial/universe amd64 cgroupfs-mount all 1.2 [4,970 B]
Get:3 ubuntu-xenial/main amd64 docker-engine amd64 1.11.2-0~xenial [14.5 MB]
Fetched 14.6 MB in 7s (2,047 kB/s)
Selecting previously unselected package aufs-tools.
(Reading database ... 427978 files and directories currently installed.)
Preparing to unpack .../aufs-tools_1%3a3.2+20130722-1.1ubuntu1_amd64.deb ...
Unpacking aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Selecting previously unselected package cgroupfs-mount.
Preparing to unpack .../cgroupfs-mount_1.2_all.deb ...
Unpacking cgroupfs-mount (1.2) ...
Selecting previously unselected package docker-engine.
Preparing to unpack .../docker-engine_1.11.2-0~xenial_amd64.deb ...
Unpacking docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for systemd (229-4ubuntu6) ...
Setting up aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Setting up cgroupfs-mount (1.2) ...
Setting up docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for systemd (229-4ubuntu6) ...
Processing triggers for ureadahead (0.100.0-19) ...
+ sudo -E sh -c docker version
 Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   b9f10c9
 Built:        Wed Jun  1 22:00:43 2016
 OS/Arch:      linux/amd64

 Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   b9f10c9
 Built:        Wed Jun  1 22:00:43 2016
 OS/Arch:      linux/amd64

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  sudo usermod -aG docker stens

Remember that you will have to log out and back in for this to take effect!

Here is the underlying detailed install instructions which as you can see comes bundled into above technique ... Above one liner gives you same as :

Once installed you can see what docker packages were installed by issuing

dpkg -l|grep docker
ii  docker-ce                                  5:19.03.13~3-0~ubuntu-focal         amd64        Docker: the open-source application container engine
ii  docker-ce-cli                              5:19.03.13~3-0~ubuntu-focal         amd64        Docker CLI: the open-source application container engine

now Docker updates will get installed going forward when you issue

sudo apt-get update
sudo apt-get upgrade

take a look at

 ls -latr /etc/apt/sources.list.d/*docker*
-rw-r--r-- 1 root root 202 Jun 23 10:01 /etc/apt/sources.list.d/
-rw-r--r-- 1 root root  71 Jul  4 11:32 /etc/apt/sources.list.d/docker.list

cat /etc/apt/sources.list.d/docker.list

deb [arch=amd64] ubuntu-xenial main

or more generally

cd /etc/apt
grep -r docker *
sources.list.d/docker.list:deb [arch=amd64] focal test

IPC performance: Named Pipe vs Socket

Best results you'll get with Shared Memory solution.

Named pipes are only 16% better than TCP sockets.

Results are get with IPC benchmarking:

  • System: Linux (Linux ubuntu 4.4.0 x86_64 i7-6700K 4.00GHz)
  • Message: 128 bytes
  • Messages count: 1000000

Pipe benchmark:

Message size:       128
Message count:      1000000
Total duration:     27367.454 ms
Average duration:   27.319 us
Minimum duration:   5.888 us
Maximum duration:   15763.712 us
Standard deviation: 26.664 us
Message rate:       36539 msg/s

FIFOs (named pipes) benchmark:

Message size:       128
Message count:      1000000
Total duration:     38100.093 ms
Average duration:   38.025 us
Minimum duration:   6.656 us
Maximum duration:   27415.040 us
Standard deviation: 91.614 us
Message rate:       26246 msg/s

Message Queue benchmark:

Message size:       128
Message count:      1000000
Total duration:     14723.159 ms
Average duration:   14.675 us
Minimum duration:   3.840 us
Maximum duration:   17437.184 us
Standard deviation: 53.615 us
Message rate:       67920 msg/s

Shared Memory benchmark:

Message size:       128
Message count:      1000000
Total duration:     261.650 ms
Average duration:   0.238 us
Minimum duration:   0.000 us
Maximum duration:   10092.032 us
Standard deviation: 22.095 us
Message rate:       3821893 msg/s

TCP sockets benchmark:

Message size:       128
Message count:      1000000
Total duration:     44477.257 ms
Average duration:   44.391 us
Minimum duration:   11.520 us
Maximum duration:   15863.296 us
Standard deviation: 44.905 us
Message rate:       22483 msg/s

Unix domain sockets benchmark:

Message size:       128
Message count:      1000000
Total duration:     24579.846 ms
Average duration:   24.531 us
Minimum duration:   2.560 us
Maximum duration:   15932.928 us
Standard deviation: 37.854 us
Message rate:       40683 msg/s

ZeroMQ benchmark:

Message size:       128
Message count:      1000000
Total duration:     64872.327 ms
Average duration:   64.808 us
Minimum duration:   23.552 us
Maximum duration:   16443.392 us
Standard deviation: 133.483 us
Message rate:       15414 msg/s

Selecting the last value of a column

Regarding @Jon_Schneider's comment, if the column has blank cells just use COUNTA()

=INDEX(G2:G; COUNT**A**(G2:G))

How to check if curl is enabled or disabled

Hope this helps.

    function _iscurl() {
        return function_exists('curl_version');

How to resolve ORA 00936 Missing Expression Error?

set pd.practice_name = (
    AND PRSQ.PRAD_ID = pd.provider_id
    AND PRSQ.PRAD_TYPE = pd.prov_addr_type
    AND ROWNUM = 1

Get Substring between two characters using javascript

If you want to extract all substrings from a string, that occur between two delimiters (different or same), you can use this function. It returns an array with all substrings found:

function get_substrings_between(str, startDelimiter, endDelimiter) 
    var contents = [];
    var startDelimiterLength = startDelimiter.length;
    var endDelimiterLength = endDelimiter.length;
    var startFrom = contentStart = contentEnd = 0;
    while(false !== (contentStart = strpos(str, startDelimiter, startFrom))) 
        contentStart += startDelimiterLength;
        contentEnd = strpos(str, endDelimiter, contentStart);
        if(false === contentEnd) 
        contents.push( str.substr(contentStart, contentEnd - contentStart) );
        startFrom = contentEnd + endDelimiterLength;

    return contents;

function strpos(haystack, needle, offset) 
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;

// Example usage
var string = "We want to extract all infos (essential ones) from within the brackets (this should be fun).";
var extracted = get_substrings_between(string, '(', ')');
// output: (2) ["essential ones", "this should be fun"]

Orginally from PHP by raina77ow, ported to Javascript.

Bootstrap 4 responsive tables won't take up 100% width

None of these answers are working (date today 9th Dec 2018). The correct resolution here is to add .table-responsive-sm to your table:

<table class='table table-responsive-sm'>
[Your table]

This applies the responsiveness aspect only to the SM view (mobile). So in mobile view you get the scrolling as desired and in larger views the table is not responsive and thus displayed full width, as desired.


PHP date add 5 year to current date

To add one year to todays date use the following:

$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));

How to Read from a Text File, Character by Character in C++

To quote Bjarne Stroustrup:"The >> operator is intended for formatted input; that is, reading objects of an expected type and format. Where this is not desirable and we want to read charactes as characters and then examine them, we use the get() functions."

char c;
while (input.get(c))
    // do something with c

How do you join on the same table, twice, in mysql?

you'd use another join, something along these lines:

SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 

FROM reviews AS rvw

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from


All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).

At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.

Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.

For more info about aliasing in SQL, read here. cannot open shared object file

sudo apt-get install zlib1g:i386 fixed the Gradle issue on Android 2.1.1 on Xubuntu 16.04.

CSS text-transform capitalize on all caps

I know this is a late response but if you want to compare the performance of various solutions I have a jsPerf that I created.

Regex solutions are the fastest for sure.

Here is the jsPerf:

There are 2 regex solutions.

The first one uses/\b[a-z]/g. Word boundary will capital words such as non-disclosure to Non-Disclosure.

If you only want to capitalize letters that are preceded by a space then use the second regex


What is the difference between i++ & ++i in a for loop?

Both of them increase the variable i by one. It's like saying i = i + 1. The difference is subtle. If you're using it in a loop like this, there's no difference:

for (int i = 0; i < 100; i++) {

for (int i = 0; i < 100; ++i) {

If you want to know the difference, look at this example:

int a = 0;
int b = a++; // b = 0; a = 1

a = 0;
b = ++a: // b = 1; a = 1

The idea is that ++a increments a and returns that value, while a++ returns a's value and then increments a.

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

I use both windows and linux, but the solution core.autocrlf true didn't help me. I even got nothing changed after git checkout <filename>.

So I use workaround to substitute git status -


git status | grep modified | cut -d' ' -f 4 | while read x; do
 x1="$(git show HEAD:$x | md5sum | cut -d' ' -f 1 )"
 x2="$(cat $x | md5sum | cut -d' ' -f 1 )"

 if [ "$x1" != "$x2" ]; then
    echo "$x NOT IDENTICAL"

I just compare md5sum of a file and its brother at repository.

Example output:

$ ./
application/script.php NOT IDENTICAL
application/storage/logs/laravel.log NOT IDENTICAL

Slide right to left?

I've done it this way:

var btn_width = btn.width();
btn.width(0);{width: btn_width}, {duration: 500});

Note, that node "btn" should be hidden before animation, and you might also need to set "position: absolute" to it.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

How to change the JDK for a Jenkins job?

Here is where you should configure in your job:

In JDK there is the combobox with the different JDK configured in your Jenkins. Job

Here is where you should configure in the config of your Jenkins:

Jenkins general config

connecting MySQL server to NetBeans

I just had the same issue with Netbeans 8.2 and trying to connect to mySQL server on a Mac OS machine. The only thing that worked for me was to add the following to the url of the connection string: &serverTimezone=UTC (or if you are connecting via Hibernate.cfg.xml then escape the & as &) Not surprisingly I found the solution on this stack overflow post also:

MySQL JDBC Driver 5.1.33 - Time Zone Issue

Best Regards, Claudio

Clear data in MySQL table with PHP?

Actually I believe the MySQL optimizer carries out a TRUNCATE when you DELETE all rows.

Invoking a static method using reflection

public class Add {
    static int add(int a, int b){
        return (a+b);

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

Determine which MySQL configuration file is being used

An alternative is to use

mysqladmin variables

How can I switch views programmatically in a view controller? (Xcode, iPhone)

This worked for me:

NSTimer *switchTo = [NSTimer scheduledTimerWithTimeInterval:0.1
           target:selfselector:@selector(switchToTimer)userInfo:nil repeats:NO];

- (void) switchToTimer {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil];
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"MyViewControllerID"]; // Storyboard ID
[self presentViewController:vc animated:FALSE completion:nil];

How do I get the day month and year from a Windows cmd.exe script?

Based on the great answers above, I would like to add this variation as a one-liner that simply assigns the year to the %year% environment variable:

for /f "skip=1 tokens=2 delims==" %%y in ('wmic PATH Win32_LocalTime GET Year /value') do set year=%%y

ICommand MVVM implementation

I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.


public class SampleViewModel: BaseViewModelStub
    public string Name { get; set; }

    public void HelloWorld()
        MessageBox.Show("Hello World!");

    public void Print()
        MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");

    public bool CanPrint()
        return !String.IsNullOrEmpty(Name);


UPDATE: now there seem to exist some libraries like that solve the problem of ICommand boilerplate code.

Colors in JavaScript console

Try this:

var funcNames = ["log", "warn", "error"];
var colors = ['color:green', 'color:orange', 'color:red'];

for (var i = 0; i < funcNames.length; i++) {
    let funcName = funcNames[i];
    let color = colors[i];
    let oldFunc = console[funcName];
    console[funcName] = function () {
        var args =;
        if (args.length) args = ['%c' + args[0]].concat(color, args.slice(1));
        oldFunc.apply(null, args);

now they all are as you wanted:

console.log("Log is green.");
console.warn("Warn is orange.");
console.error("Error is red.");

note: formatting like console.log("The number = %d", 123); is not broken.

Overriding fields or properties in subclasses

The example implementation when you want to have an abstract class with implementation. Subclasses must:

  1. Parameterize the implementation of an abstract class.
  2. Fully inherit the implementation of the abstract class;
  3. Have your own implementation.

In this case, the properties that are necessary for the implementation should not be available for use except for the abstract class and its own subclass.

    internal abstract class AbstractClass
        //Properties for parameterization from concrete class
        protected abstract string Param1 { get; }
        protected abstract string Param2 { get; }

        //Internal fields need for manage state of object
        private string var1;
        private string var2;

        internal AbstractClass(string _var1, string _var2)
            this.var1 = _var1;
            this.var2 = _var2;

        internal void CalcResult()
            //The result calculation uses Param1, Param2, var1, var2;

    internal class ConcreteClassFirst : AbstractClass
        private string param1;
        private string param2;
        protected override string Param1 { get { return param1; } }
        protected override string Param2 { get { return param2; } }

        public ConcreteClassFirst(string _var1, string _var2) : base(_var1, _var2) { }

        internal void CalcParams()
            //The calculation param1 and param2

    internal class ConcreteClassSecond : AbstractClass
        private string param1;
        private string param2;

        protected override string Param1 { get { return param1; } }

        protected override string Param2 { get { return param2; } }

        public ConcreteClassSecond(string _var1, string _var2) : base(_var1, _var2) { }

        internal void CalcParams()
            //The calculation param1 and param2

    static void Main(string[] args)
        string var1_1 = "val1_1";
        string var1_2 = "val1_2";

        ConcreteClassFirst concreteClassFirst = new ConcreteClassFirst(var1_1, var1_2);

        string var2_1 = "val2_1";
        string var2_2 = "val2_2";

        ConcreteClassSecond concreteClassSecond = new ConcreteClassSecond(var2_1, var2_2);

        //Param1 and Param2 are not visible in main method

Recreate the default website in IIS

Other answers are basically right, thanks to them I was able to restore my default web site, they're just missing some more or less important details.

This was the complete process to restore the Default Web Site in my case (IIS 7 on Windows 7 64bit):

  1. open IIS Manager
  2. right click Sites node under your machine in the Connections tree on the left side and click Add Website
  3. enter "Default Web Site" as a Site name
  4. set Application pool back to DefaultAppPool!
  5. set Physical path to %SystemDrive%\inetpub\wwwroot
  6. leave Binding and everything else as is

Possible issues:

  1. If the newly created web site cannot be started with the following message:

    Internet Information Services (IIS) Manager - The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)'s possible that port 80 is already assigned to another application (Skype in my case :). You can change the binding port to e.g. 8080 by right clicking Default Web Site and selecting Edit Bindings... and Edit.... See Error 0x80070020 when you try to start a Web site in IIS 7.0 for details. Or you can just close the application sitting on the port 80, of course.

  2. Some applications require Default Web Site to have the ID 1. In my case, it got ID 1 after recreation automatically. If it's not your case, see Re-create “default Website” in IIS after accidentally deleting. It's different for IIS 6 and 7.

Note: I had to recreate the Default Web Site, because I wasn't able to even open a project configured to run under IIS in Visual Studio. I had a solution with a couple of projects inside. One of the projects failed to load with the following error message:

The Web Application Project is configured to use IIS. The Web server 'http://localhost:8080/' could not be found.

After I have recreated the Default Web Site in IIS Manager, I was able to reload and open that specific project.

How to insert a blob into a database using sql server management studio

Ok... this took me way too long. The sql-management studio tool is just not up to simple things like this (which I've noticed before when looking for where to set the timeout on queries, and it was done in 4 different locations)

I downloaded some other sql editor package (sql maestro in my case). And behold it includes a blob editor where you can look at blobs, and load new blobs into these field.

thanks for the input!

Input from the keyboard in command line application

edit As of Swift 2.2 the standard library includes readLine. I'll also note Swift switched to markdown doc comments. Leaving my original answer for historical context.

Just for completeness, here is a Swift implementation of readln I've been using. It has an optional parameter to indicate the maximum number of bytes you want to read (which may or may not be the length of the String).

This also demonstrates the proper use of swiftdoc comments - Swift will generate a <project>.swiftdoc file and Xcode will use it.

///reads a line from standard input
///:param: max specifies the number of bytes to read
///:returns: the string, or nil if an error was encountered trying to read Stdin
public func readln(max:Int = 8192) -> String? {
    assert(max > 0, "max must be between 1 and Int.max")

    var buf:Array<CChar> = []
    var c = getchar()
    while c != EOF && c != 10 && buf.count < max {
        c = getchar()

    //always null terminate

    return buf.withUnsafeBufferPointer { String.fromCString($0.baseAddress) }

Css transition from display none to display block, navigation with subnav

You can do this with animation-keyframe rather than transition. Change your hover declaration and add the animation keyframe, you might also need to add browser prefixes for -moz- and -webkit-. See for more detailed info.

nav.main ul ul {_x000D_
    position: absolute;_x000D_
    list-style: none;_x000D_
    display: none;_x000D_
    opacity: 0;_x000D_
    visibility: hidden;_x000D_
    padding: 10px;_x000D_
    background-color: rgba(92, 91, 87, 0.9);_x000D_
    -webkit-transition: opacity 600ms, visibility 600ms;_x000D_
            transition: opacity 600ms, visibility 600ms;_x000D_
nav.main ul li:hover ul {_x000D_
    display: block;_x000D_
    visibility: visible;_x000D_
    opacity: 1;_x000D_
    animation: fade 1s;_x000D_
@keyframes fade {_x000D_
    0% {_x000D_
        opacity: 0;_x000D_
    100% {_x000D_
        opacity: 1;_x000D_
<nav class="main">_x000D_
            <a href="">Lorem</a>_x000D_
                <li><a href="">Ipsum</a></li>_x000D_
                <li><a href="">Dolor</a></li>_x000D_
                <li><a href="">Sit</a></li>_x000D_
                <li><a href="">Amet</a></li>_x000D_

Here is an update on your fiddle.

API vs. Webservice

API is code based integration while web service is message based integration with interoperable standards having a contract such as WSDL.

xml.LoadData - Data at the root level is invalid. Line 1, position 1

if we are using XDocument.Parse(@""). Use @ it resolves the issue.

belongs_to through associations

So you cant have the behavior that you want but you can do something that feels like it. You want to be able to do Choice.first.question

what I have done in the past is something like this

class Choice
  belongs_to :user
  belongs_to :answer
  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
  def question

this way the you can now call question on Choice

Programmatically scroll a UIScrollView

Here is another use case which worked well for me.

  1. User tap a button/cell.
  2. Scroll to a position just enough to make a target view visible.

Code: Swift 5.3

// Assuming you have a view named "targeView"
scrollView.scroll(to: CGPoint(x:targeView.frame.minX, y:targeView.frame.minY), animated: true)

As you can guess if you want to scroll to make a bottom part of your target view visible then use maxX and minY.

Ajax passing data to php script

You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {

In Python, how do I read the exif data for an image?

You can also use the ExifRead module:

import exifread
# Open image file for reading (binary mode)
f = open(path_name, 'rb')

# Return Exif tags
tags = exifread.process_file(f)

In oracle, how do I change my session to display UTF8?

Therefore, before starting '$ sqlplus' on OS, run the followings:

  • On Windows


  • On Unix (Solaris and Linux, centos etc)


It would also be advisable to set env variable in your '.bash_profile' [on start up script]

This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.

just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.

Accessing Google Account Id /username via Android

Retrieve profile information for a signed-in user Use the GoogleSignInResult.getSignInAccount method to request profile information for the currently signed in user. You can call the getSignInAccount method after the sign-in intent succeeds.

GoogleSignInResult result = 
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();

Remove all whitespace from C# string with regex

Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.

                       new string
                                    c => !char.IsWhiteSpace(c)


                       new string
                                    c => char.IsWhiteSpace(c) ? ' ' : c

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

There can be multiple reasons for the issue. One that worked for me on IIS 8.5 was as follow


  1. Type "turn windows features on or off" in search.
  2. Click on "Add Roles and features" in Server Manager.
  3. In Wizard scroll down to the Web server and select : Web Server -> Application Development. Select all except CGI from the list as shown in the screen shot

enter image description here

  1. Finally hit next and Install.
  2. Restart IIS

Your website may start working.

How can I sort one set of data to match another set of data in Excel?

You can use VLOOKUP.

Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:

=VLOOKUP(A2, Sheet2!A:B, 2, 0)

This will return you #N/A if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.

Check if a value is in an array (C#)

Not very clear what your issue is, but it sounds like you want something like this:

    List<string> printer = new List<string>( new [] { "jupiter", "neptune", "pangea", "mercury", "sonic" } );

    if( printer.Exists( p => p.Equals( "jupiter" ) ) )

How do I run pip on python for windows?

First go to the pip documentation if not install before:

and follow the install pip which is first download from

Then run the following (which may require administrator access): python

How do I compare strings in GoLang?

For the Platform Independent Users or Windows users, what you can do is:

import runtime:

import (

and then trim the string like this:

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")

now you can compare it like that:

if strings.Compare(input, "a") == 0 {

This is a better approach when you're making use of STDIN on multiple platforms.


This happens because on windows lines end with "\r\n" which is known as CRLF, but on UNIX lines end with "\n" which is known as LF and that's why we trim "\n" on unix based operating systems while we trim "\r\n" on windows.

Set a button group's width to 100% and make buttons equal width?

There's no need for extra css the .btn-group-justified class does this.

You have to add this to the parent element and then wrap each btn element in a div with .btn-group like this

    <div class="form-group">

            <div class="btn-group btn-group-justified">
                <div class="btn-group">
                    <button type="submit" id="like" class="btn btn-lg btn-success ">Like</button>
                <div class="btn-group">
                    <button type="submit" id="nope" class="btn btn-lg btn-danger ">Nope</button>


How to identify object types in java

You can compare class tokens to each other, so you could use value.getClass() == Integer.class. However, the simpler and more canonical way is to use instanceof :

    if (value instanceof Integer) {
        System.out.println("This is an Integer");
    } else if(value instanceof String) {
        System.out.println("This is a String");
    } else if(value instanceof Float) {
        System.out.println("This is a Float");


  • the only difference between the two is that comparing class tokens detects exact matches only, while instanceof C matches for subclasses of C too. However, in this case all the classes listed are final, so they have no subclasses. Thus instanceof is probably fine here.
  • as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.

    System.out.println("This is a(n) " + value.getClass().getSimpleName());

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

This can also occur if you do something stupid (like I did) and place the api url in the "Project Url" (e.g. http://localhost:59088/api/Product) on the Project Properties->Web tab instead of specifying it in the "Specific Page" text box. This causes Visual Studio to go ahead and create an APP called ProjectName/api/Product, and this will expect a default page. The only way to undo this is to go to C:\Program Files (x86)\IIS Express and use appcmd.exe to delete it like so

>.\appcmd.exe delete APP "ProjectName/api/Product"

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.


Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.


Works for me.

How to center an image horizontally and align it to the bottom of the container?

This is tricky; the reason it's failing is that you can't position via margin or text-align while absolutely positioned.

If the image is alone in the div, then I recommend something like this:

.image_block {
    width: 175px;
    height: 175px;
    line-height: 175px;
    text-align: center;
    vertical-align: bottom;

You may need to stick the vertical-align call on the image instead; not really sure without testing it. Using vertical-align and line-height is going to treat you a lot better, though, than trying to mess around with absolute positioning.

Convert LocalDateTime to LocalDateTime in UTC

public static String convertFromGmtToLocal(String gmtDtStr, String dtFormat, TimeZone lclTimeZone) throws Exception{
        if (gmtDtStr == null || gmtDtStr.trim().equals("")) return null;
        SimpleDateFormat format = new SimpleDateFormat(dtFormat);
        Date dt = format.parse(gmtDtStr);

format.format(dt); }

What is the difference between Tomcat, JBoss and Glassfish?

Apache tomcat is just an only serverlet container it does not support for Enterprise Java application(JEE). JBoss and Glassfish are supporting for JEE application but Glassfish much heavy than JBOSS server : Reference Slide

Cannot find reference 'xxx' in - Python / Pycharm

Make sure you didn't by mistake changed the file type of files. If, for example, you changed their type to "Text" (instead of "Python"), PyCharm won't analyze the file for Python code. In that case, you may notice that the file icon for files is different from other Python files.

To fix, in Settings > Editor > File Types, in the "Recognized File Types" list click on "Text" and in the "File name patterns" list remove

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit

if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte

when in doubt, use VARCHAR2(1 CHAR)

same thing answered here Difference between BYTE and CHAR in column datatypes

Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB

in Oracle, don't use VARCHAR

for each loop in Objective-C for accessing NSMutable dictionary

You can use -[NSDictionary allKeys] to access all the keys and loop through it.

how can get index & count in vuejs

you can just add 1

<li v-for="(catalog, itemObjKey) in catalogs">this index : {{itemObjKey + 1}}</li>

to get the length of an array/objects

{{ catalogs.length }}

How to find the cumulative sum of numbers in a list?

Somewhat hacky, but seems to work:

def cumulative_sum(l):
  y = [0]
  def inc(n):
    y[0] += n
    return y[0]
  return [inc(x) for x in l]

I did think that the inner function would be able to modify the y declared in the outer lexical scope, but that didn't work, so we play some nasty hacks with structure modification instead. It is probably more elegant to use a generator.

Find most frequent value in SQL column

One way I like to use is:

select ,COUNT()as VAR1 from Table_Name

group by

order by VAR1 desc

limit 1

rand() between 0 and 1

In my case (I'm using VS 2017) works fine the following simple code:

#include "pch.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

int main()

    for (int i = 1000; i > 0; i--) //try it thousand times
        int randnum = (double)rand() / ((double)RAND_MAX + 1);
        std::cout << " rnum: " << rand()%2 ;

How to recover a dropped stash in Git?

To see the commits in terminal, only filtering the ones we care about we can use:

git log --oneline --all --grep="^WIP on .*: [a-f0-9]\+" --grep="^On [^ ]*:" $( env LANG=C git fsck --no-reflog | awk '/dangling commit/ {print $3}' )

This is based on Aristotle Pagaltzis answer.

Convert String to Calendar Object in Java

No new Calendar needs to be created, SimpleDateFormat already uses a Calendar underneath.

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US);
Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Calendar cal = sdf.getCalendar();

(I can't comment yet, that's why I created a new answer)

Generate .pem file used to set up Apple Push Notifications

Apple have changed the name of the certificate that is issued. You can now use the same certificate for both development and production. While you can still request a development only certificate you can no longer request a production only certificate.

please see below screnshot

Angular2 module has no exported member

You do not need the line:

import { SigninComponent, RegisterComponent } from './auth/auth.module';

in your app.component.ts as you already included the AuthModule in your app.module.ts. AutModule import is sufficient to use your component in the app.

The error that you get is a TypeScript error, not a Angular one, and it is correct in stating that there is no exported member, as it searches for a valid EC6 syntax for export, not angular module export. This line would thus work in your app.component.ts:

import { SigninComponent } from './auth/components/signin.component';

python ValueError: invalid literal for float()

I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.

In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.

I was getting the error:

> '     0.00'
> 3 0 fast loop, delta =  10.0 weight =  0.0 
> '     0.00'
> 1 800 fast loop, delta = 10.0 weight =  0.0 
> '     0.00'
> 6 0 fast loop, delta =  10.0 weight =  0.0
> '     0\x00.0' 
> Traceback (most recent call last):
>   File "", line 172, in start
>     valueScale = float(answer_string) 
>     ValueError: invalid literal for float(): 0

After some research I wrote few lines of code that work in my case.

replyScale =
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
valueScale = float(answer_strip)

The answers in these posts helped:

  1. How to get rid of \x00 in my array of bytes?
  2. Invalid literal for float(): 0.000001, how to fix error?

#1071 - Specified key was too long; max key length is 767 bytes

My fix to this very same issue was to add an option as a 3rd argument: charset

  { /*... columns*/ },
  { charset: 'utf8' } 

Otherwise sequelize would create tables as utf8mb4.

How to use Fiddler to monitor WCF service

This is straightforward if you have control over the client that is sending the communications. All you need to do is set the HttpProxy on the client-side service class.

I did this, for example, to trace a web service client running on a smartphone. I set the proxy on that client-side connection to the IP/port of Fiddler, which was running on a PC on the network. The smartphone app then sent all of its outgoing communication to the web service, through Fiddler.

This worked perfectly.

If your client is a WCF client, then see this Q&A for how to set the proxy.

Even if you don't have the ability to modify the code of the client-side app, you may be able to set the proxy administratively, depending on the webservices stack your client uses.

Laravel 4: how to "order by" using Eloquent ORM

This is how I would go about it.

$posts = $this->post->orderBy('id', 'DESC')->get();

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

How to use forEach in vueJs?

The keyword you need is flatten an array. Modern javascript array comes with a flat method. You can use third party libraries like underscorejs in case you need to support older browsers.

Native Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=response.flat(); //data=[1,2,3,4,12,15,20,21]

Underscore Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=_.flatten(response);

regex to remove all text before a character

Variant of Tim's one, good only on some implementations of Regex: ^.*?_

var subjectString = "3.04_somename.jpg";
var resultString = Regex.Replace(subjectString,
    @"^   # Match start of string
    .*?   # Lazily match any character, trying to stop when the next condition becomes true
    _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);

JavaFX Application Icon

Full program for starters :) This program sets icon for StackOverflowIcon.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class StackoverflowIcon extends Application {

    public void start(Stage stage) {
        StackPane root = new StackPane();
        // set icon
        stage.getIcons().add(new Image("/path/to/stackoverflow.jpg"));
        stage.setTitle("Wow!! Stackoverflow Icon");
        stage.setScene(new Scene(root, 300, 250));;

    public static void main(String[] args) {

Output Screnshot

JavaFX Screenshot

Updated for JavaFX 8

No need to change the code. It still works fine. Tested and verified in Java 1.8(1.8.0_45). Path can be set to local or remote both are supported.

stage.getIcons().add(new Image("/path/to/javaicon.png"));


stage.getIcons().add(new Image(""));

enter image description here

Hope it helps. Thanks!!

rotate image with css

The trouble looks like the image isn't square and the browser adjusts as such. After rotation ensure the dimensions are retained by changing the image margin.

.imagetest img {
  transform: rotate(270deg);
  margin: 10px 0px;

The amount will depend on the difference in height x width of the image. You may also need to add display:inline-block; or display:block to get it to recognize the margin parameter.

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference.

Another great site to help you get started is

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!


Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
End Sub

phpMyAdmin allow remote users

The other answers so far seem to advocate the complete replacement of the <Directory/> block, this is not needed and may remove extra settings like the 'AddDefaultCharset UTF-8' now included.

To allow remote access you need to add 1 line to the 2.4 config block or change 2 lines in the 2.2 (depending on your apache version):

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
       #ADD following line:
       Require all granted
       Require ip
       Require ip ::1
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     #CHANGE following 2 lines:
     Order Allow,Deny
     Allow from All
     Allow from
     Allow from ::1

Connecting to TCP Socket from browser using javascript

As for your problem, currently you will have to depend on XHR or websockets for this.

Currently no popular browser has implemented any such raw sockets api for javascript that lets you create and access raw sockets, but a draft for the implementation of raw sockets api in JavaScript is under-way. Have a look at these links:

Chrome now has support for raw TCP and UDP sockets in its ‘experimental’ APIs. These features are only available for extensions and, although documented, are hidden for the moment. Having said that, some developers are already creating interesting projects using it, such as this IRC client.

To access this API, you’ll need to enable the experimental flag in your extension’s manifest. Using sockets is pretty straightforward, for example:

chrome.experimental.socket.create('tcp', '', 8080, function(socketInfo) {
  chrome.experimental.socket.connect(socketInfo.socketId, function (result) {
        chrome.experimental.socket.write(socketInfo.socketId, "Hello, world!");         

How can I post an array of string to ASP.NET MVC Controller without a form?

Don't post the data as an array. To bind to a list, the key/value pairs should be submitted with the same value for each key.

You should not need a form to do this. You just need a list of key/value pairs, which you can include in the call to $.post.

Assigning default value while creating migration file

Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":

class AddColumnToWidgets < ActiveRecord::Migration
  def change
    add_column :widgets, :colour, :string, default: 'red'

This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.

How to append one DataTable to another DataTable

The datatype in the same columns name must be equals.


After that the result is:

dataTable1 = dataTable1 + dataTable2

Set value for particular cell in pandas DataFrame using index

To set values, use:[0, 'clm1'] = 0
  • The fastest recommended method for setting variables.
  • set_value, ix have been deprecated.
  • No warning, unlike iloc and loc

Mongoose: Get full list of users

My Solution

        .then(users => {
            const response = {
                count: users.length,
                users: => {

                    return {
                        _id: user._id,
                        // other property


        }).catch(err => {
            success: false

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

For individual element the code below could be used:

private boolean isElementPresent(By by) {
        try {
            return true;
        } catch (NoSuchElementException e) {
            return false;
for (int second = 0;; second++) {
            if (second >= 60){
            try {
                if (isElementPresent("someid"))){
            catch (Exception e) {


Tools for making latex tables in R

The stargazer package is another good option. It supports objects from many commonly used functions and packages (lm, glm, svyreg, survival, pscl, AER), as well as from zelig. In addition to regression tables, it can also output summary statistics for data frames, or directly output the content of data frames.

AWS ssh access 'Permission denied (publickey)' issue

For Ubuntu instances:

chmod 600 ec2-keypair.pem
ssh -v -i ec2-keypair.pem [email protected]

For other instances, you might have to use ec2-user instead of ubuntu.

Most EC2 Linux images I've used only have the root user created by default.

See also:

Call a VBA Function into a Sub Procedure

Procedures in a Module start being useful and generic when you pass in arguments.

For example:

Public Function DoSomethingElse(strMessage As String)  
    MsgBox strMessage
End Function

Can now display any message that is passed in with the string variable called strMessage.

How to set DateTime to null

DateTime is a non-nullable value type

DateTime? newdate = null;

You can use a Nullable<DateTime>

c# Nullable Datetime

string.split - by multiple character delimiter

string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);

SSL certificate is not trusted - on mobile only

Put your domain name here: You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.

Gerrit error when Change-Id in commit messages are missing

under my .git/hooks folder, some sample files were missing. like commit-msg,post-commit.sample,post-update.sample...adding these files resolved my change id missing issue.

CSS background opacity with rgba not working in IE 8

To use rgba background in IE there is a fallback.

We have to use filter property. that uses ARGB

    zoom: 1;

this is fallback for rgba(255, 255, 255, 0.2)

Change #33ffffff according to yours.

How to calculate ARGB for RGBA

How to Install gcc 5.3 with yum on CentOS 7.2?

The best approach to use yum and update your devtoolset is to utilize the CentOS SCLo RH Testing repository.

yum install centos-release-scl-rh
yum --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc devtoolset-7-gcc-c++

Many additional packages are also available, to see them all

yum --enablerepo=centos-sclo-rh-testing list devtoolset-7*

You can use this method to install any dev tool version, just swap the 7 for your desired version. devtoolset-6-gcc, devtoolset-5-gcc etc.

Best way to store a key=>value array in JavaScript?

Simply do this

var key = "keyOne";
var obj = {};
obj[key] = someValue;

Array.sort() doesn't sort numbers correctly

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:




Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.

Split string in Lua?

Just as string.gmatch will find patterns in a string, this function will find the things between patterns:

function string:split(pat)
  pat = pat or '%s+'
  local st, g = 1, self:gmatch("()("..pat..")")
  local function getter(segs, seps, sep, cap1, ...)
    st = sep and seps + #sep
    return self:sub(segs, (seps or 0) - 1), cap1 or sep, ...
  return function() if st then return getter(st, g()) end end

By default it returns whatever is separated by whitespace.

Check if XML Element exists


Should do it (where doc is your XmlDocument object, obviously)

Alternatively you could use an XSD and validate against that

WPF C# button style

<!--Customize button -->

<LinearGradientBrush x:Key="Buttongradient" StartPoint="0.500023,0.999996" EndPoint="0.500023,4.37507e-006">
    <GradientStop Color="#5e5e5e" Offset="1" />
    <GradientStop Color="#0b0b0b" Offset="0" />

<Style x:Key="hhh" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{DynamicResource Buttongradient}"/>
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />
    <Setter Property="Template">
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="0.5">
                        <DropShadowEffect ShadowDepth="0" BlurRadius="2"></DropShadowEffect>


                        <Path Width="9" Height="16.5" Stretch="Fill" Fill="#000"  HorizontalAlignment="Left" Margin="16.5,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z " Opacity="0.2">

                        <Path x:Name="PathIcon" Width="8" Height="15"  Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z ">
                                <DropShadowEffect ShadowDepth="0" BlurRadius="5"></DropShadowEffect>

                        <Line  HorizontalAlignment="Left" Margin="40,0,0,0" Name="line4" Stroke="Black" VerticalAlignment="Top" Width="2" Y1="0" Y2="640" Opacity="0.5" />
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />

                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />

Read a zipped file as a pandas DataFrame

I think you want to open the ZipFile, which returns a file-like object, rather than read:

In [11]: crime2013 = pd.read_csv('crime_incidents_2013_CSV.csv'))

In [12]: crime2013
<class 'pandas.core.frame.DataFrame'>
Int64Index: 24567 entries, 0 to 24566
Data columns (total 15 columns):
CCN                            24567  non-null values
REPORTDATETIME                 24567  non-null values
SHIFT                          24567  non-null values
OFFENSE                        24567  non-null values
METHOD                         24567  non-null values
LASTMODIFIEDDATE               24567  non-null values
BLOCKSITEADDRESS               24567  non-null values
BLOCKXCOORD                    24567  non-null values
BLOCKYCOORD                    24567  non-null values
WARD                           24563  non-null values
ANC                            24567  non-null values
DISTRICT                       24567  non-null values
PSA                            24567  non-null values
NEIGHBORHOODCLUSTER            24263  non-null values
dtypes: float64(4), int64(1), object(10)

Configuration with name 'default' not found. Android Studio

If you're getting this error with react native, it may be due to a link to an NPM package that you removed (as it was in my case). After removing references to it in the settings.gradle and build.gradle files, I cleaned and rebuilt and it's as good as new :)

Date ticks and rotation in matplotlib

Solution works for matplotlib 2.1+

There exists an axes method tick_params that can change tick properties. It also exists as an axis method as set_tick_params

ax.tick_params(axis='x', rotation=45)



As a side note, the current solution mixes the stateful interface (using pyplot) with the object-oriented interface by using the command plt.xticks(rotation=70). Since the code in the question uses the object-oriented approach, it's best to stick to that approach throughout. The solution does give a good explicit solution with plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )