Programs & Examples On #Quotes

Computer programming languages' facility for embedding text in source code, also known as String literals

How to select between brackets (or quotes or ...) in Vim?

To select between the single quotes I usually do a vi' ("select inner single quotes").

Inside a parenthesis block, I use vib ("select inner block")

Inside a curly braces block you can use viB ("capital B")

To make the selections "inclusive" (select also the quotes, parenthesis or braces) you can use a instead of i.

You can read more about the Text object selections on the manual, or :help text-objects within vim.

Escaping Strings in JavaScript

A variation of the function provided by Paolo Bergantino that works directly on String:

String.prototype.addSlashes = function() 
{ 
   //no need to do (str+'') anymore because 'this' can only be a string
   return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} 

By adding the code above in your library you will be able to do:

var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());

EDIT:

Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:

if(!String.prototype.addSlashes)
{
   String.prototype.addSlashes = function()... 
}
else
   alert("Warning: String.addSlashes has already been declared elsewhere.");

How to enter quotes in a Java string?

In Java, you can escape quotes with \:

String value = " \"ROM\" ";

How to use an environment variable inside a quoted string in Bash

Note that COLUMNS is:

  1. NOT an environment variable. It is an ordinary bash parameter that is set by bash itself.
  2. Set automatically upon receipt of a SIGWINCH signal.

That second point usually means that your COLUMNS variable will only be set in your interactive shell, not in a bash script.

If your script's stdin is connected to your terminal you can manually look up the width of your terminal by asking your terminal:

tput cols

And to use this in your SVN command:

svn diff "$@" --diff-cmd /usr/bin/diff -x "-y -w -p -W $(tput cols)"

(Note: you should quote "$@" and stay away from eval ;-))

Difference between single and double quotes in Bash

Since this is the de facto answer when dealing with quotes in bash, I'll add upon one more point missed in the answers above, when dealing with the arithmetic operators in the shell.

The bash shell supports two ways do arithmetic operation, one defined by the built-in let command and the $((..)) operator. The former evaluates an arithmetic expression while the latter is more of a compound statement.

It is important to understand that the arithmetic expression used with let undergoes word-splitting, pathname expansion just like any other shell commands. So proper quoting and escaping needs to be done.

See this example when using let

let 'foo = 2 + 1'
echo $foo
3

Using single quotes here is absolutely fine here, as there is no need for variable expansions here, consider a case of

bar=1
let 'foo = $bar + 1'

would fail miserably, as the $bar under single quotes would not expand and needs to be double-quoted as

let 'foo = '"$bar"' + 1'

This should be one of the reasons, the $((..)) should always be considered over using let. Because inside it, the contents aren't subject to word-splitting. The previous example using let can be simply written as

(( bar=1, foo = bar + 1 ))

Always remember to use $((..)) without single quotes

Though the $((..)) can be used with double-quotes, there is no purpose to it as the result of it cannot contain a content that would need the double-quote. Just ensure it is not single quoted.

printf '%d\n' '$((1+1))'
-bash: printf: $((1+1)): invalid number
printf '%d\n' $((1+1))
2
printf '%d\n' "$((1+1))"
2

May be in some special cases of using the $((..)) operator inside a single quoted string, you need to interpolate quotes in a way that the operator either is left unquoted or under double quotes. E.g. consider a case, when you are tying to use the operator inside a curl statement to pass a counter every time a request is made, do

curl http://myurl.com --data-binary '{"requestCounter":'"$((reqcnt++))"'}'

Notice the use of nested double-quotes inside, without which the literal string $((reqcnt++)) is passed to requestCounter field.

Python "string_escape" vs "unicode_escape"

According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.

They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

How to execute a bash command stored as a string with quotes and asterisk

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd

How to Insert Double or Single Quotes

To Create New Quoted Values from Unquoted Values

  • Column A contains the names.
  • Put the following formula into Column B = """" & A1 & """"
  • Copy Column B and Paste Special -> Values

Using a Custom Function

Public Function Enquote(cell As Range, Optional quoteCharacter As String = """") As Variant
    Enquote = quoteCharacter & cell.value & quoteCharacter
End Function

=OfficePersonal.xls!Enquote(A1)

=OfficePersonal.xls!Enquote(A1, "'")

To get permanent quoted strings, you will have to copy formula values and paste-special-values.

How can I escape a double quote inside double quotes?

Add "\" before double quote to escape it, instead of \

#! /bin/csh -f

set dbtable = balabala

set dbload = "load data local infile "\""'gfpoint.csv'"\"" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"\""' LINES TERMINATED BY "\""'\n'"\"" IGNORE 1 LINES"

echo $dbload
# load data local infile "'gfpoint.csv'" into table balabala FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "''" IGNORE 1 LINES

How do you replace double quotes with a blank space in Java?

Use String#replace().

To replace them with spaces (as per your question title):

System.out.println("I don't like these \"double\" quotes".replace("\"", " "));

The above can also be done with characters:

System.out.println("I don't like these \"double\" quotes".replace('"', ' '));

To remove them (as per your example):

System.out.println("I don't like these \"double\" quotes".replace("\"", ""));

How to escape double quotes in a title attribute

Here's a snippet of the HTML escape characters taken from a cached page on archive.org:

&#060   |   <   less than sign
&#064   |   @   at sign
&#093   |   ]   right bracket
&#123   |   {   left curly brace
&#125   |   }   right curly brace
&#133   |   …   ellipsis
&#135   |   ‡   double dagger
&#146   |   ’   right single quote
&#148   |   ”   right double quote
&#150   |   –   short dash
&#153   |   ™   trademark
&#162   |   ¢   cent sign
&#165   |   ¥   yen sign
&#169   |   ©   copyright sign
&#172   |   ¬   logical not sign
&#176   |   °   degree sign
&#178   |   ²   superscript 2
&#185   |   ¹   superscript 1
&#188   |   ¼   fraction 1/4
&#190   |   ¾   fraction 3/4
&#247   |   ÷   division sign
&#8221  |   ”   right double quote
&#062   |   >   greater than sign
&#091   |   [   left bracket
&#096   |   `   back apostrophe
&#124   |   |   vertical bar
&#126   |   ~   tilde
&#134   |   †   dagger
&#145   |   ‘   left single quote
&#147   |   “   left double quote
&#149   |   •   bullet
&#151   |   —   longer dash
&#161   |   ¡   inverted exclamation point
&#163   |   £   pound sign
&#166   |   ¦   broken vertical bar
&#171   |   «   double left than sign
&#174   |   ®   registered trademark sign
&#177   |   ±   plus or minus sign
&#179   |   ³   superscript 3
&#187   |   »   double greater-than sign
&#189   |   ½   fraction 1/2
&#191   |   ¿   inverted question mark
&#8220  |   “   left double quote
&#8212  |   —   dash

Regex for quoted string with escaping quotes

This one comes from nanorc.sample available in many linux distros. It is used for syntax highlighting of C style strings

\"(\\.|[^\"])*\"

Convert XmlDocument to String

" is shown as \" in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.

What is the difference between single and double quotes in SQL?

A simple rule for us to remember what to use in which case:

  • [S]ingle quotes are for [S]trings ; [D]ouble quotes are for [D]atabase identifiers;

In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. You can use " when your SQL_MODE has ANSI_QUOTES enabled.

How to escape single quotes in MySQL

If you want to keep (') apostrophe in the database use this below code:

$new_value = str_replace("'","\'", $value); 

$new_value can store in database.

Escape quotes in JavaScript

You can copy those two functions (listed below), and use them to escape/unescape all quotes and special characters. You don't have to use jQuery or any other library for this.

function escape(s) {
    return ('' + s)
        .replace(/\\/g, '\\\\')
        .replace(/\t/g, '\\t')
        .replace(/\n/g, '\\n')
        .replace(/\u00A0/g, '\\u00A0')
        .replace(/&/g, '\\x26')
        .replace(/'/g, '\\x27')
        .replace(/"/g, '\\x22')
        .replace(/</g, '\\x3C')
        .replace(/>/g, '\\x3E');
}

function unescape(s) {
    s = ('' + s)
       .replace(/\\x3E/g, '>')
       .replace(/\\x3C/g, '<')
       .replace(/\\x22/g, '"')
       .replace(/\\x27/g, "'")
       .replace(/\\x26/g, '&')
       .replace(/\\u00A0/g, '\u00A0')
       .replace(/\\n/g, '\n')
       .replace(/\\t/g, '\t');

    return s.replace(/\\\\/g, '\\');
}

Remove quotes from a character vector in R

nump function :)

> nump <- function(x) print(formatC(x, format="fg", big.mark=","), quote=FALSE)

correct answer:

x <- 1234567890123456

> nump(x)

[1] 1,234,567,890,123,456 

How to insert text with single quotation sql server 2005

The answer really depends on how you are doing the INSERT.

If you are specifying a SQL literal then you need to use the double-tick approach:

-- Direct insert
INSERT INTO Table1 (Column1) VALUES ('John''s')

-- Using a parameter, with a direct insert
DECLARE @Value varchar(50)
SET @Value = 'John''s'
INSERT INTO Table1 (Column1) VALUES (@Value)

-- Using a parameter, with dynamic SQL
DECLARE @Value varchar(50)
SET @Value = 'John''s'
EXEC sp_executesql 'INSERT INTO Table1 (Column1) VALUES (@p1)', '@p1 varchar(50)', @Value

If you are doing the INSERT from code, use parameters:

// Sample ADO.NET
using (SqlConnection conn = new SqlConnection(connectionString)) {
    conn.Open();
    using (SqlCommand command = conn.CreateCommand()) {
        command.CommandText = "INSERT INTO Table1 (Column1) VALUES (@Value)";

        command.Parameters.AddWithValue("@Value", "John's");

        command.ExecuteNonQuery();
    }
}

If your data contains user-input, direct or indirect, USE PARAMETERS. Parameters protect against SQL Injection attacks. Never ever build up dynamic SQL with user-input.

How to output MySQL query results in CSV format?

Alternatively to the answer above, you can have a MySQL table that uses the CSV engine.

Then you will have a file on your hard disk that will always be in a CSV format which you could just copy without processing it.

When to use single quotes, double quotes, and backticks in MySQL

The string literals in MySQL and PHP are the same.

A string is a sequence of bytes or characters, enclosed within either single quote (“'”) or double quote (“"”) characters.

So if your string contains single quotes, then you could use double quotes to quote the string, or if it contains double quotes, then you could use single quotes to quote the string. But if your string contains both single quotes and double quotes, you need to escape the one that used to quote the string.

Mostly, we use single quotes for an SQL string value, so we need to use double quotes for a PHP string.

$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, 'val1', 'val2')";

And you could use a variable in PHP's double-quoted string:

$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, '$val1', '$val2')";

But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

Why shouldn't `&apos;` be used to escape single quotes?

&quot; is valid in both HTML5 and HTML4.

&apos; is valid in HTML5, but not HTML4. However, most browsers support &apos; for HTML4 anyway.

Escaping Double Quotes in Batch Script

For example for Unreal engine Automation tool run from batch file - this worked for me

eg: -cmdline=" -Messaging" -device=device -addcmdline="-SessionId=session -SessionOwner='owner' -SessionName='Build' -dataProviderMode=local -LogCmds='LogCommodity OFF' -execcmds='automation list; runtests tests+separated+by+T1+T2; quit' " -run

Hope this helps someone, worked for me.

Regex to split a CSV

Aaaand another answer here. :) Since I couldn't make the others quite work.

My solution both handles escaped quotes (double occurrences), and it does not include delimiters in the match.

Note that I have been matching against ' instead of " as that was my scenario, but simply replace them in the pattern for the same effect.

Here goes (remember to use the "ignore whitespace" flag /x if you use the commented version below) :

# Only include if previous char was start of string or delimiter
(?<=^|,)
(?:
  # 1st option: empty quoted string (,'',)
  '{2}
  |
  # 2nd option: nothing (,,)
  (?:)
  |
  # 3rd option: all but quoted strings (,123,)
  # (included linebreaks to allow multiline matching)
  [^,'\r\n]+
  |
  # 4th option: quoted strings (,'123''321',)
  # start pling
  ' 
    (?:
      # double quote
      '{2}
      |
      # or anything but quotes
      [^']+
    # at least one occurance - greedy
    )+
  # end pling
  '
)
# Only include if next char is delimiter or end of string
(?=,|$)

Single line version:

(?<=^|,)(?:'{2}|(?:)|[^,'\r\n]+|'(?:'{2}|[^']+)+')(?=,|$)

Regular expression visualization (if it works, debux has issues right now it seems - else follow the next link)

Debuggex Demo

regex101 example

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

Expansion of variables inside single quotes in a command in Bash

The repo command can't care what kind of quotes it gets. If you need parameter expansion, use double quotes. If that means you wind up having to backslash a lot of stuff, use single quotes for most of it, and then break out of them and go into doubles for the part where you need the expansion to happen.

repo forall -c 'literal stuff goes here; '"stuff with $parameters here"' more literal stuff'

Explanation follows, if you're interested.

When you run a command from the shell, what that command receives as arguments is an array of null-terminated strings. Those strings may contain absolutely any non-null character.

But when the shell is building that array of strings from a command line, it interprets some characters specially; this is designed to make commands easier (indeed, possible) to type. For instance, spaces normally indicate the boundary between strings in the array; for that reason, the individual arguments are sometimes called "words". But an argument may nonetheless have spaces in it; you just need some way to tell the shell that's what you want.

You can use a backslash in front of any character (including space, or another backslash) to tell the shell to treat that character literally. But while you can do something like this:

echo \”That\'ll\ be\ \$4.96,\ please,\"\ said\ the\ cashier

...it can get tiresome. So the shell offers an alternative: quotation marks. These come in two main varieties.

Double-quotation marks are called "grouping quotes". They prevent wildcards and aliases from being expanded, but mostly they're for including spaces in a word. Other things like parameter and command expansion (the sorts of thing signaled by a $) still happen. And of course if you want a literal double-quote inside double-quotes, you have to backslash it:

echo "\"That'll be \$4.96, please,\" said the cashier"

Single-quotation marks are more draconian. Everything between them is taken completely literally, including backslashes. There is absolutely no way to get a literal single quote inside single quotes.

Fortunately, quotation marks in the shell are not word delimiters; by themselves, they don't terminate a word. You can go in and out of quotes, including between different types of quotes, within the same word to get the desired result:

echo '"That'\''ll be $4.96, please," said the cashier'

So that's easier - a lot fewer backslashes, although the close-single-quote, backslashed-literal-single-quote, open-single-quote sequence takes some getting used to.

Modern shells have added another quoting style not specified by the POSIX standard, in which the leading single quotation mark is prefixed with a dollar sign. Strings so quoted follow similar conventions to string literals in the ANSI standard version of the C programming language, and are therefore sometimes called "ANSI strings" and the $'...' pair "ANSI quotes". Within such strings, the above advice about backslashes being taken literally no longer applies. Instead, they become special again - not only can you include a literal single quotation mark or backslash by prepending a backslash to it, but the shell also expands the ANSI C character escapes (like \n for a newline, \t for tab, and \xHH for the character with hexadecimal code HH). Otherwise, however, they behave as single-quoted strings: no parameter or command substitution takes place:

echo $'"That\'ll be $4.96, please," said the cashier'

The important thing to note is that the single string received as the argument to the echo command is exactly the same in all of these examples. After the shell is done parsing a command line, there is no way for the command being run to tell what was quoted how. Even if it wanted to.

Removing double quotes from variables in batch file creates problems with CMD environment

The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files

SET xyz=%~1

Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).

But, This simple tilde syntax will not work for other variables that were not passed in as parameters

For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.

@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%

If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows

@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%

How to run an EXE file in PowerShell with parameters with spaces and quotes

I had spaces in both command and parameters, and this is what worked for me:

$Command = "E:\X64\Xendesktop Setup\XenDesktopServerSetup.exe"
$Parms = "/COMPONENTS CONTROLLER,DESKTOPSTUDIO,DESKTOPDIRECTOR,LICENSESERVER,STOREFRONT /PASSIVE /NOREBOOT /CONFIGURE_FIREWALL /NOSQL"

$Prms = $Parms.Split(" ")
& "$Command" $Prms

It's basically the same as Akira's answer, but this works if you dynamically build your command parameters and put them in a variable.

How to plot two columns of a pandas data frame using points?

You can specify the style of the plotted line when calling df.plot:

df.plot(x='col_name_1', y='col_name_2', style='o')

The style argument can also be a dict or list, e.g.:

import numpy as np
import pandas as pd

d = {'one' : np.random.rand(10),
     'two' : np.random.rand(10)}

df = pd.DataFrame(d)

df.plot(style=['o','rx'])

All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot.

Output

Cannot access wamp server on local network

Wamp server share in local network

Reference Link: http://forum.aminfocraft.com/blog/view/141/wamp-server-share-in-local-netword

Edit your Apache httpd.conf:

Options FollowSymLinks
AllowOverride None
Order deny,allow
Allow from all
#Deny from all

and

#onlineoffline tag - don't remove
Order Deny,Allow
Allow from all
#Deny from all

to share mysql server:

edit wamp/alias/phpmyadmin.conf

<Directory "E:/wamp/apps/phpmyadmin3.2.0.1/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
    Order Deny,Allow
    #Deny from all
    Allow from all


Alternating Row Colors in Bootstrap 3 - No Table

Since you are using bootstrap and you want alternating row colors for every screen sizes you need to write separate style rules for all the screen sizes.

/* For small screen */
.row :nth-child(even){
  background-color: #dcdcdc;
}
.row :nth-child(odd){
  background-color: #aaaaaa;
}

/* For medium screen */    
@media (min-width: 768px) {
    .row :nth-child(4n), .row :nth-child(4n-1) {
        background: #dcdcdc;
    }
    .row :nth-child(4n-2), .row :nth-child(4n-3) {
        background: #aaaaaa;
    }
}

/* For large screen */
@media (min-width: 992px) {
    .row :nth-child(6n), .row :nth-child(6n-1), .row :nth-child(6n-2) {
        background: #dcdcdc;
    }
    .row :nth-child(6n-3), .row :nth-child(6n-4), .row :nth-child(6n-5) {
        background: #aaaaaa;
    }
}

Working FIDDLE
I have also included the bootstrap CSS here.

How do I replace part of a string in PHP?

Simply use str_replace:

$text = str_replace(' ', '_', $text);

You would do this after your previous substr and strtolower calls, like so:

$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);

If you want to get fancy, though, you can do it in one line:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));

Listen to changes within a DIV and act accordingly

The change event is limited to input, textarea & and select.

See http://api.jquery.com/change/ for more information.

Simple Random Samples from a Sql database

I want to point out that all of these solutions appear to sample without replacement. Selecting the top K rows from a random sort or joining to a table that contains unique keys in random order will yield a random sample generated without replacement.

If you want your sample to be independent, you'll need to sample with replacement. See Question 25451034 for one example of how to do this using a JOIN in a manner similar to user12861's solution. The solution is written for T-SQL, but the concept works in any SQL db.

How to use `subprocess` command with pipes

Or you can always use the communicate method on the subprocess objects.

cmd = "ps -A|grep 'process_name'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

The communicate method returns a tuple of the standard output and the standard error.

Quick way to create a list of values in C#?

You can do that with

var list = new List<string>{ "foo", "bar" };

Here are some other common instantiations of other common Data Structures:

Dictionary

var dictionary = new Dictionary<string, string> 
{
    { "texas",   "TX" },
    { "utah",    "UT" },
    { "florida", "FL" }
};

Array list

var array = new string[] { "foo", "bar" };

Queue

var queque = new Queue<int>(new[] { 1, 2, 3 });

Stack

var queque = new Stack<int>(new[] { 1, 2, 3 });

As you can see for the majority of cases it is merely adding the values in curly braces, or instantiating a new array followed by curly braces and values.

How can I make Bootstrap 4 columns all the same height?

You just have to use class="row-eq-height" with your class="row" to get equal height columns for previous bootstrap versions.

but with bootstrap 4 this comes natively.

check this link --http://getbootstrap.com.vn/examples/equal-height-columns/

How to get Enum Value from index in Java?

I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

public enum Example {

    UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");

    private static HashMap<Integer, Example> enumById = new HashMap<>();
    static {
        Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
    }

    public static Example getById(int id) {
        return enumById.getOrDefault(id, UNKNOWN);
    }

    private int id;
    private String description;

    private Example(int id, String description) {
        this.id = id;
        this.description= description;
    }

    public String getDescription() {
        return description;
    }

    public int getId() {
        return id;
    }
}

If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

public static Example getById(int id) {
        return enumById.get(id);
}

How do I list one filename per output line in Linux?

Ls is designed for human consumption, and you should not parse its output.

In shell scripts, there are a few cases where parsing the output of ls does work is the simplest way of achieving the desired effect. Since ls might mangle non-ASCII and control characters in file names, these cases are a subset of those that do not require obtaining a file name from ls.

In python, there is absolutely no reason to invoke ls. Python has all of ls's functionality built-in. Use os.listdir to list the contents of a directory and os.stat or os to obtain file metadata. Other functions in the os modules are likely to be relevant to your problem as well.


If you're accessing remote files over ssh, a reasonably robust way of listing file names is through sftp:

echo ls -1 | sftp remote-site:dir

This prints one file name per line, and unlike the ls utility, sftp does not mangle nonprintable characters. You will still not be able to reliably list directories where a file name contains a newline, but that's rarely done (remember this as a potential security issue, not a usability issue).

In python (beware that shell metacharacters must be escapes in remote_dir):

command_line = "echo ls -1 | sftp " + remote_site + ":" + remote_dir
remote_files = os.popen(command_line).read().split("\n")

For more complex interactions, look up sftp's batch mode in the documentation.

On some systems (Linux, Mac OS X, perhaps some other unices, but definitely not Windows), a different approach is to mount a remote filesystem through ssh with sshfs, and then work locally.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I found a possible solution here: http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15

Edit:

If you automate Microsoft Excel with Microsoft Visual Basic .NET, Microsoft Visual C# .NET, or Microsoft Visual C++, you may receive the following errors when calling certain methods because the machine has the locale set to something other than US English (locale ID or LCID 1033):

Exception from HRESULT: 0x800A03EC

and/or

Old format or invalid type library

SOLUTION 1:


To get around this error you can set CurrentCulture to en-US when executing code related to Excel and reset back to your originale by using these 2 functions.

//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
void SetNewCurrentCulture()
{
  oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
//reset Current Culture back to the originale
void ResetCurrentCulture()
{
  System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}

SOLUTION 2:


Another solution that could work, create a 1033 directory under Microsoft Office\Office11 (or your corresponding office-version), copy excel.exe to the 1033 directory, and rename it to xllex.dll.

Although you might solve the problem using one off these solutions, when you call the Excel object model in locales other than US English, the Excel object model can act differently and your code can fail in ways you may not have thought of. For example, you might have code that sets the value of a range to a date:

yourRange.Value2 = "10/10/09"

Depending on the locale this code can act differently resulting in Excel putting into the range any of the following values:

October 10, 2009 September 10, 2009 October 9, 2010

How do I make an editable DIV look like a text field?

I would suggest this for matching Chrome's style, extended from Jarish's example. Notice the cursor property which previous answers have omitted.

cursor: text;
border: 1px solid #ccc;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 200px;
overflow: auto;
padding: 2px;
resize: both;
-moz-box-shadow: inset 0px 1px 2px #ccc;
-webkit-box-shadow: inset 0px 1px 2px #ccc;
box-shadow: inset 0px 1px 2px #ccc;

How do I get a specific range of numbers from rand()?

This answer does not focus on the randomness but on the arithmetic order. To get a number within a range, usually we can do it like this:

// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin + f * (aMax - aMin);

However, there is a possibility that (aMax - aMin) overflows. E.g. aMax = 1, aMin = -DBL_MAX. A safer way is to write like this:

// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin - f * aMin + f * aMax;

Based on this concept, something like this may cause a problem.

rand() % (max_number + 1 - minimum_number) + minimum_number
// 1. max_number + 1 might overflow
// 2. max_number + 1 - min_number might overflow

Prevent flex items from overflowing a container

If you want the overflow to wrap: flex-flow: row wrap

What does "res.render" do, and what does the html file look like?

What does res.render do and what does the html file look like?

res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.


Answering Edit 2 part.

// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `orders` template
response.render("orders", {orders: orders_json});

So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs


Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.

Browser detection in JavaScript?

I make this small function, hope it helps. Here you can find the latest version browserDetection

function detectBrowser(userAgent){
  var chrome  = /.*(Chrome\/).*(Safari\/).*/g;
  var firefox = /.*(Firefox\/).*/g;
  var safari  = /.*(Version\/).*(Safari\/).*/g;
  var opera   = /.*(Chrome\/).*(Safari\/).*(OPR\/).*/g

  if(opera.exec(userAgent))
    return "Opera"
  if(chrome.exec(userAgent))
    return "Chrome"
  if(safari.exec(userAgent))
    return "Safari"
  if(firefox.exec(userAgent))
    return "Firefox"
}

Multiple WHERE clause in Linq

@Jon: Jon, are you saying using multiple where clauses e.g.

var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" 
            where r.Field<string>("UserName") != "YYYY"
            select r;

is more restictive than using

var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" && r.Field<string>("UserName") != "YYYY"
            select r;

I think they are equivalent as far as the result goes.

However, I haven't tested, if using multiple where in the first example cause in 2 subqueries, i.e. .Where(r=>r.UserName!="XXXX").Where(r=>r.UserName!="YYYY) or the LINQ translator is smart enought to execute .Where(r=>r.UserName!="XXXX" && r.UsernName!="YYYY")

Simple InputBox function

The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.

$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString

This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:

[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))

If the info does not need to be secure at all you can convert it to plain text:

$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))

Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0

How to define an enum with string value?

Well first you try to assign strings not chars, even if they are just one character. use ',' instead of ",". Next thing is, enums only take integral types without char you could use the unicode value, but i would strongly advice you not to do so. If you are certain that these values stay the same, in differnt cultures and languages, i would use a static class with const strings.

How to use ArrayList's get() method

Here is the official documentation of ArrayList.get().

Anyway it is very simple, for example

ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = (String) list.get(0); // here you get "1" in str

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

I know that maybe this problem was resolved but I had the same problem with different solution. For that, I am going to explain another possible solution. In my case, the port 80 was occupied by Skype (pid: 25252) and I did not know what programme was.

To see the program's pid which is using the port 80 you can use the command that other people said before:

netstat -aon | findstr 0.0:80

To kill the process using the pid (in the case that you do not know the programme) you have to open the CMD with administrator permission and use the next command:

taskkill /pid 25252

Other options with this command are here.

How to get Linux console window width in Python

I was trying the solution from here that calls out to stty size:

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

However this failed for me because I was working on a script that expects redirected input on stdin, and stty would complain that "stdin isn't a terminal" in that case.

I was able to make it work like this:

with open('/dev/tty') as tty:
    height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split()

Getting the text from a drop-down box

    var ele = document.getElementById('newSkill')
    ele.onchange = function(){
            var length = ele.children.length
            for(var i=0; i<length;i++){
                if(ele.children[i].selected){alert(ele.children[i].text)};              
            }
    }   

How to select the first element of a set with JSTL?

Since i have have just one element in my Set the order is not important So I can access to the first element like this :

${ attachments.iterator().next().id }

How to style SVG with external CSS?

Your main.css file would only have an effect on the content of the SVG if the SVG file is included inline in the HTML:

https://developer.mozilla.org/en/docs/SVG_In_HTML_Introduction

<html>
  <body>
  <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">
    <g>
      <path d="M28.44......./>
    </g>
  </svg>
</html>

If you want to keep your SVG in files, the CSS needs to be defined inside of the SVG file.

You can do it with a style tag:

http://www.w3.org/TR/SVG/styling.html#StyleElementExample

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
     width="50px" height="50px" viewBox="0 0 50 50">
  <defs>
    <style type="text/css"><![CDATA[
      .socIcon g {
        fill:red;
      }
    ]]></style>
  </defs>
  <g>
    <path d="M28.44......./>
  </g>
</svg>

You could use a tool on the server side to update the style tag depending on the active style. In ruby you could achieve this with Nokogiri. SVG is just XML. So there are probably many XML libraries available that can probably achieve this.

If you're not able to do that, you will have to just have to use them as though they were PNGs; creating a set for each style, and saving their styles inline.

Using Chrome, how to find to which events are bound to an element

2018 Update - Might be helpful for future readers:

I am not sure when this was originally introduced in Chrome. But another (easy) way this can be done now in Chrome is via console commands.

For example: (in chrome console type)

getEventListeners($0)

Whereas $0 is the selected element in the DOM.

https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#0_-_4

enter image description here

How to force a list to be vertical using html css

CSS

li {
   display: inline-block;
}

Works for me also.

git checkout all the files

If you are at the root of your working directory, you can do git checkout -- . to check-out all files in the current HEAD and replace your local files.

You can also do git reset --hard to reset your working directory and replace all changes (including the index).

How do I check if a directory exists? "is_dir", "file_exists" or both?

Well instead of checking both, you could do if(stream_resolve_include_path($folder)!==false). It is slower but kills two birds in one shot.

Another option is to simply ignore the E_WARNING, not by using @mkdir(...); (because that would simply waive all possible warnings, not just the directory already exists one), but by registering a specific error handler before doing it:

namespace com\stackoverflow;

set_error_handler(function($errno, $errm) { 
    if (strpos($errm,"exists") === false) throw new \Exception($errm); //or better: create your own FolderCreationException class
});
mkdir($folder);
/* possibly more mkdir instructions, which is when this becomes useful */
restore_error_handler();

Using OR operator in a jquery if statement

Update: using .indexOf() to detect if stat value is one of arr elements

Pure JavaScript

_x000D_
_x000D_
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
    var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
_x000D_
_x000D_

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

As Rahul stated, it is a common Chrome and an OSX bug. I was having similar issues in the past. In fact I finally got tired of making the 2 [yes I know it is not many] additional clicks when testing a local site for work.

As for a possible workaround to this issue [using Windows], I would using one of the many self signing certificate utilities available.

Recommended Steps:

  1. Create a Self Signed Cert
  2. Import Certificate into Windows Certificate Manager
  3. Import Certificate in Chrome Certificate Manager
    NOTE: Step 3 will resolve the issue experienced once Google addresses the bug...considering the time in has been stale there is no ETA in the foreseeable future.**

    As much as I prefer to use Chrome for development, I have found myself in Firefox Developer Edition lately. which does not have this issue.

    Hope this helps :)

Pandas dataframe get first row of each group

>>> df.groupby('id').first()
     value
id        
1    first
2    first
3    first
4   second
5    first
6    first
7   fourth

If you need id as column:

>>> df.groupby('id').first().reset_index()
   id   value
0   1   first
1   2   first
2   3   first
3   4  second
4   5   first
5   6   first
6   7  fourth

To get n first records, you can use head():

>>> df.groupby('id').head(2).reset_index(drop=True)
    id   value
0    1   first
1    1  second
2    2   first
3    2  second
4    3   first
5    3   third
6    4  second
7    4   fifth
8    5   first
9    6   first
10   6  second
11   7  fourth
12   7   fifth

Does React Native styles support gradients?

Just export your gradient as SVG and use it using react-native-svg and when after you import your component set width and height and preserveAspectRatio="xMinYMin slice"to scale an SVG gradient at your needs.

Setting timezone to UTC (0) in PHP

List of entire available timezones.

$time_zones = array (
  0 => 'Africa/Abidjan',
  1 => 'Africa/Accra',
  2 => 'Africa/Addis_Ababa',
  3 => 'Africa/Algiers',
  4 => 'Africa/Asmara',
  5 => 'Africa/Asmera',
  6 => 'Africa/Bamako',
  7 => 'Africa/Bangui',
  8 => 'Africa/Banjul',
  9 => 'Africa/Bissau',
  10 => 'Africa/Blantyre',
  11 => 'Africa/Brazzaville',
  12 => 'Africa/Bujumbura',
  13 => 'Africa/Cairo',
  14 => 'Africa/Casablanca',
  15 => 'Africa/Ceuta',
  16 => 'Africa/Conakry',
  17 => 'Africa/Dakar',
  18 => 'Africa/Dar_es_Salaam',
  19 => 'Africa/Djibouti',
  20 => 'Africa/Douala',
  21 => 'Africa/El_Aaiun',
  22 => 'Africa/Freetown',
  23 => 'Africa/Gaborone',
  24 => 'Africa/Harare',
  25 => 'Africa/Johannesburg',
  26 => 'Africa/Juba',
  27 => 'Africa/Kampala',
  28 => 'Africa/Khartoum',
  29 => 'Africa/Kigali',
  30 => 'Africa/Kinshasa',
  31 => 'Africa/Lagos',
  32 => 'Africa/Libreville',
  33 => 'Africa/Lome',
  34 => 'Africa/Luanda',
  35 => 'Africa/Lubumbashi',
  36 => 'Africa/Lusaka',
  37 => 'Africa/Malabo',
  38 => 'Africa/Maputo',
  39 => 'Africa/Maseru',
  40 => 'Africa/Mbabane',
  41 => 'Africa/Mogadishu',
  42 => 'Africa/Monrovia',
  43 => 'Africa/Nairobi',
  44 => 'Africa/Ndjamena',
  45 => 'Africa/Niamey',
  46 => 'Africa/Nouakchott',
  47 => 'Africa/Ouagadougou',
  48 => 'Africa/Porto-Novo',
  49 => 'Africa/Sao_Tome',
  50 => 'Africa/Timbuktu',
  51 => 'Africa/Tripoli',
  52 => 'Africa/Tunis',
  53 => 'Africa/Windhoek',
  54 => 'America/Adak',
  55 => 'America/Anchorage',
  56 => 'America/Anguilla',
  57 => 'America/Antigua',
  58 => 'America/Araguaina',
  59 => 'America/Argentina/Buenos_Aires',
  60 => 'America/Argentina/Catamarca',
  61 => 'America/Argentina/ComodRivadavia',
  62 => 'America/Argentina/Cordoba',
  63 => 'America/Argentina/Jujuy',
  64 => 'America/Argentina/La_Rioja',
  65 => 'America/Argentina/Mendoza',
  66 => 'America/Argentina/Rio_Gallegos',
  67 => 'America/Argentina/Salta',
  68 => 'America/Argentina/San_Juan',
  69 => 'America/Argentina/San_Luis',
  70 => 'America/Argentina/Tucuman',
  71 => 'America/Argentina/Ushuaia',
  72 => 'America/Aruba',
  73 => 'America/Asuncion',
  74 => 'America/Atikokan',
  75 => 'America/Atka',
  76 => 'America/Bahia',
  77 => 'America/Bahia_Banderas',
  78 => 'America/Barbados',
  79 => 'America/Belem',
  80 => 'America/Belize',
  81 => 'America/Blanc-Sablon',
  82 => 'America/Boa_Vista',
  83 => 'America/Bogota',
  84 => 'America/Boise',
  85 => 'America/Buenos_Aires',
  86 => 'America/Cambridge_Bay',
  87 => 'America/Campo_Grande',
  88 => 'America/Cancun',
  89 => 'America/Caracas',
  90 => 'America/Catamarca',
  91 => 'America/Cayenne',
  92 => 'America/Cayman',
  93 => 'America/Chicago',
  94 => 'America/Chihuahua',
  95 => 'America/Coral_Harbour',
  96 => 'America/Cordoba',
  97 => 'America/Costa_Rica',
  98 => 'America/Creston',
  99 => 'America/Cuiaba',
  100 => 'America/Curacao',
  101 => 'America/Danmarkshavn',
  102 => 'America/Dawson',
  103 => 'America/Dawson_Creek',
  104 => 'America/Denver',
  105 => 'America/Detroit',
  106 => 'America/Dominica',
  107 => 'America/Edmonton',
  108 => 'America/Eirunepe',
  109 => 'America/El_Salvador',
  110 => 'America/Ensenada',
  111 => 'America/Fort_Nelson',
  112 => 'America/Fort_Wayne',
  113 => 'America/Fortaleza',
  114 => 'America/Glace_Bay',
  115 => 'America/Godthab',
  116 => 'America/Goose_Bay',
  117 => 'America/Grand_Turk',
  118 => 'America/Grenada',
  119 => 'America/Guadeloupe',
  120 => 'America/Guatemala',
  121 => 'America/Guayaquil',
  122 => 'America/Guyana',
  123 => 'America/Halifax',
  124 => 'America/Havana',
  125 => 'America/Hermosillo',
  126 => 'America/Indiana/Indianapolis',
  127 => 'America/Indiana/Knox',
  128 => 'America/Indiana/Marengo',
  129 => 'America/Indiana/Petersburg',
  130 => 'America/Indiana/Tell_City',
  131 => 'America/Indiana/Vevay',
  132 => 'America/Indiana/Vincennes',
  133 => 'America/Indiana/Winamac',
  134 => 'America/Indianapolis',
  135 => 'America/Inuvik',
  136 => 'America/Iqaluit',
  137 => 'America/Jamaica',
  138 => 'America/Jujuy',
  139 => 'America/Juneau',
  140 => 'America/Kentucky/Louisville',
  141 => 'America/Kentucky/Monticello',
  142 => 'America/Knox_IN',
  143 => 'America/Kralendijk',
  144 => 'America/La_Paz',
  145 => 'America/Lima',
  146 => 'America/Los_Angeles',
  147 => 'America/Louisville',
  148 => 'America/Lower_Princes',
  149 => 'America/Maceio',
  150 => 'America/Managua',
  151 => 'America/Manaus',
  152 => 'America/Marigot',
  153 => 'America/Martinique',
  154 => 'America/Matamoros',
  155 => 'America/Mazatlan',
  156 => 'America/Mendoza',
  157 => 'America/Menominee',
  158 => 'America/Merida',
  159 => 'America/Metlakatla',
  160 => 'America/Mexico_City',
  161 => 'America/Miquelon',
  162 => 'America/Moncton',
  163 => 'America/Monterrey',
  164 => 'America/Montevideo',
  165 => 'America/Montreal',
  166 => 'America/Montserrat',
  167 => 'America/Nassau',
  168 => 'America/New_York',
  169 => 'America/Nipigon',
  170 => 'America/Nome',
  171 => 'America/Noronha',
  172 => 'America/North_Dakota/Beulah',
  173 => 'America/North_Dakota/Center',
  174 => 'America/North_Dakota/New_Salem',
  175 => 'America/Ojinaga',
  176 => 'America/Panama',
  177 => 'America/Pangnirtung',
  178 => 'America/Paramaribo',
  179 => 'America/Phoenix',
  180 => 'America/Port-au-Prince',
  181 => 'America/Port_of_Spain',
  182 => 'America/Porto_Acre',
  183 => 'America/Porto_Velho',
  184 => 'America/Puerto_Rico',
  185 => 'America/Rainy_River',
  186 => 'America/Rankin_Inlet',
  187 => 'America/Recife',
  188 => 'America/Regina',
  189 => 'America/Resolute',
  190 => 'America/Rio_Branco',
  191 => 'America/Rosario',
  192 => 'America/Santa_Isabel',
  193 => 'America/Santarem',
  194 => 'America/Santiago',
  195 => 'America/Santo_Domingo',
  196 => 'America/Sao_Paulo',
  197 => 'America/Scoresbysund',
  198 => 'America/Shiprock',
  199 => 'America/Sitka',
  200 => 'America/St_Barthelemy',
  201 => 'America/St_Johns',
  202 => 'America/St_Kitts',
  203 => 'America/St_Lucia',
  204 => 'America/St_Thomas',
  205 => 'America/St_Vincent',
  206 => 'America/Swift_Current',
  207 => 'America/Tegucigalpa',
  208 => 'America/Thule',
  209 => 'America/Thunder_Bay',
  210 => 'America/Tijuana',
  211 => 'America/Toronto',
  212 => 'America/Tortola',
  213 => 'America/Vancouver',
  214 => 'America/Virgin',
  215 => 'America/Whitehorse',
  216 => 'America/Winnipeg',
  217 => 'America/Yakutat',
  218 => 'America/Yellowknife',
  219 => 'Antarctica/Casey',
  220 => 'Antarctica/Davis',
  221 => 'Antarctica/DumontDUrville',
  222 => 'Antarctica/Macquarie',
  223 => 'Antarctica/Mawson',
  224 => 'Antarctica/McMurdo',
  225 => 'Antarctica/Palmer',
  226 => 'Antarctica/Rothera',
  227 => 'Antarctica/South_Pole',
  228 => 'Antarctica/Syowa',
  229 => 'Antarctica/Troll',
  230 => 'Antarctica/Vostok',
  231 => 'Arctic/Longyearbyen',
  232 => 'Asia/Aden',
  233 => 'Asia/Almaty',
  234 => 'Asia/Amman',
  235 => 'Asia/Anadyr',
  236 => 'Asia/Aqtau',
  237 => 'Asia/Aqtobe',
  238 => 'Asia/Ashgabat',
  239 => 'Asia/Ashkhabad',
  240 => 'Asia/Baghdad',
  241 => 'Asia/Bahrain',
  242 => 'Asia/Baku',
  243 => 'Asia/Bangkok',
  244 => 'Asia/Beirut',
  245 => 'Asia/Bishkek',
  246 => 'Asia/Brunei',
  247 => 'Asia/Calcutta',
  248 => 'Asia/Chita',
  249 => 'Asia/Choibalsan',
  250 => 'Asia/Chongqing',
  251 => 'Asia/Chungking',
  252 => 'Asia/Colombo',
  253 => 'Asia/Dacca',
  254 => 'Asia/Damascus',
  255 => 'Asia/Dhaka',
  256 => 'Asia/Dili',
  257 => 'Asia/Dubai',
  258 => 'Asia/Dushanbe',
  259 => 'Asia/Gaza',
  260 => 'Asia/Harbin',
  261 => 'Asia/Hebron',
  262 => 'Asia/Ho_Chi_Minh',
  263 => 'Asia/Hong_Kong',
  264 => 'Asia/Hovd',
  265 => 'Asia/Irkutsk',
  266 => 'Asia/Istanbul',
  267 => 'Asia/Jakarta',
  268 => 'Asia/Jayapura',
  269 => 'Asia/Jerusalem',
  270 => 'Asia/Kabul',
  271 => 'Asia/Kamchatka',
  272 => 'Asia/Karachi',
  273 => 'Asia/Kashgar',
  274 => 'Asia/Kathmandu',
  275 => 'Asia/Katmandu',
  276 => 'Asia/Khandyga',
  277 => 'Asia/Kolkata',
  278 => 'Asia/Krasnoyarsk',
  279 => 'Asia/Kuala_Lumpur',
  280 => 'Asia/Kuching',
  281 => 'Asia/Kuwait',
  282 => 'Asia/Macao',
  283 => 'Asia/Macau',
  284 => 'Asia/Magadan',
  285 => 'Asia/Makassar',
  286 => 'Asia/Manila',
  287 => 'Asia/Muscat',
  288 => 'Asia/Nicosia',
  289 => 'Asia/Novokuznetsk',
  290 => 'Asia/Novosibirsk',
  291 => 'Asia/Omsk',
  292 => 'Asia/Oral',
  293 => 'Asia/Phnom_Penh',
  294 => 'Asia/Pontianak',
  295 => 'Asia/Pyongyang',
  296 => 'Asia/Qatar',
  297 => 'Asia/Qyzylorda',
  298 => 'Asia/Rangoon',
  299 => 'Asia/Riyadh',
  300 => 'Asia/Saigon',
  301 => 'Asia/Sakhalin',
  302 => 'Asia/Samarkand',
  303 => 'Asia/Seoul',
  304 => 'Asia/Shanghai',
  305 => 'Asia/Singapore',
  306 => 'Asia/Srednekolymsk',
  307 => 'Asia/Taipei',
  308 => 'Asia/Tashkent',
  309 => 'Asia/Tbilisi',
  310 => 'Asia/Tehran',
  311 => 'Asia/Tel_Aviv',
  312 => 'Asia/Thimbu',
  313 => 'Asia/Thimphu',
  314 => 'Asia/Tokyo',
  315 => 'Asia/Ujung_Pandang',
  316 => 'Asia/Ulaanbaatar',
  317 => 'Asia/Ulan_Bator',
  318 => 'Asia/Urumqi',
  319 => 'Asia/Ust-Nera',
  320 => 'Asia/Vientiane',
  321 => 'Asia/Vladivostok',
  322 => 'Asia/Yakutsk',
  323 => 'Asia/Yekaterinburg',
  324 => 'Asia/Yerevan',
  325 => 'Atlantic/Azores',
  326 => 'Atlantic/Bermuda',
  327 => 'Atlantic/Canary',
  328 => 'Atlantic/Cape_Verde',
  329 => 'Atlantic/Faeroe',
  330 => 'Atlantic/Faroe',
  331 => 'Atlantic/Jan_Mayen',
  332 => 'Atlantic/Madeira',
  333 => 'Atlantic/Reykjavik',
  334 => 'Atlantic/South_Georgia',
  335 => 'Atlantic/St_Helena',
  336 => 'Atlantic/Stanley',
  337 => 'Australia/ACT',
  338 => 'Australia/Adelaide',
  339 => 'Australia/Brisbane',
  340 => 'Australia/Broken_Hill',
  341 => 'Australia/Canberra',
  342 => 'Australia/Currie',
  343 => 'Australia/Darwin',
  344 => 'Australia/Eucla',
  345 => 'Australia/Hobart',
  346 => 'Australia/LHI',
  347 => 'Australia/Lindeman',
  348 => 'Australia/Lord_Howe',
  349 => 'Australia/Melbourne',
  350 => 'Australia/North',
  351 => 'Australia/NSW',
  352 => 'Australia/Perth',
  353 => 'Australia/Queensland',
  354 => 'Australia/South',
  355 => 'Australia/Sydney',
  356 => 'Australia/Tasmania',
  357 => 'Australia/Victoria',
  358 => 'Australia/West',
  359 => 'Australia/Yancowinna',
  360 => 'Europe/Amsterdam',
  361 => 'Europe/Andorra',
  362 => 'Europe/Athens',
  363 => 'Europe/Belfast',
  364 => 'Europe/Belgrade',
  365 => 'Europe/Berlin',
  366 => 'Europe/Bratislava',
  367 => 'Europe/Brussels',
  368 => 'Europe/Bucharest',
  369 => 'Europe/Budapest',
  370 => 'Europe/Busingen',
  371 => 'Europe/Chisinau',
  372 => 'Europe/Copenhagen',
  373 => 'Europe/Dublin',
  374 => 'Europe/Gibraltar',
  375 => 'Europe/Guernsey',
  376 => 'Europe/Helsinki',
  377 => 'Europe/Isle_of_Man',
  378 => 'Europe/Istanbul',
  379 => 'Europe/Jersey',
  380 => 'Europe/Kaliningrad',
  381 => 'Europe/Kiev',
  382 => 'Europe/Lisbon',
  383 => 'Europe/Ljubljana',
  384 => 'Europe/London',
  385 => 'Europe/Luxembourg',
  386 => 'Europe/Madrid',
  387 => 'Europe/Malta',
  388 => 'Europe/Mariehamn',
  389 => 'Europe/Minsk',
  390 => 'Europe/Monaco',
  391 => 'Europe/Moscow',
  392 => 'Europe/Nicosia',
  393 => 'Europe/Oslo',
  394 => 'Europe/Paris',
  395 => 'Europe/Podgorica',
  396 => 'Europe/Prague',
  397 => 'Europe/Riga',
  398 => 'Europe/Rome',
  399 => 'Europe/Samara',
  400 => 'Europe/San_Marino',
  401 => 'Europe/Sarajevo',
  402 => 'Europe/Simferopol',
  403 => 'Europe/Skopje',
  404 => 'Europe/Sofia',
  405 => 'Europe/Stockholm',
  406 => 'Europe/Tallinn',
  407 => 'Europe/Tirane',
  408 => 'Europe/Tiraspol',
  409 => 'Europe/Uzhgorod',
  410 => 'Europe/Vaduz',
  411 => 'Europe/Vatican',
  412 => 'Europe/Vienna',
  413 => 'Europe/Vilnius',
  414 => 'Europe/Volgograd',
  415 => 'Europe/Warsaw',
  416 => 'Europe/Zagreb',
  417 => 'Europe/Zaporozhye',
  418 => 'Europe/Zurich',
  419 => 'Indian/Antananarivo',
  420 => 'Indian/Chagos',
  421 => 'Indian/Christmas',
  422 => 'Indian/Cocos',
  423 => 'Indian/Comoro',
  424 => 'Indian/Kerguelen',
  425 => 'Indian/Mahe',
  426 => 'Indian/Maldives',
  427 => 'Indian/Mauritius',
  428 => 'Indian/Mayotte',
  429 => 'Indian/Reunion',
  430 => 'Pacific/Apia',
  431 => 'Pacific/Auckland',
  432 => 'Pacific/Bougainville',
  433 => 'Pacific/Chatham',
  434 => 'Pacific/Chuuk',
  435 => 'Pacific/Easter',
  436 => 'Pacific/Efate',
  437 => 'Pacific/Enderbury',
  438 => 'Pacific/Fakaofo',
  439 => 'Pacific/Fiji',
  440 => 'Pacific/Funafuti',
  441 => 'Pacific/Galapagos',
  442 => 'Pacific/Gambier',
  443 => 'Pacific/Guadalcanal',
  444 => 'Pacific/Guam',
  445 => 'Pacific/Honolulu',
  446 => 'Pacific/Johnston',
  447 => 'Pacific/Kiritimati',
  448 => 'Pacific/Kosrae',
  449 => 'Pacific/Kwajalein',
  450 => 'Pacific/Majuro',
  451 => 'Pacific/Marquesas',
  452 => 'Pacific/Midway',
  453 => 'Pacific/Nauru',
  454 => 'Pacific/Niue',
  455 => 'Pacific/Norfolk',
  456 => 'Pacific/Noumea',
  457 => 'Pacific/Pago_Pago',
  458 => 'Pacific/Palau',
  459 => 'Pacific/Pitcairn',
  460 => 'Pacific/Pohnpei',
  461 => 'Pacific/Ponape',
  462 => 'Pacific/Port_Moresby',
  463 => 'Pacific/Rarotonga',
  464 => 'Pacific/Saipan',
  465 => 'Pacific/Samoa',
  466 => 'Pacific/Tahiti',
  467 => 'Pacific/Tarawa',
  468 => 'Pacific/Tongatapu',
  469 => 'Pacific/Truk',
  470 => 'Pacific/Wake',
  471 => 'Pacific/Wallis',
  472 => 'Pacific/Yap',
  473 => 'Brazil/Acre',
  474 => 'Brazil/DeNoronha',
  475 => 'Brazil/East',
  476 => 'Brazil/West',
  477 => 'Canada/Atlantic',
  478 => 'Canada/Central',
  479 => 'Canada/East-Saskatchewan',
  480 => 'Canada/Eastern',
  481 => 'Canada/Mountain',
  482 => 'Canada/Newfoundland',
  483 => 'Canada/Pacific',
  484 => 'Canada/Saskatchewan',
  485 => 'Canada/Yukon',
  486 => 'CET',
  487 => 'Chile/Continental',
  488 => 'Chile/EasterIsland',
  489 => 'CST6CDT',
  490 => 'Cuba',
  491 => 'EET',
  492 => 'Egypt',
  493 => 'Eire',
  494 => 'EST',
  495 => 'EST5EDT',
  496 => 'Etc/GMT',
  497 => 'Etc/GMT+0',
  498 => 'Etc/GMT+1',
  499 => 'Etc/GMT+10',
  500 => 'Etc/GMT+11',
  501 => 'Etc/GMT+12',
  502 => 'Etc/GMT+2',
  503 => 'Etc/GMT+3',
  504 => 'Etc/GMT+4',
  505 => 'Etc/GMT+5',
  506 => 'Etc/GMT+6',
  507 => 'Etc/GMT+7',
  508 => 'Etc/GMT+8',
  509 => 'Etc/GMT+9',
  510 => 'Etc/GMT-0',
  511 => 'Etc/GMT-1',
  512 => 'Etc/GMT-10',
  513 => 'Etc/GMT-11',
  514 => 'Etc/GMT-12',
  515 => 'Etc/GMT-13',
  516 => 'Etc/GMT-14',
  517 => 'Etc/GMT-2',
  518 => 'Etc/GMT-3',
  519 => 'Etc/GMT-4',
  520 => 'Etc/GMT-5',
  521 => 'Etc/GMT-6',
  522 => 'Etc/GMT-7',
  523 => 'Etc/GMT-8',
  524 => 'Etc/GMT-9',
  525 => 'Etc/GMT0',
  526 => 'Etc/Greenwich',
  527 => 'Etc/UCT',
  528 => 'Etc/Universal',
  529 => 'Etc/UTC',
  530 => 'Etc/Zulu',
  531 => 'Factory',
  532 => 'GB',
  533 => 'GB-Eire',
  534 => 'GMT',
  535 => 'GMT+0',
  536 => 'GMT-0',
  537 => 'GMT0',
  538 => 'Greenwich',
  539 => 'Hongkong',
  540 => 'HST',
  541 => 'Iceland',
  542 => 'Iran',
  543 => 'Israel',
  544 => 'Jamaica',
  545 => 'Japan',
  546 => 'Kwajalein',
  547 => 'Libya',
  548 => 'MET',
  549 => 'Mexico/BajaNorte',
  550 => 'Mexico/BajaSur',
  551 => 'Mexico/General',
  552 => 'MST',
  553 => 'MST7MDT',
  554 => 'Navajo',
  555 => 'NZ',
  556 => 'NZ-CHAT',
  557 => 'Poland',
  558 => 'Portugal',
  559 => 'PRC',
  560 => 'PST8PDT',
  561 => 'ROC',
  562 => 'ROK',
  563 => 'Singapore',
  564 => 'Turkey',
  565 => 'UCT',
  566 => 'Universal',
  567 => 'US/Alaska',
  568 => 'US/Aleutian',
  569 => 'US/Arizona',
  570 => 'US/Central',
  571 => 'US/East-Indiana',
  572 => 'US/Eastern',
  573 => 'US/Hawaii',
  574 => 'US/Indiana-Starke',
  575 => 'US/Michigan',
  576 => 'US/Mountain',
  577 => 'US/Pacific',
  578 => 'US/Pacific-New',
  579 => 'US/Samoa',
  580 => 'UTC',
  581 => 'W-SU',
  582 => 'WET',
  583 => 'Zulu',
)

Android "Only the original thread that created a view hierarchy can touch its views."

My solution to this:

private void setText(final TextView text,final String value){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            text.setText(value);
        }
    });
}

Call this method on a background thread.

Matplotlib different size subplots

Probably the simplest way is using subplot2grid, described in Customizing Location of Subplot Using GridSpec.

ax = plt.subplot2grid((2, 2), (0, 0))

is equal to

import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])

so bmu's example becomes:

import numpy as np
import matplotlib.pyplot as plt

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

Launch Android application without main Activity and start Service on launching application

Android Studio Version 2.3

You can create a Service without a Main Activity by following a few easy steps. You'll be able to install this app through Android Studio and debug it like a normal app.

First, create a project in Android Studio without an activity. Then create your Service class and add the service to your AndroidManifest.xml

<application android:allowBackup="true"
    android:label="@string/app_name"
    android:icon="@mipmap/ic_launcher"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <service android:name="com.whatever.myservice.MyService">
        <intent-filter>
            <action android:name="com.whatever.myservice.MyService" />
        </intent-filter>
    </service>
</application>

Now, in the drop down next to the "Run" button(green arrow), go to "edit configurations" and within the "Launch Options" choose "Nothing". This will allow you to install your Service without Android Studio complaining about not having a Main Activity.

Once installed, the service will NOT be running but you will be able to start it with this adb shell command...

am startservice -n com.whatever.myservice/.MyService

Can check it's running with...

ps | grep whatever

I haven't tried yet but you can likely have Android Studio automatically start the service too. This would be done in that "Edit Configurations" menu.

How do I access properties of a javascript object if I don't know the names?

var attr, object_information='';

for(attr in object){

      //Get names and values of propertys with style (name : value)
      object_information += attr + ' : ' + object[attr] + '\n'; 

   }


alert(object_information); //Show all Object

How to use PowerShell select-string to find more than one pattern in a file?

To search for multiple matches in each file, we can sequence several Select-String calls:

Get-ChildItem C:\Logs |
  where { $_ | Select-String -Pattern 'VendorEnquiry' } |
  where { $_ | Select-String -Pattern 'Failed' } |
  ...

At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.

Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:

filter MultiSelect-String( [string[]]$Patterns ) {
  # Check the current item against all patterns.
  foreach( $Pattern in $Patterns ) {
    # If one of the patterns does not match, skip the item.
    $matched = @($_ | Select-String -Pattern $Pattern)
    if( -not $matched ) {
      return
    }
  }

  # If all patterns matched, pass the item through.
  $_
}

Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...


Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:

function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
  $time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}

PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True

PHP code to remove everything but numbers

This is for future developers, you can also try this. Simple too

echo preg_replace('/\D/', '', '604-619-5135');

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

Ruby send JSON request

A simple json POST request example for those that need it even simpler than what Tom is linking to:

require 'net/http'

uri = URI.parse("http://www.example.com/search.json")
response = Net::HTTP.post_form(uri, {"search" => "Berlin"})

How can I return two values from a function in Python?

def test():
    ....
    return r1, r2, r3, ....

>> ret_val = test()
>> print ret_val
(r1, r2, r3, ....)

now you can do everything you like with your tuple.

Timestamp with a millisecond precision: How to save them in MySQL

You can use BIGINT as follows:

CREATE TABLE user_reg (
user_id INT NOT NULL AUTO_INCREMENT,
identifier INT,
phone_number CHAR(11) NOT NULL,
verified TINYINT UNSIGNED NOT NULL,
reg_time BIGINT,
last_active_time BIGINT,
PRIMARY KEY (user_id),
INDEX (phone_number, user_id, identifier)
   );

How can I easily convert DataReader to List<T>?

I have written the following method using this case.

First, add the namespace: System.Reflection

For Example: T is return type(ClassName) and dr is parameter to mapping DataReader

C#, Call mapping method like the following:

List<Person> personList = new List<Person>();
personList = DataReaderMapToList<Person>(dataReaderForPerson);

This is the mapping method:

public static List<T> DataReaderMapToList<T>(IDataReader dr)
{
    List<T> list = new List<T>();
    T obj = default(T);
    while (dr.Read()) {
        obj = Activator.CreateInstance<T>();
        foreach (PropertyInfo prop in obj.GetType().GetProperties()) {
            if (!object.Equals(dr[prop.Name], DBNull.Value)) {
                prop.SetValue(obj, dr[prop.Name], null);
            }
        }
        list.Add(obj);
    }
    return list;
}

VB.NET, Call mapping method like the following:

Dim personList As New List(Of Person)
personList = DataReaderMapToList(Of Person)(dataReaderForPerson)

This is the mapping method:

Public Shared Function DataReaderMapToList(Of T)(ByVal dr As IDataReader) As List(Of T)
        Dim list As New List(Of T)
        Dim obj As T
        While dr.Read()
            obj = Activator.CreateInstance(Of T)()
            For Each prop As PropertyInfo In obj.GetType().GetProperties()
                If Not Object.Equals(dr(prop.Name), DBNull.Value) Then
                    prop.SetValue(obj, dr(prop.Name), Nothing)
                End If
            Next
            list.Add(obj)
        End While
        Return list
    End Function

What is the copy-and-swap idiom?

Assignment, at its heart, is two steps: tearing down the object's old state and building its new state as a copy of some other object's state.

Basically, that's what the destructor and the copy constructor do, so the first idea would be to delegate the work to them. However, since destruction mustn't fail, while construction might, we actually want to do it the other way around: first perform the constructive part and, if that succeeded, then do the destructive part. The copy-and-swap idiom is a way to do just that: It first calls a class' copy constructor to create a temporary object, then swaps its data with the temporary's, and then lets the temporary's destructor destroy the old state.
Since swap() is supposed to never fail, the only part which might fail is the copy-construction. That is performed first, and if it fails, nothing will be changed in the targeted object.

In its refined form, copy-and-swap is implemented by having the copy performed by initializing the (non-reference) parameter of the assignment operator:

T& operator=(T tmp)
{
    this->swap(tmp);
    return *this;
}

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

For the above issue, first of all if suppose tables contains more than 1 primary key then first remove all those primary keys and add first AUTO INCREMENT field as primary key then add another required primary keys which is removed earlier. Set AUTO INCREMENT option for required field from the option area.

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

For me Updating the SDK Tools fixed the errors.

Screenshot of the errors and update progress

How to convert .pem into .key?

CA's don't ask for your private keys! They only asks for CSR to issue a certificate for you.

If they have your private key, it's possible that your SSL certificate will be compromised and end up being revoked.

Your .key file is generated during CSR generation and, most probably, it's somewhere on your PC where you generated the CSR.

That's why private key is called "Private" - because nobody can have that file except you.

What does void mean in C, C++, and C#?

It indicates the absence of a return value in a function.

Some languages have two sorts of subroutines: procedures and functions. Procedures are just a sequence of operations, whereas a function is a sequence of operations that return a result.

In C and its derivatives, the difference between the two is not explicit. Everything is basically a function. the void keyword indicates that it's not an "actual" function, since it doesn't return a value.

How to set auto increment primary key in PostgreSQL?

Steps to do it on PgAdmin:

  • CREATE SEQUENCE sequnence_title START 1; // if table exist last id
  • Add this sequense to the primary key, table - properties - columns - column_id(primary key) edit - Constraints - Add nextval('sequnence_title'::regclass) to the field default.

how to loop through rows columns in excel VBA Macro

Try this:

Create A Macro with the following thing inside:

Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select

That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.

This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.

Just put it inside a For loop statement to do it x number of times. like:

For i = 1 to 100 'Do this 100 times
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(-1, 1).Select
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(0, -1).Select
Next i

Html helper for <input type="file" />

You can also use:

@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <p>
        <input type="file" id="fileUpload" name="fileUpload" size="23" />
    </p>
    <p>
        <input type="submit" value="Upload file" /></p> 
}

How to use aria-expanded="true" to change a css property

_x000D_
_x000D_
li a[aria-expanded="true"] span{_x000D_
    color: red;_x000D_
}
_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
li a[aria-expanded="true"]{_x000D_
    background: yellow;_x000D_
}
_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

Can't push to remote branch, cannot be resolved to branch

Git will let you checkout the current branch with a different casing, and it will fail to find a ref on the remote.

Just found out the hard way.

Algorithm to compare two images

These are simply ideas I've had thinking about the problem, never tried it but I like thinking about problems like this!

Before you begin

Consider normalising the pictures, if one is a higher resolution than the other, consider the option that one of them is a compressed version of the other, therefore scaling the resolution down might provide more accurate results.

Consider scanning various prospective areas of the image that could represent zoomed portions of the image and various positions and rotations. It starts getting tricky if one of the images are a skewed version of another, these are the sort of limitations you should identify and compromise on.

Matlab is an excellent tool for testing and evaluating images.

Testing the algorithms

You should test (at the minimum) a large human analysed set of test data where matches are known beforehand. If for example in your test data you have 1,000 images where 5% of them match, you now have a reasonably reliable benchmark. An algorithm that finds 10% positives is not as good as one that finds 4% of positives in our test data. However, one algorithm may find all the matches, but also have a large 20% false positive rate, so there are several ways to rate your algorithms.

The test data should attempt to be designed to cover as many types of dynamics as possible that you would expect to find in the real world.

It is important to note that each algorithm to be useful must perform better than random guessing, otherwise it is useless to us!

You can then apply your software into the real world in a controlled way and start to analyse the results it produces. This is the sort of software project which can go on for infinitum, there are always tweaks and improvements you can make, it is important to bear that in mind when designing it as it is easy to fall into the trap of the never ending project.

Colour Buckets

With two pictures, scan each pixel and count the colours. For example you might have the 'buckets':

white
red
blue
green
black

(Obviously you would have a higher resolution of counters). Every time you find a 'red' pixel, you increment the red counter. Each bucket can be representative of spectrum of colours, the higher resolution the more accurate but you should experiment with an acceptable difference rate.

Once you have your totals, compare it to the totals for a second image. You might find that each image has a fairly unique footprint, enough to identify matches.

Edge detection

How about using Edge Detection. alt text
(source: wikimedia.org)

With two similar pictures edge detection should provide you with a usable and fairly reliable unique footprint.

Take both pictures, and apply edge detection. Maybe measure the average thickness of the edges and then calculate the probability the image could be scaled, and rescale if necessary. Below is an example of an applied Gabor Filter (a type of edge detection) in various rotations.

alt text

Compare the pictures pixel for pixel, count the matches and the non matches. If they are within a certain threshold of error, you have a match. Otherwise, you could try reducing the resolution up to a certain point and see if the probability of a match improves.

Regions of Interest

Some images may have distinctive segments/regions of interest. These regions probably contrast highly with the rest of the image, and are a good item to search for in your other images to find matches. Take this image for example:

alt text
(source: meetthegimp.org)

The construction worker in blue is a region of interest and can be used as a search object. There are probably several ways you could extract properties/data from this region of interest and use them to search your data set.

If you have more than 2 regions of interest, you can measure the distances between them. Take this simplified example:

alt text
(source: per2000.eu)

We have 3 clear regions of interest. The distance between region 1 and 2 may be 200 pixels, between 1 and 3 400 pixels, and 2 and 3 200 pixels.

Search other images for similar regions of interest, normalise the distance values and see if you have potential matches. This technique could work well for rotated and scaled images. The more regions of interest you have, the probability of a match increases as each distance measurement matches.

It is important to think about the context of your data set. If for example your data set is modern art, then regions of interest would work quite well, as regions of interest were probably designed to be a fundamental part of the final image. If however you are dealing with images of construction sites, regions of interest may be interpreted by the illegal copier as ugly and may be cropped/edited out liberally. Keep in mind common features of your dataset, and attempt to exploit that knowledge.

Morphing

Morphing two images is the process of turning one image into the other through a set of steps:

alt text

Note, this is different to fading one image into another!

There are many software packages that can morph images. It's traditionaly used as a transitional effect, two images don't morph into something halfway usually, one extreme morphs into the other extreme as the final result.

Why could this be useful? Dependant on the morphing algorithm you use, there may be a relationship between similarity of images, and some parameters of the morphing algorithm.

In a grossly over simplified example, one algorithm might execute faster when there are less changes to be made. We then know there is a higher probability that these two images share properties with each other.

This technique could work well for rotated, distorted, skewed, zoomed, all types of copied images. Again this is just an idea I have had, it's not based on any researched academia as far as I am aware (I haven't look hard though), so it may be a lot of work for you with limited/no results.

Zipping

Ow's answer in this question is excellent, I remember reading about these sort of techniques studying AI. It is quite effective at comparing corpus lexicons.

One interesting optimisation when comparing corpuses is that you can remove words considered to be too common, for example 'The', 'A', 'And' etc. These words dilute our result, we want to work out how different the two corpus are so these can be removed before processing. Perhaps there are similar common signals in images that could be stripped before compression? It might be worth looking into.

Compression ratio is a very quick and reasonably effective way of determining how similar two sets of data are. Reading up about how compression works will give you a good idea why this could be so effective. For a fast to release algorithm this would probably be a good starting point.

Transparency

Again I am unsure how transparency data is stored for certain image types, gif png etc, but this will be extractable and would serve as an effective simplified cut out to compare with your data sets transparency.

Inverting Signals

An image is just a signal. If you play a noise from a speaker, and you play the opposite noise in another speaker in perfect sync at the exact same volume, they cancel each other out.

alt text
(source: themotorreport.com.au)

Invert on of the images, and add it onto your other image. Scale it/loop positions repetitively until you find a resulting image where enough of the pixels are white (or black? I'll refer to it as a neutral canvas) to provide you with a positive match, or partial match.

However, consider two images that are equal, except one of them has a brighten effect applied to it:

alt text
(source: mcburrz.com)

Inverting one of them, then adding it to the other will not result in a neutral canvas which is what we are aiming for. However, when comparing the pixels from both original images, we can definatly see a clear relationship between the two.

I haven't studied colour for some years now, and am unsure if the colour spectrum is on a linear scale, but if you determined the average factor of colour difference between both pictures, you can use this value to normalise the data before processing with this technique.

Tree Data structures

At first these don't seem to fit for the problem, but I think they could work.

You could think about extracting certain properties of an image (for example colour bins) and generate a huffman tree or similar data structure. You might be able to compare two trees for similarity. This wouldn't work well for photographic data for example with a large spectrum of colour, but cartoons or other reduced colour set images this might work.

This probably wouldn't work, but it's an idea. The trie datastructure is great at storing lexicons, for example a dictionarty. It's a prefix tree. Perhaps it's possible to build an image equivalent of a lexicon, (again I can only think of colours) to construct a trie. If you reduced say a 300x300 image into 5x5 squares, then decompose each 5x5 square into a sequence of colours you could construct a trie from the resulting data. If a 2x2 square contains:

FFFFFF|000000|FDFD44|FFFFFF

We have a fairly unique trie code that extends 24 levels, increasing/decreasing the levels (IE reducing/increasing the size of our sub square) may yield more accurate results.

Comparing trie trees should be reasonably easy, and could possible provide effective results.

More ideas

I stumbled accross an interesting paper breif about classification of satellite imagery, it outlines:

Texture measures considered are: cooccurrence matrices, gray-level differences, texture-tone analysis, features derived from the Fourier spectrum, and Gabor filters. Some Fourier features and some Gabor filters were found to be good choices, in particular when a single frequency band was used for classification.

It may be worth investigating those measurements in more detail, although some of them may not be relevant to your data set.

Other things to consider

There are probably a lot of papers on this sort of thing, so reading some of them should help although they can be very technical. It is an extremely difficult area in computing, with many fruitless hours of work spent by many people attempting to do similar things. Keeping it simple and building upon those ideas would be the best way to go. It should be a reasonably difficult challenge to create an algorithm with a better than random match rate, and to start improving on that really does start to get quite hard to achieve.

Each method would probably need to be tested and tweaked thoroughly, if you have any information about the type of picture you will be checking as well, this would be useful. For example advertisements, many of them would have text in them, so doing text recognition would be an easy and probably very reliable way of finding matches especially when combined with other solutions. As mentioned earlier, attempt to exploit common properties of your data set.

Combining alternative measurements and techniques each that can have a weighted vote (dependant on their effectiveness) would be one way you could create a system that generates more accurate results.

If employing multiple algorithms, as mentioned at the begining of this answer, one may find all the positives but have a false positive rate of 20%, it would be of interest to study the properties/strengths/weaknesses of other algorithms as another algorithm may be effective in eliminating false positives returned from another.

Be careful to not fall into attempting to complete the never ending project, good luck!

Multi-character constant warnings

If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:

-Wno-multichar

I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.

Does java have a int.tryparse that doesn't throw an exception for bad data?

Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.

Anyway, I'd just do this:

public Integer tryParse(Object obj) {
  Integer retVal;
  try {
    retVal = Integer.parseInt((String) obj);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

Open up Windows' System Properties from the control panel and hunt down the environment variables section:

  • Add a JAVA_HOME entry pointing to the directory where the JDK is installed (e.g. C:\Program Files\Java\jre6)
  • Find the Path entry and add the following onto the end ;%JAVA_HOME%\bin
  • OK the changes
  • Restart eclipse so that it is aware of the new environment

Most Java tools will now be able to find your Java installation either by using the JAVA_HOME environment variable or by looking for java.exe / javaw.exe in the Path environment variable.

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

How to list the size of each file and directory and sort by descending size in Bash?

du -s -- * | sort -n

(this willnot show hidden (.dotfiles) files)

Use du -sm for Mb units etc. I always use

du -smc -- * | sort -n

because the total line (-c) will end up at the bottom for obvious reasons :)

PS:

  • See comments for handling dotfiles
  • I frequently use e.g. 'du -smc /home// | sort -n |tail' to get a feel of where exactly the large bits are sitting

Ansible - read inventory hosts and variables to group_vars/all file

If you want to refer one host define under /etc/ansible/host in a task or role, the bellow link might help:

https://www.middlewareinventory.com/blog/ansible-get-ip-address/

Insert Picture into SQL Server 2005 Image Field using only SQL

CREATE TABLE Employees
(
    Id int,
    Name varchar(50) not null,
    Photo varbinary(max) not null
)


INSERT INTO Employees (Id, Name, Photo) 
SELECT 10, 'John', BulkColumn 
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture

Running Jupyter via command line on Windows

If you are absolutely sure that your Python library path is in your system variables (and you can find that path when you pip install Jupyter, you just have to read a bit) and you still experience "command not found or recognized" errors in Windows, you can try:

python -m notebook

For my Windows at least (Windows 10 Pro), having the python -m is the only way I can run my Python packages from command line without running into some sort of error

Fatal error in launcher: Unable to create process using ' "

or

Errno 'THIS_PROGRAM' not found

Add a list item through javascript

If you want to create a li element for each input/name, then you have to create it, with document.createElement [MDN].

Give the list the ID:

<ol id="demo"></ol>

and get a reference to it:

var list = document.getElementById('demo');

In your event handler, create a new list element with the input value as content and append to the list with Node.appendChild [MDN]:

var firstname = document.getElementById('firstname').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);

DEMO

How to reset a timer in C#?

All the timers have the equivalent of Start() and Stop() methods, except System.Threading.Timer.

So an extension method such as...

public static void Reset(this Timer timer)
{
  timer.Stop();
  timer.Start();
}

...is one way to go about it.

CSS: Set Div height to 100% - Pixels

Negative margins of course!

HTML

<div id="header">
    <h1>Header Text</h1>
</div>
<div id="wrapper">
    <div id="content">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur 
        ullamcorper velit aliquam dolor dapibus interdum sed in dolor. Phasellus 
        vel quam et quam congue sodales.
    </div>
</div>

CSS

#header
{
    height: 111px;
    margin-top: 0px;
}
#wrapper
{
    margin-bottom: 0px;
    margin-top: -111px;
    height: 100%;
    position:relative;
    z-index:-1;
}
#content
{
    margin-top: 111px;
    padding: 0.5em;
}

IOException: read failed, socket might closed - Bluetooth on Android 4.3

I ran into this problem and fixed it by closing the input and output streams before closing the socket. Now I can disconnect and connect again with no issues.

https://stackoverflow.com/a/3039807/5688612

In Kotlin:

fun disconnect() {
    bluetoothSocket.inputStream.close()
    bluetoothSocket.outputStream.close()
    bluetoothSocket.close()
}

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

Minimal runnable POSIX read + write example

Usage:

  1. get two computers on a LAN.

    For example, this will work if both computers are connected to your home router in most cases, which is how I tested it.

  2. On the server computer:

    1. Find the server local IP with ifconfig, e.g. 192.168.0.10

    2. Run:

      ./server output.tmp 12345
      
  3. On the client computer:

    printf 'ab\ncd\n' > input.tmp
    ./client input.tmp 192.168.0.10 12345
    
  4. Outcome: a file output.tmp is created on the sever computer containing 'ab\ncd\n'!

server.c

/*
Receive a file over a socket.

Saves it to output.tmp by default.

Interface:

    ./executable [<output_file> [<port>]]

Defaults:

- output_file: output.tmp
- port: 12345
*/

#define _XOPEN_SOURCE 700

#include <stdio.h>
#include <stdlib.h>

#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h> /* getprotobyname */
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char *file_path = "output.tmp";
    char buffer[BUFSIZ];
    char protoname[] = "tcp";
    int client_sockfd;
    int enable = 1;
    int filefd;
    int i;
    int server_sockfd;
    socklen_t client_len;
    ssize_t read_return;
    struct protoent *protoent;
    struct sockaddr_in client_address, server_address;
    unsigned short server_port = 12345u;

    if (argc > 1) {
        file_path = argv[1];
        if (argc > 2) {
            server_port = strtol(argv[2], NULL, 10);
        }
    }

    /* Create a socket and listen to it.. */
    protoent = getprotobyname(protoname);
    if (protoent == NULL) {
        perror("getprotobyname");
        exit(EXIT_FAILURE);
    }
    server_sockfd = socket(
        AF_INET,
        SOCK_STREAM,
        protoent->p_proto
    );
    if (server_sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    if (setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0) {
        perror("setsockopt(SO_REUSEADDR) failed");
        exit(EXIT_FAILURE);
    }
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);
    server_address.sin_port = htons(server_port);
    if (bind(
            server_sockfd,
            (struct sockaddr*)&server_address,
            sizeof(server_address)
        ) == -1
    ) {
        perror("bind");
        exit(EXIT_FAILURE);
    }
    if (listen(server_sockfd, 5) == -1) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    fprintf(stderr, "listening on port %d\n", server_port);

    while (1) {
        client_len = sizeof(client_address);
        puts("waiting for client");
        client_sockfd = accept(
            server_sockfd,
            (struct sockaddr*)&client_address,
            &client_len
        );
        filefd = open(file_path,
                O_WRONLY | O_CREAT | O_TRUNC,
                S_IRUSR | S_IWUSR);
        if (filefd == -1) {
            perror("open");
            exit(EXIT_FAILURE);
        }
        do {
            read_return = read(client_sockfd, buffer, BUFSIZ);
            if (read_return == -1) {
                perror("read");
                exit(EXIT_FAILURE);
            }
            if (write(filefd, buffer, read_return) == -1) {
                perror("write");
                exit(EXIT_FAILURE);
            }
        } while (read_return > 0);
        close(filefd);
        close(client_sockfd);
    }
    return EXIT_SUCCESS;
}

client.c

/*
Send a file over a socket.

Interface:

    ./executable [<input_path> [<sever_hostname> [<port>]]]

Defaults:

- input_path: input.tmp
- server_hostname: 127.0.0.1
- port: 12345
*/

#define _XOPEN_SOURCE 700

#include <stdio.h>
#include <stdlib.h>

#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h> /* getprotobyname */
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char protoname[] = "tcp";
    struct protoent *protoent;
    char *file_path = "input.tmp";
    char *server_hostname = "127.0.0.1";
    char *server_reply = NULL;
    char *user_input = NULL;
    char buffer[BUFSIZ];
    in_addr_t in_addr;
    in_addr_t server_addr;
    int filefd;
    int sockfd;
    ssize_t i;
    ssize_t read_return;
    struct hostent *hostent;
    struct sockaddr_in sockaddr_in;
    unsigned short server_port = 12345;

    if (argc > 1) {
        file_path = argv[1];
        if (argc > 2) {
            server_hostname = argv[2];
            if (argc > 3) {
                server_port = strtol(argv[3], NULL, 10);
            }
        }
    }

    filefd = open(file_path, O_RDONLY);
    if (filefd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    /* Get socket. */
    protoent = getprotobyname(protoname);
    if (protoent == NULL) {
        perror("getprotobyname");
        exit(EXIT_FAILURE);
    }
    sockfd = socket(AF_INET, SOCK_STREAM, protoent->p_proto);
    if (sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    /* Prepare sockaddr_in. */
    hostent = gethostbyname(server_hostname);
    if (hostent == NULL) {
        fprintf(stderr, "error: gethostbyname(\"%s\")\n", server_hostname);
        exit(EXIT_FAILURE);
    }
    in_addr = inet_addr(inet_ntoa(*(struct in_addr*)*(hostent->h_addr_list)));
    if (in_addr == (in_addr_t)-1) {
        fprintf(stderr, "error: inet_addr(\"%s\")\n", *(hostent->h_addr_list));
        exit(EXIT_FAILURE);
    }
    sockaddr_in.sin_addr.s_addr = in_addr;
    sockaddr_in.sin_family = AF_INET;
    sockaddr_in.sin_port = htons(server_port);
    /* Do the actual connection. */
    if (connect(sockfd, (struct sockaddr*)&sockaddr_in, sizeof(sockaddr_in)) == -1) {
        perror("connect");
        return EXIT_FAILURE;
    }

    while (1) {
        read_return = read(filefd, buffer, BUFSIZ);
        if (read_return == 0)
            break;
        if (read_return == -1) {
            perror("read");
            exit(EXIT_FAILURE);
        }
        /* TODO use write loop: https://stackoverflow.com/questions/24259640/writing-a-full-buffer-using-write-system-call */
        if (write(sockfd, buffer, read_return) == -1) {
            perror("write");
            exit(EXIT_FAILURE);
        }
    }
    free(user_input);
    free(server_reply);
    close(filefd);
    exit(EXIT_SUCCESS);
}

GitHub upstream.

Further comments

Possible improvements:

  • Currently output.tmp gets overwritten each time a send is done.

    This begs for the creation of a simple protocol that allows to pass a filename so that multiple files can be uploaded, e.g.: filename up to the first newline character, max filename 256 chars, and the rest until socket closure are the contents. Of course, that would require sanitation to avoid a path transversal vulnerability.

    Alternatively, we could make a server that hashes the files to find filenames, and keeps a map from original paths to hashes on disk (on a database).

  • Only one client can connect at a time.

    This is specially harmful if there are slow clients whose connections last for a long time: the slow connection halts everyone down.

    One way to work around that is to fork a process / thread for each accept, start listening again immediately, and use file lock synchronization on the files.

  • Add timeouts, and close clients if they take too long. Or else it would be easy to do a DoS.

    poll or select are some options: How to implement a timeout in read function call?

A simple HTTP wget implementation is shown at: How to make an HTTP get request in C without libcurl?

Tested on Ubuntu 15.10.

How to paste into a terminal?

Mostly likely middle click your mouse.

Or try Shift + Insert.

It all depends on terminal used and X11-config for mouse.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Firebase Storage How to store and Retrieve images

I ended up storing the images in base64 format myself. I translate them from their base64 value when called back from firebase.

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

Display current time in 12 hour format with AM/PM

use "hh:mm a" instead of "HH:mm a". Here hh for 12 hour format and HH for 24 hour format.

Live Demo

How to get last items of a list in Python?

Here are several options for getting the "tail" items of an iterable:

Given

n = 9
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Desired Output

[2, 3, 4, 5, 6, 7, 8, 9, 10]

Code

We get the latter output using any of the following options:

from collections import deque
import itertools

import more_itertools


# A: Slicing
iterable[-n:]


# B: Implement an itertools recipe
def tail(n, iterable):
    """Return an iterator over the last *n* items of *iterable*.

        >>> t = tail(3, 'ABCDEFG')
        >>> list(t)
        ['E', 'F', 'G']

    """
    return iter(deque(iterable, maxlen=n))
list(tail(n, iterable))


# C: Use an implemented recipe, via more_itertools
list(more_itertools.tail(n, iterable))


# D: islice, via itertools
list(itertools.islice(iterable, len(iterable)-n, None))


# E: Negative islice, via more_itertools
list(more_itertools.islice_extended(iterable, -n, None))

Details

  • A. Traditional Python slicing is inherent to the language. This option works with sequences such as strings, lists and tuples. However, this kind of slicing does not work on iterators, e.g. iter(iterable).
  • B. An itertools recipe. It is generalized to work on any iterable and resolves the iterator issue in the last solution. This recipe must be implemented manually as it is not officially included in the itertools module.
  • C. Many recipes, including the latter tool (B), have been conveniently implemented in third party packages. Installing and importing these these libraries obviates manual implementation. One of these libraries is called more_itertools (install via > pip install more-itertools); see more_itertools.tail.
  • D. A member of the itertools library. Note, itertools.islice does not support negative slicing.
  • E. Another tool is implemented in more_itertools that generalizes itertools.islice to support negative slicing; see more_itertools.islice_extended.

Which one do I use?

It depends. In most cases, slicing (option A, as mentioned in other answers) is most simple option as it built into the language and supports most iterable types. For more general iterators, use any of the remaining options. Note, options C and E require installing a third-party library, which some users may find useful.

How to concatenate multiple lines of output to one line?

Here is another simple method using awk:

# cat > file.txt
a
b
c

# cat file.txt | awk '{ printf("%s ", $0) }'
a b c

Also, if your file has columns, this gives an easy way to concatenate only certain columns:

# cat > cols.txt
a b c
d e f

# cat cols.txt | awk '{ printf("%s ", $2) }'
b e

NodeJS - Error installing with NPM

As commented below you may not need to install VS on windows, check this out

https://github.com/nodejs/node-gyp/issues/629#issuecomment-153196245

UPDATED 02/2016

Some npm plugins need node-gyp to be installed.

However, node-gyp has it's own dependencies (from the github page):

enter image description here

UPDATED 09/2016

If you're using Windows you can now install all node-gyp dependencies with single command (NOTE: Run As Admin in Windows PowerShell):

 $ npm install --global --production windows-build-tools

and then install the package

 $ npm install --global node-gyp

UPDATED 06/2018

https://github.com/nodejs/node-gyp/issues/809#issuecomment-155019383

Delete your $HOME/.node-gyp directory and try again.

See full documentation here: node-gyp

Filtering collections in C#

Here is a code block / example of some list filtering using three different methods that I put together to show Lambdas and LINQ based list filtering.

#region List Filtering

static void Main(string[] args)
{
    ListFiltering();
    Console.ReadLine();
}

private static void ListFiltering()
{
    var PersonList = new List<Person>();

    PersonList.Add(new Person() { Age = 23, Name = "Jon", Gender = "M" }); //Non-Constructor Object Property Initialization
    PersonList.Add(new Person() { Age = 24, Name = "Jack", Gender = "M" });
    PersonList.Add(new Person() { Age = 29, Name = "Billy", Gender = "M" });

    PersonList.Add(new Person() { Age = 33, Name = "Bob", Gender = "M" });
    PersonList.Add(new Person() { Age = 45, Name = "Frank", Gender = "M" });

    PersonList.Add(new Person() { Age = 24, Name = "Anna", Gender = "F" });
    PersonList.Add(new Person() { Age = 29, Name = "Sue", Gender = "F" });
    PersonList.Add(new Person() { Age = 35, Name = "Sally", Gender = "F" });
    PersonList.Add(new Person() { Age = 36, Name = "Jane", Gender = "F" });
    PersonList.Add(new Person() { Age = 42, Name = "Jill", Gender = "F" });

    //Logic: Show me all males that are less than 30 years old.

    Console.WriteLine("");
    //Iterative Method
    Console.WriteLine("List Filter Normal Way:");
    foreach (var p in PersonList)
        if (p.Gender == "M" && p.Age < 30)
            Console.WriteLine(p.Name + " is " + p.Age);

    Console.WriteLine("");
    //Lambda Filter Method
    Console.WriteLine("List Filter Lambda Way");
    foreach (var p in PersonList.Where(p => (p.Gender == "M" && p.Age < 30))) //.Where is an extension method
        Console.WriteLine(p.Name + " is " + p.Age);

    Console.WriteLine("");
    //LINQ Query Method
    Console.WriteLine("List Filter LINQ Way:");
    foreach (var v in from p in PersonList
                      where p.Gender == "M" && p.Age < 30
                      select new { p.Name, p.Age })
        Console.WriteLine(v.Name + " is " + v.Age);
}

private class Person
{
    public Person() { }
    public int Age { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
}

#endregion

How to center horizontal table-cell

Sometimes you have things other than text inside a table cell that you'd like to be horizontally centered. In order to do this, first set up some css...

<style>
    div.centered {
        margin: auto;
        width: 100%;
        display: flex;
        justify-content: center;
    }
</style>

Then declare a div with class="centered" inside each table cell you want centered.

<td>
    <div class="centered">
        Anything: text, controls, etc... will be horizontally centered.
    </div>
</td>

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

Java Long primitive type maximum limit

Long.MAX_VALUE is 9,223,372,036,854,775,807.

If you were executing your function once per nanosecond, it would still take over 292 years to encounter this situation according to this source.

When that happens, it'll just wrap around to Long.MIN_VALUE, or -9,223,372,036,854,775,808 as others have said.

Truncating long strings with CSS: feasible yet?

Another solution to the problem could be the following set of CSS rules:

.ellipsis{
 white-space:nowrap;
 overflow:hidden;
}

.ellipsis:after{
  content:'...';
}

The only drawback with the above CSS is that it would add the "..." irrespective of whether the text-overflows the container or not. Still, if you have a case where you have a bunch of elements and are sure that content will overflow, this one would be a simpler set of rules.

My two cents. Hats off to the original technique by Justin Maxwell

How to generate serial version UID in Intellij

with in the code editor, Open the class you want to create the UID for , Right click -> Generate -> SerialVersionUID. You may need to have the GenerateSerialVersionUID plugin installed for this to work.

How to send email in ASP.NET C#

Try using this code instead. Note: In the "from address" give your correct email id and password.

protected void btn_send_Click(object sender, EventArgs e)
{

    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
    mail.To.Add("to gmail address");
    mail.From = new MailAddress("from gmail address", "Email head", System.Text.Encoding.UTF8);
    mail.Subject = "This mail is send from asp.net application";
    mail.SubjectEncoding = System.Text.Encoding.UTF8;
    mail.Body = "This is Email Body Text";
    mail.BodyEncoding = System.Text.Encoding.UTF8;
    mail.IsBodyHtml = true;
    mail.Priority = MailPriority.High;
    SmtpClient client = new SmtpClient();
    client.Credentials = new System.Net.NetworkCredential("from gmail address", "your gmail account password");
    client.Port = 587;
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true;
    try
    {
        client.Send(mail);
        Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendMail.aspx';}</script>");
    }
    catch (Exception ex)
    {
        Exception ex2 = ex;
        string errorMessage = string.Empty;
        while (ex2 != null)
        {
            errorMessage += ex2.ToString();
            ex2 = ex2.InnerException;
        }
        Page.RegisterStartupScript("UserMsg", "<script>alert('Sending Failed...');if(alert){ window.location='SendMail.aspx';}</script>");
    }
}

How to extract epoch from LocalDate and LocalDateTime?

This is one way without using time a zone:

LocalDateTime now = LocalDateTime.now();
long epoch = (now.getLong(ChronoField.EPOCH_DAY) * 86400000) + now.getLong(ChronoField.MILLI_OF_DAY);

How get all values in a column using PHP?

I would use a mysqli connection to connect to the database. Here is an example:

$connection = new mysqli("127.0.0.1", "username", "password", "database_name", 3306);

The next step is to select the information. In your case I would do:

$query = $connection->query("SELECT `names` FROM `Customers`;");

And finally we make an array from all these names by typing:

$array = Array();
while($result = $query->fetch_assoc()){
    $array[] = $result['names'];
}

print_r($array);

So what I've done in this code: I selected all names from the table using a mysql query. Next I use a while loop to check if the $query has a next value. If so the while loop continues and adds that value to the array '$array'. Else the loop stops. And finally I print the array using the 'print_r' method so you can see it all works. I hope this was helpful.

what is trailing whitespace and how can I handle this?

Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.

In your posted question, there is one extra space after try:, and there are 12 extra spaces after pass:

>>> post_text = '''\
...             if self.tagname and self.tagname2 in list1:
...                 try: 
...                     question = soup.find("div", "post-text")
...                     title = soup.find("a", "question-hyperlink")
...                     self.list2.append(str(title)+str(question)+url)
...                     current += 1
...                 except AttributeError:
...                     pass            
...             logging.info("%s questions passed, %s questions \
...                 collected" % (count, current))
...             count += 1
...         return self.list2
... '''
>>> for line in post_text.splitlines():
...     if line.rstrip() != line:
...         print(repr(line))
... 
'                try: '
'                    pass            '

See where the strings end? There are spaces before the lines (indentation), but also spaces after.

Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.

How to get absolute value from double - c-language

I have found that using cabs(double), cabsf(float), cabsl(long double), __cabsf(float), __cabs(double), __cabsf(long double) is the solution

Best way to implement keyboard shortcuts in a Windows Forms application?

If you have a menu then changing ShortcutKeys property of the ToolStripMenuItem should do the trick.

If not, you could create one and set its visible property to false.

Why dividing two integers doesn't get a float?

Dividing two integers will result in an integer (whole number) result.

You need to cast one number as a float, or add a decimal to one of the numbers, like a/350.0.

Unexpected token }

You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

REST API - file (ie images) processing - best practices

There's no easy solution. Each way has their pros and cons . But the canonical way is using the first option: multipart/form-data. As W3 recommendation guide says

The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

We aren't sending forms,really, but the implicit principle still applies. Using base64 as a binary representation, is incorrect because you're using the incorrect tool for accomplish your goal, in other hand, the second option forces your API clients to do more job in order to consume your API service. You should do the hard work in the server side in order to supply an easy-to-consume API. The first option is not easy to debug, but when you do it, it probably never changes.

Using multipart/form-data you're sticked with the REST/http philosophy. You can view an answer to similar question here.

Another option if mixing the alternatives, you can use multipart/form-data but instead of send every value separate, you can send a value named payload with the json payload inside it. (I tried this approach using ASP.NET WebAPI 2 and works fine).

Volatile boolean vs AtomicBoolean

AtomicBoolean has methods that perform their compound operations atomically and without having to use a synchronized block. On the other hand, volatile boolean can only perform compound operations if done so within a synchronized block.

The memory effects of reading/writing to volatile boolean are identical to the get and set methods of AtomicBoolean respectively.

For example the compareAndSet method will atomically perform the following (without a synchronized block):

if (value == expectedValue) {
    value = newValue;
    return true;
} else {
    return false;
}

Hence, the compareAndSet method will let you write code that is guaranteed to execute only once, even when called from multiple threads. For example:

final AtomicBoolean isJobDone = new AtomicBoolean(false);

...

if (isJobDone.compareAndSet(false, true)) {
    listener.notifyJobDone();
}

Is guaranteed to only notify the listener once (assuming no other thread sets the AtomicBoolean back to false again after it being set to true).

Calling constructors in c++ without new

In append to JaredPar answer

1-usual ctor, 2nd-function-like-ctor with temporary object.

Compile this source somewhere here http://melpon.org/wandbox/ with different compilers

// turn off rvo for clang, gcc with '-fno-elide-constructors'

#include <stdio.h>
class Thing {
public:
    Thing(const char*){puts(__FUNCTION__ );}
    Thing(const Thing&){puts(__FUNCTION__ );}   
    ~Thing(){puts(__FUNCTION__);}
};
int main(int /*argc*/, const char** /*argv*/) {
    Thing myThing = Thing("asdf");
}

And you will see the result.

From ISO/IEC 14882 2003-10-15

8.5, part 12

Your 1st,2nd construction are called direct-initialization

12.1, part 13

A functional notation type conversion (5.2.3) can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ... An object created in this way is unnamed. [Note: 12.2 describes the lifetime of temporary objects. ] [Note: explicit constructor calls do not yield lvalues, see 3.10. ]


Where to read about RVO:

12 Special member functions / 12.8 Copying class objects/ Part 15

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.

Turn off it with compiler flag from comment to view such copy-behavior)

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

If you are like me, and are staring at this thread thinking "But I'm not trying to add a component, I am trying to add a guard/service/pipe, etc." then the issue is likely that you have added the wrong type to a routing path. That is what I did. I accidentally added a guard to the component: section of a path instead of the canActivate: section. I love IDE autocomplete but you have to slow down a bit and pay attention. If you absolutely can't find it, do a global search for the name it is complaining about and look at every usage to make sure you didn't slip-up with a name.

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 convert from int to string in objective c: example code

The commented out version is the more correct way to do this.

If you use the == operator on strings, you're comparing the strings' addresses (where they're allocated in memory) rather than the values of the strings. This is very occasional useful (it indicates you have the exact same string object), but 99% of the time you want to compare the values, which you do like so:

if([myT isEqualToString:@"10"] || [myT isEqualToString:@"11"] || [myT isEqualToString:@"12"])

Print a variable in hexadecimal in Python

Another answer with later print/format style is:

res[0]=12
res[1]=23
print("my num is 0x{0:02x}{1:02x}".format(res[0],res[1]))

How do you round a floating point number in Perl?

loads of reading documentation on how to round numbers, many experts suggest writing your own rounding routines, as the 'canned' version provided with your language may not be precise enough, or contain errors. i imagine, however, they're talking many decimal places not just one, two, or three. with that in mind, here is my solution (although not EXACTLY as requested as my needs are to display dollars - the process is not much different, though).

sub asDollars($) {
  my ($cost) = @_;
  my $rv = 0;

  my $negative = 0;
  if ($cost =~ /^-/) {
    $negative = 1;
    $cost =~ s/^-//;
  }

  my @cost = split(/\./, $cost);

  # let's get the first 3 digits of $cost[1]
  my ($digit1, $digit2, $digit3) = split("", $cost[1]);
  # now, is $digit3 >= 5?
  # if yes, plus one to $digit2.
  # is $digit2 > 9 now?
  # if yes, $digit2 = 0, $digit1++
  # is $digit1 > 9 now??
  # if yes, $digit1 = 0, $cost[0]++
  if ($digit3 >= 5) {
    $digit3 = 0;
    $digit2++;
    if ($digit2 > 9) {
      $digit2 = 0;
      $digit1++;
      if ($digit1 > 9) {
        $digit1 = 0;
        $cost[0]++;
      }
    }
  }
  $cost[1] = $digit1 . $digit2;
  if ($digit1 ne "0" and $cost[1] < 10) { $cost[1] .= "0"; }

  # and pretty up the left of decimal
  if ($cost[0] > 999) { $cost[0] = commafied($cost[0]); }

  $rv = join(".", @cost);

  if ($negative) { $rv = "-" . $rv; }

  return $rv;
}

sub commafied($) {
  #*
  # to insert commas before every 3rd number (from the right)
  # positive or negative numbers
  #*
  my ($num) = @_; # the number to insert commas into!

  my $negative = 0;
  if ($num =~ /^-/) {
    $negative = 1;
    $num =~ s/^-//;
  }
  $num =~ s/^(0)*//; # strip LEADING zeros from given number!
  $num =~ s/0/-/g; # convert zeros to dashes because ... computers!

  if ($num) {
    my @digits = reverse split("", $num);
    $num = "";

    for (my $i = 0; $i < @digits; $i += 3) {
      $num .= $digits[$i];
      if ($digits[$i+1]) { $num .= $digits[$i+1]; }
      if ($digits[$i+2]) { $num .= $digits[$i+2]; }
      if ($i < (@digits - 3)) { $num .= ","; }
      if ($i >= @digits) { last; }
    }

    #$num =~ s/,$//;
    $num = join("", reverse split("", $num));
    $num =~ s/-/0/g;
  }

  if ($negative) { $num = "-" . $num; }

  return $num; # a number with commas added
  #usage: my $prettyNum = commafied(1234567890);
}

How to check if mod_rewrite is enabled in php?

This is my current method of checking if Mod_rewrite enabled for both Apache and IIS

/**
 * --------------------------------------------------------------
 *  MOD REWRITE CHECK
 * --------------------------------------------------------------
 *                                        - By A H Abid
 * Define Constant for MOD REWRITE
 * 
 * Check if server allows MOD REWRITE. Checks for both 
 * Apache and IIS.
 * 
 */
if( function_exists('apache_get_modules') && in_array('mod_rewrite',apache_get_modules()) )
    $mod_rewrite = TRUE;
elseif( isset($_SERVER['IIS_UrlRewriteModule']) )
    $mod_rewrite = TRUE;
else
    $mod_rewrite = FALSE;
define('MOD_REWRITE', $mod_rewrite);

It works in my local machine and also worked in my IIS based webhost. However, on a particular apache server, it didn't worked for Apache as the apache_get_modules() was disabled but the mod_rewrite was enable in that server.

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

This link has the break down

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property

assign implies __unsafe_unretained ownership.

copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.

retain implies __strong ownership.

strong implies __strong ownership.

unsafe_unretained implies __unsafe_unretained ownership.

weak implies __weak ownership.

Convert datatable to JSON in C#

This has similar approach to the accepted answer, but uses LINQ to convert datatable to list in a single line of code.

//convert datatable to list using LINQ. Input datatable is "dt", returning list of "name:value" tuples
var lst = dt.AsEnumerable()
    .Select(r => r.Table.Columns.Cast<DataColumn>()
            .Select(c => new KeyValuePair<string, object>(c.ColumnName, r[c.Ordinal])
           ).ToDictionary(z=>z.Key,z=>z.Value)
    ).ToList();
//now serialize it
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Serialize(lst);

This is an incredibly useful way to enumerate a datatable, which would normally take a ton of coding! Here are some variations:

//convert to list with array of values for each row
var list1 = dt.AsEnumerable().Select(r => r.ItemArray.ToList()).ToList();

//convert to list of first column values only
var list2 = dt.AsEnumerable().Select(r => r.ItemArray[0]).ToList();

// parse a datatable with conditions and get CSV string
string MalesOver21 = string.Join(",",
    dt.AsEnumerable()
      .Where(r => r["GENDER"].ToString()=="M" && r.Field<int>("AGE")>21)
      .Select(r => r.Field<string>("FULLNAME"))
 );

This is off topic to the original question but for completeness sake, I'd mention that if you just want to filter out rows from an existing datatable, See this answer

Squash the first two commits in Git?

You could use rebase interactive to modify the last two commits before they've been pushed to a remote

git rebase HEAD^^ -i

Select every Nth element in CSS

Try this

div:nth-child(4n+4)

socket programming multiple client to one server

Here is code for Multiple Client to one Server Working Fine .. Give it a try :)

Server.java:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

class Multi extends Thread{
private Socket s=null;
DataInputStream infromClient;
Multi() throws IOException{


}
Multi(Socket s) throws IOException{
    this.s=s;
    infromClient = new DataInputStream(s.getInputStream());
}
public void run(){  

    String SQL=new String();
    try {
        SQL = infromClient.readUTF();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Query: " + SQL); 
    try {
        System.out.println("Socket Closing");
        s.close();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
       }
   }  
}
public class Server {

public static void main(String args[]) throws IOException, 
InterruptedException{   

    while(true){
        ServerSocket ss=new ServerSocket(11111);
        System.out.println("Server is Awaiting"); 
        Socket s=ss.accept();
        Multi t=new Multi(s);
        t.start();

        Thread.sleep(2000);
        ss.close();
    }    




    }   
}

Client1.java:

 import java.io.DataOutputStream;
 import java.io.ObjectInputStream;
 import java.net.Socket;


public class client1 {
   public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I  am  client 1";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
}

Client2.java

import java.io.DataOutputStream; 
import java.net.Socket;


public class client2 {
    public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I am  Client 2";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
 }

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

Powershell send-mailmessage - email to multiple recipients

$recipients = "Marcel <[email protected]>, Marcelt <[email protected]>"

is type of string you need pass to send-mailmessage a string[] type (an array):

[string[]]$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

I think that not casting to string[] do the job for the coercing rules of powershell:

$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

is object[] type but can do the same job.

ASP.NET Core - Swashbuckle not creating swagger.json file

I am moving my comment to an answer since it appears to be helpful.


To avoid issues with IIS aliases, remove /swagger/ from the URL path. It should look like this:

app.UseSwaggerUI(c => { c.SwaggerEndpoint("v1/swagger.json", "API name"); });

PHP - warning - Undefined property: stdClass - fix?

Error control operator

In case the warning is expected you can use the error control operator @ to suppress thrown messages.

$role_arr = getRole(@$response->records);

While this reduces clutter in your code you should use it with caution as it may make debugging future errors harder. An example where using @ may be useful is when creating an object from user input and running it through a validation method before using it in further logic.


Null Coalesce Operator

Another alternative is using the isset_ternary operator ??. This allows you to avoid warnings and assign default value in a short one line fashion.

$role_arr = getRole($response->records ?? null);

What is the proper way to check if a string is empty in Perl?

For string comparisons in Perl, use eq or ne:

if ($str eq "")
{
  // ...
}

The == and != operators are numeric comparison operators. They will attempt to convert both operands to integers before comparing them.

See the perlop man page for more information.

MySQL query finding values in a comma separated string

This will work for sure, and I actually tried it out:

lwdba@localhost (DB test) :: DROP TABLE IF EXISTS shirts;
Query OK, 0 rows affected (0.08 sec)

lwdba@localhost (DB test) :: CREATE TABLE shirts
    -> (<BR>
    -> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> ticketnumber INT,
    -> colors VARCHAR(30)
    -> );<BR>
Query OK, 0 rows affected (0.19 sec)

lwdba@localhost (DB test) :: INSERT INTO shirts (ticketnumber,colors) VALUES
    -> (32423,'1,2,5,12,15'),
    -> (32424,'1,5,12,15,30'),
    -> (32425,'2,5,11,15,28'),
    -> (32426,'1,2,7,12,15'),
    -> (32427,'2,4,8,12,15');
Query OK, 5 rows affected (0.06 sec)
Records: 5  Duplicates: 0  Warnings: 0

lwdba@localhost (DB test) :: SELECT * FROM shirts WHERE LOCATE(CONCAT(',', 1 ,','),CONCAT(',',colors,',')) > 0;
+----+--------------+--------------+
| id | ticketnumber | colors       |
+----+--------------+--------------+
|  1 |        32423 | 1,2,5,12,15  |
|  2 |        32424 | 1,5,12,15,30 |
|  4 |        32426 | 1,2,7,12,15  |
+----+--------------+--------------+
3 rows in set (0.00 sec)

Give it a Try !!!

Open Source HTML to PDF Renderer with Full CSS Support

It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.

How to clear browsing history using JavaScript?

No,that would be a security issue.


However, it's possible to clear the history in JavaScript within a Google chrome extension. chrome.history.deleteAll().
Use

window.location.replace('pageName.html');

similar behavior as an HTTP redirect

Read How to redirect to another webpage in JavaScript/jQuery?

fatal: git-write-tree: error building trees

maybe there are some unmerged paths in your git repository that you have to resolve before stashing.

Easiest way to convert int to string in C++

Picking up a discussion with @v.oddou a couple of years later, C++17 has finally delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro uglyness.

// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
    std::ostringstream sstr;
    // fold expression
    ( sstr << std::dec << ... << args );
    return sstr.str();
}

Usage:

int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );

Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );

Original answer:

Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:

#include <sstream>

#define SSTR( x ) static_cast< std::ostringstream & >( \
        ( std::ostringstream() << std::dec << x ) ).str()

Usage is as easy as could be:

int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );

Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );

The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast<>); both these other solutions have a better performance though.

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

How to implement an android:background that doesn't stretch?

I had a background image, not big in size, but with weird dimensions - therefore the stretching and bad performance. I made a method with parameters Context, a View and a drawable ID(int) that will match the device screen size. Use this in e.g a Fragments onCreateView to set the background.

public void setBackground(Context context, View view, int drawableId){
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),drawableId);

    bitmap = Bitmap.createScaledBitmap(bitmap, Resources.getSystem().
             getDisplayMetrics().widthPixels,
             Resources.getSystem().getDisplayMetrics().heightPixels,
             true);

    BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), 
                                    bitmap);

    view.setBackground(bitmapDrawable);
}

Could not reserve enough space for object heap to start JVM

I had the same problem when using a 32 bit version of java in a 64 bit environment. When using 64 java in a 64 OS it was ok.

Laravel 5.2 - pluck() method returns array

I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();

it gives back an array of ids [50,2,3] and this is the whole query I used:

   $article_tags = DB::table('tags')
    ->join('taggables', function ($join) use ($id) {
        $join->on('tags.id', '=', 'taggables.tag_id');
        $join->where([
            ['taggable_id', '=', $id],
            ['taggable_type','=','article']
        ]);
    })->select('tags.id')->get()->pluck('id')->toArray();

Cookies on localhost with explicit domain

There is an issue on Chromium open since 2011, that if you are explicitly setting the domain as 'localhost', you should set it as false or undefined.

Jquery: How to check if the element has certain css class/style

Question is asking for two different things:

  1. An element has certain class
  2. An element has certain style.

Second question has been already answered. For the first one, I would do it this way:

if($("#someElement").is(".test")){
    // Has class test assigned, eventually combined with other classes
}
else{
    // Does not have it
}

What "wmic bios get serialnumber" actually retrieves?

run cmd

Enter wmic baseboard get product,version,serialnumber

Press the enter key. The result you see under serial number column is your motherboard serial number

How do I use JDK 7 on Mac OSX?

What worked for me on Lion was installing the JDK7_u17 from Oracle, then editing ~/.bash_profile to include: export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home

Simple file write function in C++

There are two solutions to this. You can either place the method above the method that calls it:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

int main()
{
    writeFile();
}

Or declare a prototype:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int writeFile();

int main()
{
    writeFile();
}

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

How do you uninstall the package manager "pip", if installed from source?

I was using above command but it was not working. This command worked for me:

python -m pip uninstall pip setuptools

How do I detect what .NET Framework versions and service packs are installed?

Enumerate the subkeys of HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP. Each subkey is a .NET version. It should have Install=1 value if it's present on the machine, an SP value that shows the service pack and an MSI=1 value if it was installed using an MSI. (.NET 2.0 on Windows Vista doesn't have the last one for example, as it is part of the OS.)

Unable to import path from django.urls

It look's as if you forgot to activate you virtual environment try running python3 -m venv venv or if you already have virtual environment set up try to activate it by running source venv/bin/activate

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

There are still no native methods that perform the requested task.

Here is the code that I am using. It mimics the behaviour of String.prototype.indexOf and String.prototype.lastIndexOf methods but they also accept a RegExp as the search argument in addition to a string representing the value to search for.

Yes it is quite long as an answer goes as it tries to follow current standards as close as possible and of course contains a reasonable amount of JSDOC comments. However, once minified, the code is only 2.27k and once gzipped for transmission it is only 1023 bytes.

The 2 methods that this adds to String.prototype (using Object.defineProperty where available) are:

  1. searchOf
  2. searchLastOf

It passes all the tests that the OP posted and additionally I have tested the routines quite thoroughly in my daily usage, and have attempted to be sure that they work across multiple environments, but feedback/issues are always welcome.

_x000D_
_x000D_
/*jslint maxlen:80, browser:true */_x000D_
_x000D_
/*_x000D_
 * Properties used by searchOf and searchLastOf implementation._x000D_
 */_x000D_
_x000D_
/*property_x000D_
    MAX_SAFE_INTEGER, abs, add, apply, call, configurable, defineProperty,_x000D_
    enumerable, exec, floor, global, hasOwnProperty, ignoreCase, index,_x000D_
    lastIndex, lastIndexOf, length, max, min, multiline, pow, prototype,_x000D_
    remove, replace, searchLastOf, searchOf, source, toString, value, writable_x000D_
*/_x000D_
_x000D_
/*_x000D_
 * Properties used in the testing of searchOf and searchLastOf implimentation._x000D_
 */_x000D_
_x000D_
/*property_x000D_
    appendChild, createTextNode, getElementById, indexOf, lastIndexOf, length,_x000D_
    searchLastOf, searchOf, unshift_x000D_
*/_x000D_
_x000D_
(function () {_x000D_
    'use strict';_x000D_
_x000D_
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1,_x000D_
        getNativeFlags = new RegExp('\\/([a-z]*)$', 'i'),_x000D_
        clipDups = new RegExp('([\\s\\S])(?=[\\s\\S]*\\1)', 'g'),_x000D_
        pToString = Object.prototype.toString,_x000D_
        pHasOwn = Object.prototype.hasOwnProperty,_x000D_
        stringTagRegExp;_x000D_
_x000D_
    /**_x000D_
     * Defines a new property directly on an object, or modifies an existing_x000D_
     * property on an object, and returns the object._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {Object} object_x000D_
     * @param {string} property_x000D_
     * @param {Object} descriptor_x000D_
     * @returns {Object}_x000D_
     * @see https://goo.gl/CZnEqg_x000D_
     */_x000D_
    function $defineProperty(object, property, descriptor) {_x000D_
        if (Object.defineProperty) {_x000D_
            Object.defineProperty(object, property, descriptor);_x000D_
        } else {_x000D_
            object[property] = descriptor.value;_x000D_
        }_x000D_
_x000D_
        return object;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operands are strictly equal with no type conversion._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} a_x000D_
     * @param {*} b_x000D_
     * @returns {boolean}_x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4_x000D_
     */_x000D_
    function $strictEqual(a, b) {_x000D_
        return a === b;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operand inputArg is undefined._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @returns {boolean}_x000D_
     */_x000D_
    function $isUndefined(inputArg) {_x000D_
        return $strictEqual(typeof inputArg, 'undefined');_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Provides a string representation of the supplied object in the form_x000D_
     * "[object type]", where type is the object type._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object for which a class string represntation_x000D_
     *                     is required._x000D_
     * @returns {string} A string value of the form "[object type]"._x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2_x000D_
     */_x000D_
    function $toStringTag(inputArg) {_x000D_
        var val;_x000D_
        if (inputArg === null) {_x000D_
            val = '[object Null]';_x000D_
        } else if ($isUndefined(inputArg)) {_x000D_
            val = '[object Undefined]';_x000D_
        } else {_x000D_
            val = pToString.call(inputArg);_x000D_
        }_x000D_
_x000D_
        return val;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The string tag representation of a RegExp object._x000D_
     *_x000D_
     * @private_x000D_
     * @type {string}_x000D_
     */_x000D_
    stringTagRegExp = $toStringTag(getNativeFlags);_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operand inputArg is a RegExp._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @returns {boolean}_x000D_
     */_x000D_
    function $isRegExp(inputArg) {_x000D_
        return $toStringTag(inputArg) === stringTagRegExp &&_x000D_
                pHasOwn.call(inputArg, 'ignoreCase') &&_x000D_
                typeof inputArg.ignoreCase === 'boolean' &&_x000D_
                pHasOwn.call(inputArg, 'global') &&_x000D_
                typeof inputArg.global === 'boolean' &&_x000D_
                pHasOwn.call(inputArg, 'multiline') &&_x000D_
                typeof inputArg.multiline === 'boolean' &&_x000D_
                pHasOwn.call(inputArg, 'source') &&_x000D_
                typeof inputArg.source === 'string';_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation throws an error if its argument is a value that_x000D_
     * cannot be converted to an Object, otherwise returns the argument._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object to be tested._x000D_
     * @throws {TypeError} If inputArg is null or undefined._x000D_
     * @returns {*} The inputArg if coercible._x000D_
     * @see https://goo.gl/5GcmVq_x000D_
     */_x000D_
    function $requireObjectCoercible(inputArg) {_x000D_
        var errStr;_x000D_
_x000D_
        if (inputArg === null || $isUndefined(inputArg)) {_x000D_
            errStr = 'Cannot convert argument to object: ' + inputArg;_x000D_
            throw new TypeError(errStr);_x000D_
        }_x000D_
_x000D_
        return inputArg;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation converts its argument to a value of type string_x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @returns {string}_x000D_
     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring_x000D_
     */_x000D_
    function $toString(inputArg) {_x000D_
        var type,_x000D_
            val;_x000D_
_x000D_
        if (inputArg === null) {_x000D_
            val = 'null';_x000D_
        } else {_x000D_
            type = typeof inputArg;_x000D_
            if (type === 'string') {_x000D_
                val = inputArg;_x000D_
            } else if (type === 'undefined') {_x000D_
                val = type;_x000D_
            } else {_x000D_
                if (type === 'symbol') {_x000D_
                    throw new TypeError('Cannot convert symbol to string');_x000D_
                }_x000D_
_x000D_
                val = String(inputArg);_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return val;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns a string only if the arguments is coercible otherwise throws an_x000D_
     * error._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @throws {TypeError} If inputArg is null or undefined._x000D_
     * @returns {string}_x000D_
     */_x000D_
    function $onlyCoercibleToString(inputArg) {_x000D_
        return $toString($requireObjectCoercible(inputArg));_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The function evaluates the passed value and converts it to an integer._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object to be converted to an integer._x000D_
     * @returns {number} If the target value is NaN, null or undefined, 0 is_x000D_
     *                   returned. If the target value is false, 0 is returned_x000D_
     *                   and if true, 1 is returned._x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.4_x000D_
     */_x000D_
    function $toInteger(inputArg) {_x000D_
        var number = +inputArg,_x000D_
            val = 0;_x000D_
_x000D_
        if ($strictEqual(number, number)) {_x000D_
            if (!number || number === Infinity || number === -Infinity) {_x000D_
                val = number;_x000D_
            } else {_x000D_
                val = (number > 0 || -1) * Math.floor(Math.abs(number));_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return val;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Copies a regex object. Allows adding and removing native flags while_x000D_
     * copying the regex._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {RegExp} regex Regex to copy._x000D_
     * @param {Object} [options] Allows specifying native flags to add or_x000D_
     *                           remove while copying the regex._x000D_
     * @returns {RegExp} Copy of the provided regex, possibly with modified_x000D_
     *                   flags._x000D_
     */_x000D_
    function $copyRegExp(regex, options) {_x000D_
        var flags,_x000D_
            opts,_x000D_
            rx;_x000D_
_x000D_
        if (options !== null && typeof options === 'object') {_x000D_
            opts = options;_x000D_
        } else {_x000D_
            opts = {};_x000D_
        }_x000D_
_x000D_
        // Get native flags in use_x000D_
        flags = getNativeFlags.exec($toString(regex))[1];_x000D_
        flags = $onlyCoercibleToString(flags);_x000D_
        if (opts.add) {_x000D_
            flags += opts.add;_x000D_
            flags = flags.replace(clipDups, '');_x000D_
        }_x000D_
_x000D_
        if (opts.remove) {_x000D_
            // Would need to escape `options.remove` if this was public_x000D_
            rx = new RegExp('[' + opts.remove + ']+', 'g');_x000D_
            flags = flags.replace(rx, '');_x000D_
        }_x000D_
_x000D_
        return new RegExp(regex.source, flags);_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation ToLength converts its argument to an integer_x000D_
     * suitable for use as the length of an array-like object._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object to be converted to a length._x000D_
     * @returns {number} If len <= +0 then +0 else if len is +INFINITY then_x000D_
     *                   2^53-1 else min(len, 2^53-1)._x000D_
     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength_x000D_
     */_x000D_
    function $toLength(inputArg) {_x000D_
        return Math.min(Math.max($toInteger(inputArg), 0), MAX_SAFE_INTEGER);_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Copies a regex object so that it is suitable for use with searchOf and_x000D_
     * searchLastOf methods._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {RegExp} regex Regex to copy._x000D_
     * @returns {RegExp}_x000D_
     */_x000D_
    function $toSearchRegExp(regex) {_x000D_
        return $copyRegExp(regex, {_x000D_
            add: 'g',_x000D_
            remove: 'y'_x000D_
        });_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operand inputArg is a member of one of the types_x000D_
     * Undefined, Null, Boolean, Number, Symbol, or String._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @returns {boolean}_x000D_
     * @see https://goo.gl/W68ywJ_x000D_
     * @see https://goo.gl/ev7881_x000D_
     */_x000D_
    function $isPrimitive(inputArg) {_x000D_
        var type = typeof inputArg;_x000D_
_x000D_
        return type === 'undefined' ||_x000D_
                inputArg === null ||_x000D_
                type === 'boolean' ||_x000D_
                type === 'string' ||_x000D_
                type === 'number' ||_x000D_
                type === 'symbol';_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation converts its argument to a value of type Object_x000D_
     * but fixes some environment bugs._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The argument to be converted to an object._x000D_
     * @throws {TypeError} If inputArg is not coercible to an object._x000D_
     * @returns {Object} Value of inputArg as type Object._x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.9_x000D_
     */_x000D_
    function $toObject(inputArg) {_x000D_
        var object;_x000D_
_x000D_
        if ($isPrimitive($requireObjectCoercible(inputArg))) {_x000D_
            object = Object(inputArg);_x000D_
        } else {_x000D_
            object = inputArg;_x000D_
        }_x000D_
_x000D_
        return object;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Converts a single argument that is an array-like object or list (eg._x000D_
     * arguments, NodeList, DOMTokenList (used by classList), NamedNodeMap_x000D_
     * (used by attributes property)) into a new Array() and returns it._x000D_
     * This is a partial implementation of the ES6 Array.from_x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {Object} arrayLike_x000D_
     * @returns {Array}_x000D_
     */_x000D_
    function $toArray(arrayLike) {_x000D_
        var object = $toObject(arrayLike),_x000D_
            length = $toLength(object.length),_x000D_
            array = [],_x000D_
            index = 0;_x000D_
_x000D_
        array.length = length;_x000D_
        while (index < length) {_x000D_
            array[index] = object[index];_x000D_
            index += 1;_x000D_
        }_x000D_
_x000D_
        return array;_x000D_
    }_x000D_
_x000D_
    if (!String.prototype.searchOf) {_x000D_
        /**_x000D_
         * This method returns the index within the calling String object of_x000D_
         * the first occurrence of the specified value, starting the search at_x000D_
         * fromIndex. Returns -1 if the value is not found._x000D_
         *_x000D_
         * @function_x000D_
         * @this {string}_x000D_
         * @param {RegExp|string} regex A regular expression object or a String._x000D_
         *                              Anything else is implicitly converted to_x000D_
         *                              a String._x000D_
         * @param {Number} [fromIndex] The location within the calling string_x000D_
         *                             to start the search from. It can be any_x000D_
         *                             integer. The default value is 0. If_x000D_
         *                             fromIndex < 0 the entire string is_x000D_
         *                             searched (same as passing 0). If_x000D_
         *                             fromIndex >= str.length, the method will_x000D_
         *                             return -1 unless searchValue is an empty_x000D_
         *                             string in which case str.length is_x000D_
         *                             returned._x000D_
         * @returns {Number} If successful, returns the index of the first_x000D_
         *                   match of the regular expression inside the_x000D_
         *                   string. Otherwise, it returns -1._x000D_
         */_x000D_
        $defineProperty(String.prototype, 'searchOf', {_x000D_
            enumerable: false,_x000D_
            configurable: true,_x000D_
            writable: true,_x000D_
            value: function (regex) {_x000D_
                var str = $onlyCoercibleToString(this),_x000D_
                    args = $toArray(arguments),_x000D_
                    result = -1,_x000D_
                    fromIndex,_x000D_
                    match,_x000D_
                    rx;_x000D_
_x000D_
                if (!$isRegExp(regex)) {_x000D_
                    return String.prototype.indexOf.apply(str, args);_x000D_
                }_x000D_
_x000D_
                if ($toLength(args.length) > 1) {_x000D_
                    fromIndex = +args[1];_x000D_
                    if (fromIndex < 0) {_x000D_
                        fromIndex = 0;_x000D_
                    }_x000D_
                } else {_x000D_
                    fromIndex = 0;_x000D_
                }_x000D_
_x000D_
                if (fromIndex >= $toLength(str.length)) {_x000D_
                    return result;_x000D_
                }_x000D_
_x000D_
                rx = $toSearchRegExp(regex);_x000D_
                rx.lastIndex = fromIndex;_x000D_
                match = rx.exec(str);_x000D_
                if (match) {_x000D_
                    result = +match.index;_x000D_
                }_x000D_
_x000D_
                return result;_x000D_
            }_x000D_
        });_x000D_
    }_x000D_
_x000D_
    if (!String.prototype.searchLastOf) {_x000D_
        /**_x000D_
         * This method returns the index within the calling String object of_x000D_
         * the last occurrence of the specified value, or -1 if not found._x000D_
         * The calling string is searched backward, starting at fromIndex._x000D_
         *_x000D_
         * @function_x000D_
         * @this {string}_x000D_
         * @param {RegExp|string} regex A regular expression object or a String._x000D_
         *                              Anything else is implicitly converted to_x000D_
         *                              a String._x000D_
         * @param {Number} [fromIndex] Optional. The location within the_x000D_
         *                             calling string to start the search at,_x000D_
         *                             indexed from left to right. It can be_x000D_
         *                             any integer. The default value is_x000D_
         *                             str.length. If it is negative, it is_x000D_
         *                             treated as 0. If fromIndex > str.length,_x000D_
         *                             fromIndex is treated as str.length._x000D_
         * @returns {Number} If successful, returns the index of the first_x000D_
         *                   match of the regular expression inside the_x000D_
         *                   string. Otherwise, it returns -1._x000D_
         */_x000D_
        $defineProperty(String.prototype, 'searchLastOf', {_x000D_
            enumerable: false,_x000D_
            configurable: true,_x000D_
            writable: true,_x000D_
            value: function (regex) {_x000D_
                var str = $onlyCoercibleToString(this),_x000D_
                    args = $toArray(arguments),_x000D_
                    result = -1,_x000D_
                    fromIndex,_x000D_
                    length,_x000D_
                    match,_x000D_
                    pos,_x000D_
                    rx;_x000D_
_x000D_
                if (!$isRegExp(regex)) {_x000D_
                    return String.prototype.lastIndexOf.apply(str, args);_x000D_
                }_x000D_
_x000D_
                length = $toLength(str.length);_x000D_
                if (!$strictEqual(args[1], args[1])) {_x000D_
                    fromIndex = length;_x000D_
                } else {_x000D_
                    if ($toLength(args.length) > 1) {_x000D_
                        fromIndex = $toInteger(args[1]);_x000D_
                    } else {_x000D_
                        fromIndex = length - 1;_x000D_
                    }_x000D_
                }_x000D_
_x000D_
                if (fromIndex >= 0) {_x000D_
                    fromIndex = Math.min(fromIndex, length - 1);_x000D_
                } else {_x000D_
                    fromIndex = length - Math.abs(fromIndex);_x000D_
                }_x000D_
_x000D_
                pos = 0;_x000D_
                rx = $toSearchRegExp(regex);_x000D_
                while (pos <= fromIndex) {_x000D_
                    rx.lastIndex = pos;_x000D_
                    match = rx.exec(str);_x000D_
                    if (!match) {_x000D_
                        break;_x000D_
                    }_x000D_
_x000D_
                    pos = +match.index;_x000D_
                    if (pos <= fromIndex) {_x000D_
                        result = pos;_x000D_
                    }_x000D_
_x000D_
                    pos += 1;_x000D_
                }_x000D_
_x000D_
                return result;_x000D_
            }_x000D_
        });_x000D_
    }_x000D_
}());_x000D_
_x000D_
(function () {_x000D_
    'use strict';_x000D_
_x000D_
    /*_x000D_
     * testing as follow to make sure that at least for one character regexp,_x000D_
     * the result is the same as if we used indexOf_x000D_
     */_x000D_
_x000D_
    var pre = document.getElementById('out');_x000D_
_x000D_
    function log(result) {_x000D_
        pre.appendChild(document.createTextNode(result + '\n'));_x000D_
    }_x000D_
_x000D_
    function test(str) {_x000D_
        var i = str.length + 2,_x000D_
            r,_x000D_
            a,_x000D_
            b;_x000D_
_x000D_
        while (i) {_x000D_
            a = str.indexOf('a', i);_x000D_
            b = str.searchOf(/a/, i);_x000D_
            r = ['Failed', 'searchOf', str, i, a, b];_x000D_
            if (a === b) {_x000D_
                r[0] = 'Passed';_x000D_
            }_x000D_
_x000D_
            log(r);_x000D_
            a = str.lastIndexOf('a', i);_x000D_
            b = str.searchLastOf(/a/, i);_x000D_
            r = ['Failed', 'searchLastOf', str, i, a, b];_x000D_
            if (a === b) {_x000D_
                r[0] = 'Passed';_x000D_
            }_x000D_
_x000D_
            log(r);_x000D_
            i -= 1;_x000D_
        }_x000D_
    }_x000D_
_x000D_
    /*_x000D_
     * Look for the a among the xes_x000D_
     */_x000D_
_x000D_
    test('xxx');_x000D_
    test('axx');_x000D_
    test('xax');_x000D_
    test('xxa');_x000D_
    test('axa');_x000D_
    test('xaa');_x000D_
    test('aax');_x000D_
    test('aaa');_x000D_
}());
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

How npm start runs a server on port 8000

If you will look at package.json file.

you will see something like this

 "start": "http-server -a localhost -p 8000"

This tells start a http-server at address of localhost on port 8000

http-server is a node-module.

Update:- Including comment by @Usman, ideally it should be present in your package.json but if it's not present you can include it in scripts section.

Use of Application.DoEvents()

Application.DoEvents can create problems, if something other than graphics processing is put in the message queue.

It can be useful for updating progress bars and notifying the user of progress in something like MainForm construction and loading, if that takes a while.

In a recent application I've made, I used DoEvents to update some labels on a Loading Screen every time a block of code is executed in the constructor of my MainForm. The UI thread was, in this case, occupied with sending an email on a SMTP server that didn't support SendAsync() calls. I could probably have created a different thread with Begin() and End() methods and called a Send() from their, but that method is error-prone and I would prefer the Main Form of my application not throwing exceptions during construction.

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.

How do I install Java on Mac OSX allowing version switching?

With Homebrew and jenv:

Assumption: Mac machine and you already have installed homebrew.

Install cask:

$ brew tap caskroom/cask
$ brew tap caskroom/versions

To install latest java:

$ brew cask install java

To install java 8:

$ brew cask install java8

To install java 9:

$ brew cask install java9

If you want to install/manage multiple version then you can use 'jenv':

Install and configure jenv:

$ brew install jenv
$ echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(jenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile

Add the installed java to jenv:

$ jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
$ jenv add /Library/Java/JavaVirtualMachines/jdk1.11.0_2.jdk/Contents/Home

To see all the installed java:

$ jenv versions

Above command will give the list of installed java:

* system (set by /Users/lyncean/.jenv/version)
1.8
1.8.0.202-ea
oracle64-1.8.0.202-ea

Configure the java version which you want to use:

$ jenv global oracle64-1.6.0.39

Check if a string matches a regex in Bash script

Where the usage of a regex can be helpful to determine if the character sequence of a date is correct, it cannot be used easily to determine if the date is valid. The following examples will pass the regular expression, but are all invalid dates: 20180231, 20190229, 20190431

So if you want to validate if your date string (let's call it datestr) is in the correct format, it is best to parse it with date and ask date to convert the string to the correct format. If both strings are identical, you have a valid format and valid date.

if [[ "$datestr" == $(date -d "$datestr" "+%Y%m%d" 2>/dev/null) ]]; then
     echo "Valid date"
else
     echo "Invalid date"
fi

c++ integer->std::string conversion. Simple function?

Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).

What is "string[] args" in Main class for?

It's an array of the parameters/arguments (hence args) that you send to the program. For example ping 172.16.0.1 -t -4

These arguments are passed to the program as an array of strings.

string[] args // Array of Strings containing arguments.

Where is the default log location for SharePoint/MOSS?

In SharePoint 2013 they are stored in:

%COMMONPROGRAMFILES%\Microsoft Shared\web server extensions\15\LOGS

How can I find the number of years between two dates?

Here's what I think is a better method:

public int getYearsBetweenDates(Date first, Date second) {
    Calendar firstCal = GregorianCalendar.getInstance();
    Calendar secondCal = GregorianCalendar.getInstance();

    firstCal.setTime(first);
    secondCal.setTime(second);

    secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));

    return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}

EDIT

Apart from a bug which I fixed, this method does not work well with leap years. Here's a complete test suite. I guess you're better off using the accepted answer.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

class YearsBetweenDates {
    public static int getYearsBetweenDates(Date first, Date second) {
        Calendar firstCal = GregorianCalendar.getInstance();
        Calendar secondCal = GregorianCalendar.getInstance();

        firstCal.setTime(first);
        secondCal.setTime(second);

        secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));

        return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
    }

    private static class TestCase {
        public Calendar date1;
        public Calendar date2;
        public int expectedYearDiff;
        public String comment;

        public TestCase(Calendar date1, Calendar date2, int expectedYearDiff, String comment) {
            this.date1 = date1;
            this.date2 = date2;
            this.expectedYearDiff = expectedYearDiff;
            this.comment = comment;
        }
    }

    private static TestCase[] tests = {
        new TestCase(
                new GregorianCalendar(2014, Calendar.JULY, 15),
                new GregorianCalendar(2015, Calendar.JULY, 15),
                1,
                "exactly one year"),
        new TestCase(
                new GregorianCalendar(2014, Calendar.JULY, 15),
                new GregorianCalendar(2017, Calendar.JULY, 14),
                2,
                "one day less than 3 years"),
        new TestCase(
                new GregorianCalendar(2015, Calendar.NOVEMBER, 3),
                new GregorianCalendar(2017, Calendar.MAY, 3),
                1,
                "a year and a half"),
        new TestCase(
                new GregorianCalendar(2016, Calendar.JULY, 15),
                new GregorianCalendar(2017, Calendar.JULY, 15),
                1,
                "leap years do not compare correctly"),
    };

    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        for (TestCase t : tests) {
            int diff = getYearsBetweenDates(t.date1.getTime(), t.date2.getTime());
            String result = diff == t.expectedYearDiff ? "PASS" : "FAIL";
            System.out.println(t.comment + ": " +
                    df.format(t.date1.getTime()) + " -> " +
                    df.format(t.date2.getTime()) + " = " +
                    diff + ": " + result);
        }
    }
}

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I think this is very nice and short

<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />

But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.


EDIT To avoid endless loop, remove the onerror from it at once.

<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />

By calling this.onerror=null it will remove the onerror then try to get the alternate image.


NEW I would like to add a jQuery way, if this can help anyone.

<script>
$(document).ready(function()
{
    $(".backup_picture").on("error", function(){
        $(this).attr('src', './images/nopicture.png');
    });
});
</script>

<img class='backup_picture' src='./images/nonexistent_image_file.png' />

You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.

How to use a FolderBrowserDialog from a WPF application

OK, figured it out now - thanks to Jobi whose answer was close, but not quite.

From a WPF application, here's my code that works:

First a helper class:

private class OldWindow : System.Windows.Forms.IWin32Window
{    
    IntPtr _handle;    
    public OldWindow(IntPtr handle)
    {
        _handle = handle;
    }   

    #region IWin32Window Members    
    IntPtr System.Windows.Forms.IWin32Window.Handle
    {
        get { return _handle; }
    }    
    #endregion
}

Then, to use this:

    System.Windows.Forms.FolderBrowserDialog dlg = new FolderBrowserDialog();
    HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
    System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
    System.Windows.Forms.DialogResult result = dlg.ShowDialog(win);

I'm sure I can wrap this up better, but basically it works. Yay! :-)

DbEntityValidationException - How can I easily tell what caused the error?

As Martin indicated, there is more information in the DbEntityValidationResult. I found it useful to get both my POCO class name and property name in each message, and wanted to avoid having to write custom ErrorMessage attributes on all my [Required] tags just for this.

The following tweak to Martin's code took care of these details for me:

// Retrieve the error messages as a list of strings.
List<string> errorMessages = new List<string>();
foreach (DbEntityValidationResult validationResult in ex.EntityValidationErrors)
{
    string entityName = validationResult.Entry.Entity.GetType().Name;
    foreach (DbValidationError error in validationResult.ValidationErrors)
    {
        errorMessages.Add(entityName + "." + error.PropertyName + ": " + error.ErrorMessage);
    }
}

Java String.split() Regex

    String str = "a + b - c * d / e < f > g >= h <= i == j";
    String reg = "\\s*[a-zA-Z]+";

    String[] res = str.split(reg);
    for (String out : res) {
        if (!"".equals(out)) {
            System.out.print(out);
        }
    }

Output : + - * / < > >= <= ==

SQL how to increase or decrease one for a int column in one command

UPDATE Orders Order
SET Order.Quantity =  Order.Quantity - 1
WHERE SomeCondition(Order)

As far as I know there is no build-in support for INSERT-OR-UPDATE in SQL. I suggest to create a stored procedure or use a conditional query to achiev this. Here you can find a collection of solutions for different databases.

Programmatically Install Certificate into Mozilla

I have an update of this awesome answer (just not working any more with last Firefox updates), in this same thread, made by H.-Dirk Schmitt, also thanks to the answer in this other thread made by BecarioEstrella.

I just adapted the script to recent changes.

Tested in 2021 just in Firefox 85.0.1 (64bit) in Ubuntu 20.04 and 18.04.

#!/usr/bin/env bash

function usage {
  echo "Error: no certificate filename or name supplied."
  echo "Usage: $ ./installcerts.sh <certname>.pem <Cert-DB-Name>"
  exit 1

}

if [ -z "$1" ] || [ -z "$2" ]
  then
    usage
fi

certificate_file="$1"
certificate_name="$2"
for certDB in $(find  ~/.mozilla* ~/.thunderbird -name "cert9.db")
do
  cert_dir=$(dirname ${certDB});
  echo "Mozilla Firefox certificate" "install '${certificate_name}' in ${cert_dir}"
  certutil -A -n "${certificate_name}" -t "TCu,Cuw,Tuw" -i ${certificate_file} -d sql:"${cert_dir}"
done

If you want it just for Firefox, replace the line:

for certDB in $(find  ~/.mozilla* ~/.thunderbird -name "cert9.db")

By

for certDB in $(find  ~/.mozilla* -name "cert9.db")

Further readings:

Search input with an icon Bootstrap 4

Update 2019

Why not use an input-group?

<div class="input-group col-md-4">
      <input class="form-control py-2" type="search" value="search" id="example-search-input">
      <span class="input-group-append">
        <button class="btn btn-outline-secondary" type="button">
            <i class="fa fa-search"></i>
        </button>
      </span>
</div>

And, you can make it appear inside the input using the border utils...

        <div class="input-group col-md-4">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
              <button class="btn btn-outline-secondary border-left-0 border" type="button">
                    <i class="fa fa-search"></i>
              </button>
            </span>
        </div>

Or, using a input-group-text w/o the gray background so the icon appears inside the input...

        <div class="input-group">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
                <div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div>
            </span>
        </div>

Alternately, you can use the grid (row>col-) with no gutter spacing:

<div class="row no-gutters">
     <div class="col">
          <input class="form-control border-secondary border-right-0 rounded-0" type="search" value="search" id="example-search-input4">
     </div>
     <div class="col-auto">
          <button class="btn btn-outline-secondary border-left-0 rounded-0 rounded-right" type="button">
             <i class="fa fa-search"></i>
          </button>
     </div>
</div>

Or, prepend the icon like this...

<div class="input-group">
  <span class="input-group-prepend">
    <div class="input-group-text bg-transparent border-right-0">
      <i class="fa fa-search"></i>
    </div>
  </span>
  <input class="form-control py-2 border-left-0 border" type="search" value="..." id="example-search-input" />
  <span class="input-group-append">
    <button class="btn btn-outline-secondary border-left-0 border" type="button">
     Search
    </button>
  </span>
</div>

Demo of all Bootstrap 4 icon input options


enter image description here


Example with validation icons

Get POST data in C#/ASP.NET

c.Request["AP"] will read posted values. Also you need to use a submit button to post the form:

<input type="submit" value="Submit" />

instead of

<input type=button value="Submit" />

How to pip or easy_install tkinter on Windows

If you are using virtualenv, it is fine to install tkinter using sudo apt-get install python-tk(python2), sudo apt-get install python3-tk(python3), and and it will work fine in the virtual environment

Git: Cannot see new remote branch

What ended up finally working for me was to add the remote repository name to the git fetch command, like this:

git fetch core

Now you can see all of them like this:

git branch --all

Using NOT operator in IF conditions

As a general statement, its good to make your if conditionals as readable as possible. For your example, using ! is ok. the problem is when things look like

if ((a.b && c.d.e) || !f)

you might want to do something like

bool isOk = a.b;
bool isStillOk = c.d.e
bool alternateOk = !f

then your if statement is simplified to

if ( (isOk && isStillOk) || alternateOk)

It just makes the code more readable. And if you have to debug, you can debug the isOk set of vars instead of having to dig through the variables in scope. It is also helpful for dealing with NPEs -- breaking code out into simpler chunks is always good.

Get the generated SQL statement from a SqlCommand object?

You can't, because it does not generate any SQL.

The parameterized query (the one in CommandText) is sent to the SQL Server as the equivalent of a prepared statement. When you execute the command, the parameters and the query text are treated separately. At no point in time a complete SQL string is generated.

You can use SQL Profiler to take a look behind the scenes.

How do I get only directories using Get-ChildItem?

A bit more readable and simple approach could be achieved with the script below:

$Directory = "./"
Get-ChildItem $Directory -Recurse | % {
    if ($_.Attributes -eq "Directory") {
        Write-Host $_.FullName
    }
}

Hope this helps!

Understanding REST: Verbs, error codes, and authentication

For the examples you stated I'd use the following:

activate_login

POST /users/1/activation

deactivate_login

DELETE /users/1/activation

change_password

PUT /passwords (this assumes the user is authenticated)

add_credit

POST /credits (this assumes the user is authenticated)

For errors you'd return the error in the body in the format that you got the request in, so if you receive:

DELETE /users/1.xml

You'd send the response back in XML, the same would be true for JSON etc...

For authentication you should use http authentication.

Relative paths in Python

Consider my code:

import os


def readFile(filename):
    filehandle = open(filename)
    print filehandle.read()
    filehandle.close()



fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)

MySQL SELECT LIKE or REGEXP to match multiple words in one record

you need to do something like this,

SELECT * FROM buckets WHERE bucketname RLIKE 'Stylus.*2100';

or

SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus)+.*(2100)+';

Oracle SQL, concatenate multiple columns + add text

The Oracle/PLSQL CONCAT function allows to concatenate two strings together.

CONCAT( string1, string2 )

string1

The first string to concatenate.

string2

The second string to concatenate.

E.g.

SELECT 'I like ' || type_column_name || ' cake with ' || 
icing_column_name || ' and a ' fruit_column_name || '.' 
AS Cake FROM table;

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

How do I plot list of tuples in Python?

If I get your question correctly, you could do something like this.

>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()

which would give you something like

enter image description here

Or as a line plot,

>>> plt.plot(*zip(*testList2))
>>> plt.show()

enter image description here

EDIT - If you want to add a title and labels for the axis, you could do something like

>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()

which would give you

enter image description here

Gridview row editing - dynamic binding to a DropDownList

I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:

protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    // This stmt is used to execute the code only in case of edit 
    if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
    {
        ((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
        ((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
    }
}

How to write "not in ()" sql query using join

SELECT d1.Short_Code 
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL

How to read a single character from the user?

sys.stdin.read(1)

will basically read 1 byte from STDIN.

If you must use the method which does not wait for the \n you can use this code as suggested in previous answer:

class _Getch:
    """Gets a single character from standard input.  Does not echo to the screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()

(taken from http://code.activestate.com/recipes/134892/)

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

How to add line break for UILabel?

// DO not forget to set numberOfLines to zero

UILabel* locationTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 30, 230, 40)];
locationTitle.font = [UIFont systemFontOfSize:13.0];
locationTitle.numberOfLines = 0;
locationTitle.text = [NSString stringWithFormat:@"Eaton industries pvt. Ltd \nUK Apr 12"];
[cell addSubview:locationTitle];

Get latest from Git branch

If you have forked a repository fro Delete your forked copy and fork it again from master.

WCF Exception: Could not find a base address that matches scheme http for the endpoint

In my case the binding name in under protocol mapping did not match the binding name on the endpoint. They match in the example below.

<endpoint address="" binding="basicHttpsBinding" contract="serviceName" />

and

    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    

javac option to compile all java files under a given directory recursively

I would advice you to learn using ant, which is very-well suited for this task and is very easy to grasp and well documented.

You would just have to define a target like this in the build.xml file:

<target name="compile">
    <javac srcdir="your/source/directory"
           destdir="your/output/directory"
           classpath="xyz.jar" />
</target>

Ignore mapping one property with Automapper

There is now (AutoMapper 2.0) an IgnoreMap attribute, which I'm going to use rather than the fluent syntax which is a bit heavy IMHO.

Is there a wikipedia API just for retrieve content summary?

This url will return summary in xml format.

http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=Agra&MaxHits=1

I have created a function to fetch description of a keyword from wikipedia.

function getDescription($keyword){
    $url='http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString='.urlencode($keyword).'&MaxHits=1';
    $xml=simplexml_load_file($url);
    return $xml->Result->Description;
}
echo getDescription('agra');

How to convert an array into an object using stdClass()

To convert array to object using stdClass just add (object) to array u declare.

EX:

echo $array['value'];
echo $object->value;

to convert object to array

$obj = (object)$array;

to convert array to object

$arr = (array)$object

with these methods you can swap between array and object very easily.


Another method is to use json

$object = json_decode(json_encode($array), FALSE);

But this is a much more memory intensive way to do and is not supported by versions of PHP <= 5.1

What does "implements" do on a class?

It is called an interface. Many OO languages have this feature. You might want to read through the php explanation here: http://de2.php.net/interface

How to create a QR code reader in a HTML5 website?

Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.

However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.

Happy coding.

Launch Bootstrap Modal on page load

<div id="ModalStart" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-body">
          <p><i class="icon-spinner icon-spin icon-4x"></i></p>
    </div>
</div>

You can show it on start even without Javascript. Just delete the class "hide".

class="Modal"

How can I open a popup window with a fixed size using the HREF tag?

Plain HTML does not support this. You'll need to use some JavaScript code.

Also, note that large parts of the world are using a popup blocker nowadays. You may want to reconsider your design!

Bulk insert with SQLAlchemy ORM

As far as I know, there is no way to get the ORM to issue bulk inserts. I believe the underlying reason is that SQLAlchemy needs to keep track of each object's identity (i.e., new primary keys), and bulk inserts interfere with that. For example, assuming your foo table contains an id column and is mapped to a Foo class:

x = Foo(bar=1)
print x.id
# None
session.add(x)
session.flush()
# BEGIN
# INSERT INTO foo (bar) VALUES(1)
# COMMIT
print x.id
# 1

Since SQLAlchemy picked up the value for x.id without issuing another query, we can infer that it got the value directly from the INSERT statement. If you don't need subsequent access to the created objects via the same instances, you can skip the ORM layer for your insert:

Foo.__table__.insert().execute([{'bar': 1}, {'bar': 2}, {'bar': 3}])
# INSERT INTO foo (bar) VALUES ((1,), (2,), (3,))

SQLAlchemy can't match these new rows with any existing objects, so you'll have to query them anew for any subsequent operations.

As far as stale data is concerned, it's helpful to remember that the session has no built-in way to know when the database is changed outside of the session. In order to access externally modified data through existing instances, the instances must be marked as expired. This happens by default on session.commit(), but can be done manually by calling session.expire_all() or session.expire(instance). An example (SQL omitted):

x = Foo(bar=1)
session.add(x)
session.commit()
print x.bar
# 1
foo.update().execute(bar=42)
print x.bar
# 1
session.expire(x)
print x.bar
# 42

session.commit() expires x, so the first print statement implicitly opens a new transaction and re-queries x's attributes. If you comment out the first print statement, you'll notice that the second one now picks up the correct value, because the new query isn't emitted until after the update.

This makes sense from the point of view of transactional isolation - you should only pick up external modifications between transactions. If this is causing you trouble, I'd suggest clarifying or re-thinking your application's transaction boundaries instead of immediately reaching for session.expire_all().

How to get a list of current open windows/process with Java?

The below program will be compatible with Java 9+ version only...

To get the CurrentProcess information,

public class CurrentProcess {
    public static void main(String[] args) {
        ProcessHandle handle = ProcessHandle.current();
        System.out.println("Current Running Process Id: "+handle.pid());
        ProcessHandle.Info info = handle.info();
        System.out.println("ProcessHandle.Info : "+info);
    }
}

For all running processes,

import java.util.List;
import java.util.stream.Collectors;

public class AllProcesses {
    public static void main(String[] args) {
        ProcessHandle.allProcesses().forEach(processHandle -> {
            System.out.println(processHandle.pid()+" "+processHandle.info());
        });
    }
}

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

adding content type into the request as application/json resolved the issue

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

Html.BeginForm and adding properties

You can also use the following syntax for the strongly typed version:

<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(), 
          FormMethod.Post, 
          new { enctype = "multipart/form-data" })) 
   { %>

Failed to load resource: the server responded with a status of 404 (Not Found)

Please note , you might need to disable adblocks if necessary. Drag and drop off script path in visual studio doesn't work if you are using HTML pages but it does work for mvc ,asp.netwebforms. I figured this after one hour

Where can I find Android's default icons?

you can use

android.R.drawable.xxx

(use autocomplete to see whats in there)

Or download the stuff from http://developer.android.com/design/downloads/index.html

Using a list as a data source for DataGridView

Set the DataGridView property

    gridView1.AutoGenerateColumns = true;

And make sure the list of objects your are binding, those object properties should be public.

Ignore 'Security Warning' running script from command line

This is touched in "PowerShell Execution Policies in Standard Images" on Lee Holmes' Blog and "PowerShell’s Security Guiding Principles" on the Windows Power Shell Blog .

Summary Some machines treat UNC paths as the big bad internet, so PowerShell treats them as remote files. You can either disable this feature on those servers (UncAsIntranet = 0,) or add the remote machines to your trusted hosts.

If you want to do neither, PowerShell v2 supports an -ExecutionPolicy parameter that does exactly what your pseudocode wants. PowerShell -ExecutionPolicy Bypass -File (...).

Difference between clean, gradlew clean

  1. ./gradlew clean

    Uses your project's gradle wrapper to execute your project's clean task. Usually, this just means the deletion of the build directory.

  2. ./gradlew clean assembleDebug

    Again, uses your project's gradle wrapper to execute the clean and assembleDebug tasks, respectively. So, it will clean first, then execute assembleDebug, after any non-up-to-date dependent tasks.

  3. ./gradlew clean :assembleDebug

    Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.

  4. Android Studio --> Build --> Clean

    Is essentially the same as ./gradlew clean. See here.

For more info, I suggest taking the time to read through the Android docs, especially this one.

ActionBarActivity is deprecated

According to this video of Android Developers you should only make two changes

enter image description here

Should I initialize variable within constructor or outside constructor

I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly.

Either way will work, and it's a matter of style, but I prefer constructors for member initialization.

How to add a class with React.js?

you can also use pure js to accomplish this like the old ways with jquery

try this if you want a simple way

 document.getElementById("myID").classList.add("show-example");

Check if a process is running or not on Windows with Python

import psutil

def check_process_status(process_name):
    """
    Return status of process based on process name.
    """
    process_status = [ proc.status() for proc in psutil.process_iter() if proc.name() == process_name ]
    if process_status:
        print("Process name %s and staus %s"%(process_name, process_status[0]))
    else:
        print("Process name not valid", process_name)

How do you kill all current connections to a SQL Server 2005 database?

I use sp_who to get list of all process in database. This is better because you may want to review which process to kill.

declare @proc table(
    SPID bigint,
    Status nvarchar(255),
    Login nvarchar(255),
    HostName nvarchar(255),
    BlkBy nvarchar(255),
    DBName nvarchar(255),
    Command nvarchar(MAX),
    CPUTime bigint,
    DiskIO bigint,
    LastBatch nvarchar(255),
    ProgramName nvarchar(255),
    SPID2 bigint,
    REQUESTID bigint
)

insert into @proc
exec sp_who2

select  *, KillCommand = concat('kill ', SPID, ';')
from    @proc

Result
You can use command in KillCommand column to kill the process you want to.

SPID    KillCommand
26      kill 26;
27      kill 27;
28      kill 28;

List View Filter Android

In case anyone are still interested in this subject, I find that the best approach for filtering lists is to create a generic Filter class and use it with some base reflection/generics techniques contained in the Java old school SDK package. Here's what I did:

public class GenericListFilter<T> extends Filter {

    /**
     * Copycat constructor
     * @param list  the original list to be used
     */
    public GenericListFilter (List<T> list, String reflectMethodName, ArrayAdapter<T> adapter) {
        super ();

        mInternalList = new ArrayList<>(list);
        mAdapterUsed  = adapter;

        try {
            ParameterizedType stringListType = (ParameterizedType)
                    getClass().getField("mInternalList").getGenericType();
            mCompairMethod =
                    stringListType.getActualTypeArguments()[0].getClass().getMethod(reflectMethodName);
        }
        catch (Exception ex) {
            Log.w("GenericListFilter", ex.getMessage(), ex);

            try {
                if (mInternalList.size() > 0) {
                    T type = mInternalList.get(0);
                    mCompairMethod = type.getClass().getMethod(reflectMethodName);
                }
            }
            catch (Exception e) {
                Log.e("GenericListFilter", e.getMessage(), e);
            }

        }
    }

    /**
     * Let's filter the data with the given constraint
     * @param constraint
     * @return
     */
    @Override protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        List<T> filteredContents = new ArrayList<>();

        if ( constraint.length() > 0 ) {
            try {
                for (T obj : mInternalList) {
                    String result = (String) mCompairMethod.invoke(obj);
                    if (result.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        filteredContents.add(obj);
                    }
                }
            }
            catch (Exception ex) {
                Log.e("GenericListFilter", ex.getMessage(), ex);
            }
        }
        else {
            filteredContents.addAll(mInternalList);
        }

        results.values = filteredContents;
        results.count  = filteredContents.size();
        return results;
    }

    /**
     * Publish the filtering adapter list
     * @param constraint
     * @param results
     */
    @Override protected void publishResults(CharSequence constraint, FilterResults results) {
        mAdapterUsed.clear();
        mAdapterUsed.addAll((List<T>) results.values);

        if ( results.count == 0 ) {
            mAdapterUsed.notifyDataSetInvalidated();
        }
        else {
            mAdapterUsed.notifyDataSetChanged();
        }
    }

    // class properties
    private ArrayAdapter<T> mAdapterUsed;
    private List<T> mInternalList;
    private Method  mCompairMethod;
}

And afterwards, the only thing you need to do is to create the filter as a member class (possibly within the View's "onCreate") passing your adapter reference, your list, and the method to be called for filtering:

this.mFilter = new GenericFilter<MyObjectBean> (list, "getName", adapter);

The only thing missing now, is to override the "getFilter" method in the adapter class:

@Override public Filter getFilter () {
     return MyViewClass.this.mFilter;
}

All done! You should successfully filter your list - Of course, you should also implement your filter algorithm the best way that describes your need, the code bellow is just an example.. Hope it helped, take care.

How do I filter query objects by date range in Django?

Use

Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"])

Or if you are just trying to filter month wise:

Sample.objects.filter(date__year='2011', 
                      date__month='01')

Edit

As Bernhard Vallant said, if you want a queryset which excludes the specified range ends you should consider his solution, which utilizes gt/lt (greater-than/less-than).

How do I link a JavaScript file to a HTML file?

Below you have some VALID html5 example document. The type attribute in script tag is not mandatory in HTML5.

You use jquery by $ charater. Put libraries (like jquery) in <head> tag - but your script put allways at the bottom of document (<body> tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src attribute in bottom script tag to include you script file instead of putting direct js code like above.

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <title>Example</title>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
    <div>Im the content</div>_x000D_
_x000D_
    <script>_x000D_
        alert( $('div').text() ); // show message with div content_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

HTML - How to do a Confirmation popup to a Submit button and then send the request?

The most compact version:

<input type="submit" onclick="return confirm('Are you sure?')" />

The key thing to note is the return

-

Because there are many ways to skin a cat, here is another alternate method:

HTML:

<input type="submit" onclick="clicked(event)" />

Javascript:

<script>
function clicked(e)
{
    if(!confirm('Are you sure?')) {
        e.preventDefault();
    }
}
</script>

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

How about adding this to your pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
</dependency>

Animate element to auto height with jQuery

IMO this is the cleanest and easiest solution:

$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000 );

Explanation: The DOM already knows from its initial rendering what size the expanded div will have when set to auto height. This property is stored in the DOM node as scrollHeight. We just have to fetch the DOM Element from the jQuery Element by calling get(0) and then we can access the property.

Adding a callback function to set the height to auto allows for greater responsiveness once the animation is complete (credit chris-williams):

$('#first').animate({
    height: $('#first').get(0).scrollHeight
}, 1000, function(){
    $(this).height('auto');
});

PG::ConnectionBad - could not connect to server: Connection refused

I had the same problem. I Check the last line of PostgreSQL log files in /var/log/postgresql. There was an unrecognized configuration parameter in file /etc/postgresql/9.5/main/postgresql.conf. Commenting the error line in postgresql.conf resolved my problem.