Programs & Examples On #Numerical integration

Algorithms that integrate functions over one or more dimensions using approximation techniques, instead of exact, closed-form solutions using symbolic algebra and calculus. Includes concepts like adaptive quadrature, Monte-Carlo methods, finite element analysis, Markov chains.

How to convert a std::string to const char* or char*?

I am working with an API with a lot of functions get as an input a char*.

I have created a small class to face this kind of problem, I have implemented the RAII idiom.

class DeepString
{
        DeepString(const DeepString& other);
        DeepString& operator=(const DeepString& other);
        char* internal_; 

    public:
        explicit DeepString( const string& toCopy): 
            internal_(new char[toCopy.size()+1]) 
        {
            strcpy(internal_,toCopy.c_str());
        }
        ~DeepString() { delete[] internal_; }
        char* str() const { return internal_; }
        const char* c_str()  const { return internal_; }
};

And you can use it as:

void aFunctionAPI(char* input);

//  other stuff

aFunctionAPI("Foo"); //this call is not safe. if the function modified the 
                     //literal string the program will crash
std::string myFoo("Foo");
aFunctionAPI(myFoo.c_str()); //this is not compiling
aFunctionAPI(const_cast<char*>(myFoo.c_str())); //this is not safe std::string 
                                                //implement reference counting and 
                                                //it may change the value of other
                                                //strings as well.
DeepString myDeepFoo(myFoo);
aFunctionAPI(myFoo.str()); //this is fine

I have called the class DeepString because it is creating a deep and unique copy (the DeepString is not copyable) of an existing string.

build maven project with propriatery libraries included

You can get it from your local driver as below:

<dependency>
    <groupId>sample</groupId>
    <artifactId>com.sample</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

Selenium webdriver click google search

Based on quick inspection of google web, this would be CSS path to links in page list

ol[id="rso"] h3[class="r"] a

So you should do something like

String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();

However you could also use xpath which is not really recommended as a best practice and also JQuery locators but I am not sure if you can use them aynywhere else except inArquillian Graphene

How do you specify the Java compiler version in a pom.xml file?

I faced same issue in eclipse neon simple maven java project

But I add below details inside pom.xml file

   <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

After right click on project > maven > update project (checked force update)

Its resolve me to display error on project

Hope it's will helpful

Thansk

How to change font-size of a tag using inline css?

Strange it doesn't change, as inline styles are most specific, if style sheet has !important declared, it wont over ride, try this and see

<span style="font-size: 11px !important; color: #aaaaaa;">Hello</span>

How can you determine a point is between two other points on a line segment?

The length of the segment is not important, thus using a square root is not required and should be avoided since we could lose some precision.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Segment:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def is_between(self, c):
        # Check if slope of a to c is the same as a to b ;
        # that is, when moving from a.x to c.x, c.y must be proportionally
        # increased than it takes to get from a.x to b.x .

        # Then, c.x must be between a.x and b.x, and c.y must be between a.y and b.y.
        # => c is after a and before b, or the opposite
        # that is, the absolute value of cmp(a, b) + cmp(b, c) is either 0 ( 1 + -1 )
        #    or 1 ( c == a or c == b)

        a, b = self.a, self.b             

        return ((b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y) and 
                abs(cmp(a.x, c.x) + cmp(b.x, c.x)) <= 1 and
                abs(cmp(a.y, c.y) + cmp(b.y, c.y)) <= 1)

Some random example of usage :

a = Point(0,0)
b = Point(50,100)
c = Point(25,50)
d = Point(0,8)

print Segment(a,b).is_between(c)
print Segment(a,b).is_between(d)

How to use radio buttons in ReactJS?

Here is a simplest way of implementing radio buttons in react js.

_x000D_
_x000D_
class App extends React.Component {_x000D_
  _x000D_
  setGender(event) {_x000D_
    console.log(event.target.value);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return ( _x000D_
      <div onChange={this.setGender.bind(this)}>_x000D_
        <input type="radio" value="MALE" name="gender"/> Male_x000D_
        <input type="radio" value="FEMALE" name="gender"/> Female_x000D_
      </div>_x000D_
     )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Edited

You can use arrow function instead of binding. Replace the above code as

<div onChange={event => this.setGender(event)}>

For a default value use defaultChecked, like this

<input type="radio" value="MALE" defaultChecked name="gender"/> Male

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

When and why to 'return false' in JavaScript?

Often, in event handlers, such as onsubmit, returning false is a way to tell the event to not actually fire. So, say, in the onsubmit case, this would mean that the form is not submitted.

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I treid all the solutions mentioned here, but no luck. I found in my build.gradle file as below:

dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
    }

I just changed it as below and saved and tried build success.

dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
    }

grep exclude multiple strings

tail -f admin.log|grep -v -E '(Nopaging the limit is|keyword to remove is)'

PHP/MySQL insert row then get 'id'

The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.

The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().

How to get Last record from Sqlite?

To get last record from your table..

 String selectQuery = "SELECT  * FROM " + "sqlite_sequence";
 Cursor cursor = db.rawQuery(selectQuery, null);
  cursor.moveToLast();

Deserializing JSON Object Array with Json.net

You can create a new model to Deserialize your Json CustomerJson:

public class CustomerJson
{
    [JsonProperty("customer")]
    public Customer Customer { get; set; }
}

public class Customer
{
    [JsonProperty("first_name")]
    public string Firstname { get; set; }

    [JsonProperty("last_name")]
    public string Lastname { get; set; }

    ...
}

And you can deserialize your json easily :

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

Hope it helps !

Documentation: Serializing and Deserializing JSON

How to delete rows from a pandas DataFrame based on a conditional expression

In pandas you can do str.len with your boundary and using the Boolean result to filter it .

df[df['column name'].str.len().lt(2)]

How can I get the nth character of a string?

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

Ternary operator ?: vs if...else

During reversing some code (which I don't remember, few years ago) I saw single line difference between the Machine Code of :? and if-else. Don't remember much but it is clear that implementation of both is different.

But I advise You to not choose one of them b'coz of its efficiency, choose according to readability of code or your convenience. Happy Coding

ESLint Parsing error: Unexpected token

"parser": "babel-eslint" helped me to fix the issue

{
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true,
            "modules": true,
            "experimentalObjectRestSpread": true
        }
    },
    "plugins": [
        "react"
    ],
    "extends": ["eslint:recommended", "plugin:react/recommended"],
    "rules": {
        "comma-dangle": 0,
        "react/jsx-uses-vars": 1,
        "react/display-name": 1,
        "no-unused-vars": "warn",
        "no-console": 1,
        "no-unexpected-multiline": "warn"
    },
    "settings": {
        "react": {
            "pragma": "React",
            "version": "15.6.1"
        }
    }
}

Reference

Is there a "previous sibling" selector?

If you know the exact position an :nth-child()-based exclusion of all following siblings would work.

ul li:not(:nth-child(n+3))

Which would select all lis before the 3rd (e.g. 1st and 2nd). But, in my opinion this looks ugly and has a very tight usecase.

You also could select the nth-child right-to-left:

ul li:nth-child(-n+2)

Which does the same.

Escaping a forward slash in a regular expression

Use the backslash \ or choose a different delimiter, ie m#.\d# instead of /.\d/ "In Perl, you can change the / regular expression delimiter to almost any other special character if you preceed it with the letter m (for match);"

How do I add indices to MySQL tables?

You say you have an index, the explain says otherwise. However, if you really do, this is how to continue:

If you have an index on the column, and MySQL decides not to use it, it may by because:

  1. There's another index in the query MySQL deems more appropriate to use, and it can use only one. The solution is usually an index spanning multiple columns if their normal method of retrieval is by value of more then one column.
  2. MySQL decides there are to many matching rows, and thinks a tablescan is probably faster. If that isn't the case, sometimes an ANALYZE TABLE helps.
  3. In more complex queries, it decides not to use it based on extremely intelligent thought-out voodoo in the query-plan that for some reason just not fits your current requirements.

In the case of (2) or (3), you could coax MySQL into using the index by index hint sytax, but if you do, be sure run some tests to determine whether it actually improves performance to use the index as you hint it.

What is syntax for selector in CSS for next element?

This is called the adjacent sibling selector, and it is represented by a plus sign...

h1.hc-reform + p {
  clear:both;
}

Note: this is not supported in IE6 or older.

SQL SELECT everything after a certain character

Try this in MySQL.

right(field,((CHAR_LENGTH(field))-(InStr(field,','))))

Read all files in a folder and apply a function to each data frame

usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats

plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)

Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.

require(plyr)
require(dostats)

files <- list.files(pattern = ".csv")


for (i in seq_along(files)) {

    assign(paste("Df", i, sep = "."), read.csv(files[i]))

    assign(paste(paste("Df", i, sep = ""), "summary", sep = "."), 
           ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))

}

Here is the output

R> Df1.summary
  .id sum min   mean median max
1   A  34   4 5.6667    5.5   8
2   B  22   1 3.6667    3.0   9
R> Df2.summary
  .id sum min   mean median max
1   A  21   1 3.5000    3.5   6
2   B  16   1 2.6667    2.5   5

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

I got this issue for a console Application.

In my case i just changed the Platform Target to "Any CPU" which you can see when you right click your solution and click on properties , you will find a Tab "Build" click on it, you will see "Platform target:" change it to "Any CPU", which will solve your issue

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

AngularJS ng-style with a conditional expression

As @Yoshi said, from angular 1.1.5 you can use-it without any change.

If you use angular < 1.1.5, you can use ng-class.

.largeWidth {
    width: 100%;
}

.smallWidth {
    width: 0%;
}

// [...]

ng-class="{largeWidth: myVar == 'ok', smallWidth: myVar != 'ok'}"

How to get current language code with Swift?

Swift 5.3:

let languagePrefix = Locale.preferredLanguages[0]
print(languagePrefix)

Pointer vs. Reference

Use a reference when you can, use a pointer when you have to. From C++ FAQ: "When should I use references, and when should I use pointers?"

Swift do-try-catch syntax

I was also disappointed by the lack of type a function can throw, but I get it now thanks to @rickster and I'll summarize it like this: let's say we could specify the type a function throws, we would have something like this:

enum MyError: ErrorType { case ErrorA, ErrorB }

func myFunctionThatThrows() throws MyError { ...throw .ErrorA...throw .ErrorB... }

do {
    try myFunctionThatThrows()
}
case .ErrorA { ... }
case .ErrorB { ... }

The problem is that even if we don't change anything in myFunctionThatThrows, if we just add an error case to MyError:

enum MyError: ErrorType { case ErrorA, ErrorB, ErrorC }

we are screwed because our do/try/catch is no longer exhaustive, as well as any other place where we called functions that throw MyError

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

How to measure the a time-span in seconds using System.currentTimeMillis()?

// Convert millis to seconds. This can be simplified a bit,
// but I left it in this form for clarity.
long m = System.currentTimeMillis(); // that's our input
int s = Math.max(
  .18 * (Math.toRadians(m)/Math.PI),
  Math.pow( Math.E, Math.log(m)-Math.log(1000) )
);
System.out.println( "seconds: "+s );

Possible heap pollution via varargs parameter

When you use varargs, it can result in the creation of an Object[] to hold the arguments.

Due to escape analysis, the JIT can optimise away this array creation. (One of the few times I have found it does so) Its not guaranteed to be optimised away, but I wouldn't worry about it unless you see its an issue in your memory profiler.

AFAIK @SafeVarargs suppresses a warning by the compiler and doesn't change how the JIT behaves.

Scroll / Jump to id without jQuery

Oxi's answer is just wrong.¹

What you want is:

var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;

Working example:

(function (){
  var i = 20, l = 20, html = '';
  while (i--){
    html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
    html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
    html += '[ Scroll to #DIV' +i+ ' ]</a>';
    html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
  }
  document.write( html );
})();

¹ I haven't got enough reputation to comment on his answer

A general tree implementation?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name, self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

How do I iterate through the files in a directory in Java?

I like to use Optional and streams to have a net and clear solution, i use the below code to iterate over a directory. the below cases are handled by the code:

  1. handle the case of empty directory
  2. Laziness

but as mentioned by others, you still have to pay attention for outOfMemory in case you have huge folders

    File directoryFile = new File("put your path here");
    Stream<File> files = Optional.ofNullable(directoryFile// directoryFile
                                                          .listFiles(File::isDirectory)) // filter only directories(change with null if you don't need to filter)
                                 .stream()
                                 .flatMap(Arrays::stream);// flatmap from Stream<File[]> to Stream<File>

jQuery hasAttr checking to see if there is an attribute on an element

Late to the party, but... why not just this.hasAttribute("name")?

Refer This

Retrieving a random item from ArrayList

The solution is not good, even you fixed your naming and unreachable statement of that print out.

things you should pay attention also 1. randomness seed, and large data, will num of item is so big returned num of that random < itemlist.size().

  1. you didn't handle multithread, you might get index out of bound exception

Call a stored procedure with parameter in c#

As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/

SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
    sqlAccess.Procedure()
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtFirstName.Text)
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtLastName.Text)
         .ExecuteNonQuery("StoredProcedureName");

How to download a file over HTTP?

If speed matters to you, I made a small performance test for the modules urllib and wget, and regarding wget I tried once with status bar and once without. I took three different 500MB files to test with (different files- to eliminate the chance that there is some caching going on under the hood). Tested on debian machine, with python2.

First, these are the results (they are similar in different runs):

$ python wget_test.py 
urlretrive_test : starting
urlretrive_test : 6.56
==============
wget_no_bar_test : starting
wget_no_bar_test : 7.20
==============
wget_with_bar_test : starting
100% [......................................................................] 541335552 / 541335552
wget_with_bar_test : 50.49
==============

The way I performed the test is using "profile" decorator. This is the full code:

import wget
import urllib
import time
from functools import wraps

def profile(func):
    @wraps(func)
    def inner(*args):
        print func.__name__, ": starting"
        start = time.time()
        ret = func(*args)
        end = time.time()
        print func.__name__, ": {:.2f}".format(end - start)
        return ret
    return inner

url1 = 'http://host.com/500a.iso'
url2 = 'http://host.com/500b.iso'
url3 = 'http://host.com/500c.iso'

def do_nothing(*args):
    pass

@profile
def urlretrive_test(url):
    return urllib.urlretrieve(url)

@profile
def wget_no_bar_test(url):
    return wget.download(url, out='/tmp/', bar=do_nothing)

@profile
def wget_with_bar_test(url):
    return wget.download(url, out='/tmp/')

urlretrive_test(url1)
print '=============='
time.sleep(1)

wget_no_bar_test(url2)
print '=============='
time.sleep(1)

wget_with_bar_test(url3)
print '=============='
time.sleep(1)

urllib seems to be the fastest

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

First install "Microsoft ASP.NET Web API Client" nuget package:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}

And this is how to use it:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);

or

TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
        .Result

or (not recommended)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

Generating a drop down list of timezones with PHP

If you don't want to be dependent on static timezone list, or want to display the offset along with timezone.

Here is what I came up with

function timezones()
{
    $timezones = \DateTimeZone::listIdentifiers();
    $items = array();
    foreach($timezones as $timezoneId) {
        $timezone = new \DateTimeZone($timezoneId);
        $offsetInSeconds = $timezone->getOffset(new \DateTime());
        $items[$timezoneId] = $offsetInSeconds;
    }
    asort($items);
    array_walk ($items, function (&$offsetInSeconds, &$timezoneId) { 
        $offsetPrefix = $offsetInSeconds < 0 ? '-' : '+';
        $offset = gmdate('H:i', abs($offsetInSeconds));
        $offset = "(GMT${offsetPrefix}${offset}) ".$timezoneId;
        $offsetInSeconds = $offset;
    });
    return $items;
}

Which gives me the following result

Array
(
    [Pacific/Midway] => (GMT-11:00) Pacific/Midway
    [Pacific/Pago_Pago] => (GMT-11:00) Pacific/Pago_Pago
    [Pacific/Niue] => (GMT-11:00) Pacific/Niue
    [America/Adak] => (GMT-10:00) America/Adak
    [Pacific/Tahiti] => (GMT-10:00) Pacific/Tahiti
    [Pacific/Rarotonga] => (GMT-10:00) Pacific/Rarotonga
    [Pacific/Honolulu] => (GMT-10:00) Pacific/Honolulu
    [Pacific/Marquesas] => (GMT-09:30) Pacific/Marquesas
    [America/Sitka] => (GMT-09:00) America/Sitka
    [Pacific/Gambier] => (GMT-09:00) Pacific/Gambier
    [America/Yakutat] => (GMT-09:00) America/Yakutat
    [America/Juneau] => (GMT-09:00) America/Juneau
    [America/Nome] => (GMT-09:00) America/Nome
    [America/Anchorage] => (GMT-09:00) America/Anchorage
    [America/Metlakatla] => (GMT-09:00) America/Metlakatla
    [America/Los_Angeles] => (GMT-08:00) America/Los_Angeles
    [America/Tijuana] => (GMT-08:00) America/Tijuana
    [America/Whitehorse] => (GMT-08:00) America/Whitehorse
    [America/Vancouver] => (GMT-08:00) America/Vancouver
    [America/Dawson] => (GMT-08:00) America/Dawson
    [Pacific/Pitcairn] => (GMT-08:00) Pacific/Pitcairn
    [America/Mazatlan] => (GMT-07:00) America/Mazatlan
    [America/Fort_Nelson] => (GMT-07:00) America/Fort_Nelson
    [America/Yellowknife] => (GMT-07:00) America/Yellowknife
    [America/Inuvik] => (GMT-07:00) America/Inuvik
    [America/Edmonton] => (GMT-07:00) America/Edmonton
    [America/Denver] => (GMT-07:00) America/Denver
    [America/Chihuahua] => (GMT-07:00) America/Chihuahua
    [America/Boise] => (GMT-07:00) America/Boise
    [America/Ojinaga] => (GMT-07:00) America/Ojinaga
    [America/Cambridge_Bay] => (GMT-07:00) America/Cambridge_Bay
    [America/Dawson_Creek] => (GMT-07:00) America/Dawson_Creek
    [America/Phoenix] => (GMT-07:00) America/Phoenix
    [America/Hermosillo] => (GMT-07:00) America/Hermosillo
    [America/Creston] => (GMT-07:00) America/Creston
    [America/Matamoros] => (GMT-06:00) America/Matamoros
    [America/Menominee] => (GMT-06:00) America/Menominee
    [America/Indiana/Knox] => (GMT-06:00) America/Indiana/Knox
    [America/Managua] => (GMT-06:00) America/Managua
    [America/Bahia_Banderas] => (GMT-06:00) America/Bahia_Banderas
    [America/Indiana/Tell_City] => (GMT-06:00) America/Indiana/Tell_City
    [America/Belize] => (GMT-06:00) America/Belize
    [America/Chicago] => (GMT-06:00) America/Chicago
    [America/Guatemala] => (GMT-06:00) America/Guatemala
    [America/El_Salvador] => (GMT-06:00) America/El_Salvador
    [America/Merida] => (GMT-06:00) America/Merida
    [America/Costa_Rica] => (GMT-06:00) America/Costa_Rica
    [America/Mexico_City] => (GMT-06:00) America/Mexico_City
    [America/Winnipeg] => (GMT-06:00) America/Winnipeg
    [Pacific/Galapagos] => (GMT-06:00) Pacific/Galapagos
    [America/Resolute] => (GMT-06:00) America/Resolute
    [America/Regina] => (GMT-06:00) America/Regina
    [America/Rankin_Inlet] => (GMT-06:00) America/Rankin_Inlet
    [America/Rainy_River] => (GMT-06:00) America/Rainy_River
    [America/North_Dakota/New_Salem] => (GMT-06:00) America/North_Dakota/New_Salem
    [America/North_Dakota/Beulah] => (GMT-06:00) America/North_Dakota/Beulah
    [America/North_Dakota/Center] => (GMT-06:00) America/North_Dakota/Center
    [America/Tegucigalpa] => (GMT-06:00) America/Tegucigalpa
    [America/Swift_Current] => (GMT-06:00) America/Swift_Current
    [America/Monterrey] => (GMT-06:00) America/Monterrey
    [America/Pangnirtung] => (GMT-05:00) America/Pangnirtung
    [America/Indiana/Petersburg] => (GMT-05:00) America/Indiana/Petersburg
    [America/Indiana/Marengo] => (GMT-05:00) America/Indiana/Marengo
    [America/Bogota] => (GMT-05:00) America/Bogota
    [America/Toronto] => (GMT-05:00) America/Toronto
    [America/Detroit] => (GMT-05:00) America/Detroit
    [America/Panama] => (GMT-05:00) America/Panama
    [America/Cancun] => (GMT-05:00) America/Cancun
    [America/Rio_Branco] => (GMT-05:00) America/Rio_Branco
    [America/Port-au-Prince] => (GMT-05:00) America/Port-au-Prince
    [America/Cayman] => (GMT-05:00) America/Cayman
    [America/Grand_Turk] => (GMT-05:00) America/Grand_Turk
    [America/Havana] => (GMT-05:00) America/Havana
    [America/Indiana/Indianapolis] => (GMT-05:00) America/Indiana/Indianapolis
    [America/Indiana/Vevay] => (GMT-05:00) America/Indiana/Vevay
    [America/Guayaquil] => (GMT-05:00) America/Guayaquil
    [America/Nipigon] => (GMT-05:00) America/Nipigon
    [America/Indiana/Vincennes] => (GMT-05:00) America/Indiana/Vincennes
    [America/Atikokan] => (GMT-05:00) America/Atikokan
    [America/Indiana/Winamac] => (GMT-05:00) America/Indiana/Winamac
    [America/New_York] => (GMT-05:00) America/New_York
    [America/Iqaluit] => (GMT-05:00) America/Iqaluit
    [America/Jamaica] => (GMT-05:00) America/Jamaica
    [America/Nassau] => (GMT-05:00) America/Nassau
    [America/Kentucky/Louisville] => (GMT-05:00) America/Kentucky/Louisville
    [America/Kentucky/Monticello] => (GMT-05:00) America/Kentucky/Monticello
    [America/Eirunepe] => (GMT-05:00) America/Eirunepe
    [Pacific/Easter] => (GMT-05:00) Pacific/Easter
    [America/Lima] => (GMT-05:00) America/Lima
    [America/Thunder_Bay] => (GMT-05:00) America/Thunder_Bay
    [America/Guadeloupe] => (GMT-04:00) America/Guadeloupe
    [America/Manaus] => (GMT-04:00) America/Manaus
    [America/Guyana] => (GMT-04:00) America/Guyana
    [America/Halifax] => (GMT-04:00) America/Halifax
    [America/Puerto_Rico] => (GMT-04:00) America/Puerto_Rico
    [America/Porto_Velho] => (GMT-04:00) America/Porto_Velho
    [America/Port_of_Spain] => (GMT-04:00) America/Port_of_Spain
    [America/Montserrat] => (GMT-04:00) America/Montserrat
    [America/Moncton] => (GMT-04:00) America/Moncton
    [America/Martinique] => (GMT-04:00) America/Martinique
    [America/Kralendijk] => (GMT-04:00) America/Kralendijk
    [America/La_Paz] => (GMT-04:00) America/La_Paz
    [America/Marigot] => (GMT-04:00) America/Marigot
    [America/Lower_Princes] => (GMT-04:00) America/Lower_Princes
    [America/Grenada] => (GMT-04:00) America/Grenada
    [America/Santo_Domingo] => (GMT-04:00) America/Santo_Domingo
    [America/Goose_Bay] => (GMT-04:00) America/Goose_Bay
    [America/Caracas] => (GMT-04:00) America/Caracas
    [America/Anguilla] => (GMT-04:00) America/Anguilla
    [America/St_Barthelemy] => (GMT-04:00) America/St_Barthelemy
    [America/Barbados] => (GMT-04:00) America/Barbados
    [America/St_Kitts] => (GMT-04:00) America/St_Kitts
    [America/Blanc-Sablon] => (GMT-04:00) America/Blanc-Sablon
    [America/Boa_Vista] => (GMT-04:00) America/Boa_Vista
    [America/St_Lucia] => (GMT-04:00) America/St_Lucia
    [America/St_Thomas] => (GMT-04:00) America/St_Thomas
    [America/Antigua] => (GMT-04:00) America/Antigua
    [America/St_Vincent] => (GMT-04:00) America/St_Vincent
    [America/Thule] => (GMT-04:00) America/Thule
    [America/Curacao] => (GMT-04:00) America/Curacao
    [America/Tortola] => (GMT-04:00) America/Tortola
    [America/Dominica] => (GMT-04:00) America/Dominica
    [Atlantic/Bermuda] => (GMT-04:00) Atlantic/Bermuda
    [America/Glace_Bay] => (GMT-04:00) America/Glace_Bay
    [America/Aruba] => (GMT-04:00) America/Aruba
    [America/St_Johns] => (GMT-03:30) America/St_Johns
    [America/Argentina/Tucuman] => (GMT-03:00) America/Argentina/Tucuman
    [America/Belem] => (GMT-03:00) America/Belem
    [America/Santiago] => (GMT-03:00) America/Santiago
    [America/Santarem] => (GMT-03:00) America/Santarem
    [America/Recife] => (GMT-03:00) America/Recife
    [America/Punta_Arenas] => (GMT-03:00) America/Punta_Arenas
    [Atlantic/Stanley] => (GMT-03:00) Atlantic/Stanley
    [America/Paramaribo] => (GMT-03:00) America/Paramaribo
    [America/Fortaleza] => (GMT-03:00) America/Fortaleza
    [America/Argentina/San_Luis] => (GMT-03:00) America/Argentina/San_Luis
    [Antarctica/Palmer] => (GMT-03:00) Antarctica/Palmer
    [America/Montevideo] => (GMT-03:00) America/Montevideo
    [America/Cuiaba] => (GMT-03:00) America/Cuiaba
    [America/Miquelon] => (GMT-03:00) America/Miquelon
    [America/Cayenne] => (GMT-03:00) America/Cayenne
    [America/Campo_Grande] => (GMT-03:00) America/Campo_Grande
    [Antarctica/Rothera] => (GMT-03:00) Antarctica/Rothera
    [America/Godthab] => (GMT-03:00) America/Godthab
    [America/Bahia] => (GMT-03:00) America/Bahia
    [America/Asuncion] => (GMT-03:00) America/Asuncion
    [America/Argentina/Ushuaia] => (GMT-03:00) America/Argentina/Ushuaia
    [America/Argentina/La_Rioja] => (GMT-03:00) America/Argentina/La_Rioja
    [America/Araguaina] => (GMT-03:00) America/Araguaina
    [America/Argentina/Buenos_Aires] => (GMT-03:00) America/Argentina/Buenos_Aires
    [America/Argentina/Rio_Gallegos] => (GMT-03:00) America/Argentina/Rio_Gallegos
    [America/Argentina/Catamarca] => (GMT-03:00) America/Argentina/Catamarca
    [America/Maceio] => (GMT-03:00) America/Maceio
    [America/Argentina/San_Juan] => (GMT-03:00) America/Argentina/San_Juan
    [America/Argentina/Salta] => (GMT-03:00) America/Argentina/Salta
    [America/Argentina/Mendoza] => (GMT-03:00) America/Argentina/Mendoza
    [America/Argentina/Cordoba] => (GMT-03:00) America/Argentina/Cordoba
    [America/Argentina/Jujuy] => (GMT-03:00) America/Argentina/Jujuy
    [Atlantic/South_Georgia] => (GMT-02:00) Atlantic/South_Georgia
    [America/Noronha] => (GMT-02:00) America/Noronha
    [America/Sao_Paulo] => (GMT-02:00) America/Sao_Paulo
    [Atlantic/Cape_Verde] => (GMT-01:00) Atlantic/Cape_Verde
    [Atlantic/Azores] => (GMT-01:00) Atlantic/Azores
    [America/Scoresbysund] => (GMT-01:00) America/Scoresbysund
    [Europe/Lisbon] => (GMT+00:00) Europe/Lisbon
    [Europe/London] => (GMT+00:00) Europe/London
    [Europe/Jersey] => (GMT+00:00) Europe/Jersey
    [Europe/Isle_of_Man] => (GMT+00:00) Europe/Isle_of_Man
    [Atlantic/Faroe] => (GMT+00:00) Atlantic/Faroe
    [Europe/Guernsey] => (GMT+00:00) Europe/Guernsey
    [Europe/Dublin] => (GMT+00:00) Europe/Dublin
    [Atlantic/St_Helena] => (GMT+00:00) Atlantic/St_Helena
    [Atlantic/Reykjavik] => (GMT+00:00) Atlantic/Reykjavik
    [Atlantic/Madeira] => (GMT+00:00) Atlantic/Madeira
    [Atlantic/Canary] => (GMT+00:00) Atlantic/Canary
    [Africa/Accra] => (GMT+00:00) Africa/Accra
    [Antarctica/Troll] => (GMT+00:00) Antarctica/Troll
    [Africa/Abidjan] => (GMT+00:00) Africa/Abidjan
    [UTC] => (GMT+00:00) UTC
    [America/Danmarkshavn] => (GMT+00:00) America/Danmarkshavn
    [Africa/Monrovia] => (GMT+00:00) Africa/Monrovia
    [Africa/Dakar] => (GMT+00:00) Africa/Dakar
    [Africa/Conakry] => (GMT+00:00) Africa/Conakry
    [Africa/Casablanca] => (GMT+00:00) Africa/Casablanca
    [Africa/Lome] => (GMT+00:00) Africa/Lome
    [Africa/Freetown] => (GMT+00:00) Africa/Freetown
    [Africa/El_Aaiun] => (GMT+00:00) Africa/El_Aaiun
    [Africa/Bissau] => (GMT+00:00) Africa/Bissau
    [Africa/Nouakchott] => (GMT+00:00) Africa/Nouakchott
    [Africa/Banjul] => (GMT+00:00) Africa/Banjul
    [Africa/Ouagadougou] => (GMT+00:00) Africa/Ouagadougou
    [Africa/Bamako] => (GMT+00:00) Africa/Bamako
    [Europe/Gibraltar] => (GMT+01:00) Europe/Gibraltar
    [Africa/Bangui] => (GMT+01:00) Africa/Bangui
    [Europe/Ljubljana] => (GMT+01:00) Europe/Ljubljana
    [Africa/Ceuta] => (GMT+01:00) Africa/Ceuta
    [Africa/Algiers] => (GMT+01:00) Africa/Algiers
    [Europe/Busingen] => (GMT+01:00) Europe/Busingen
    [Europe/Copenhagen] => (GMT+01:00) Europe/Copenhagen
    [Europe/Madrid] => (GMT+01:00) Europe/Madrid
    [Europe/Budapest] => (GMT+01:00) Europe/Budapest
    [Europe/Brussels] => (GMT+01:00) Europe/Brussels
    [Europe/Bratislava] => (GMT+01:00) Europe/Bratislava
    [Europe/Berlin] => (GMT+01:00) Europe/Berlin
    [Europe/Belgrade] => (GMT+01:00) Europe/Belgrade
    [Europe/Andorra] => (GMT+01:00) Europe/Andorra
    [Europe/Amsterdam] => (GMT+01:00) Europe/Amsterdam
    [Europe/Luxembourg] => (GMT+01:00) Europe/Luxembourg
    [Europe/Monaco] => (GMT+01:00) Europe/Monaco
    [Europe/Malta] => (GMT+01:00) Europe/Malta
    [Europe/Tirane] => (GMT+01:00) Europe/Tirane
    [Europe/Zurich] => (GMT+01:00) Europe/Zurich
    [Europe/Zagreb] => (GMT+01:00) Europe/Zagreb
    [Europe/Warsaw] => (GMT+01:00) Europe/Warsaw
    [Europe/Vienna] => (GMT+01:00) Europe/Vienna
    [Europe/Vatican] => (GMT+01:00) Europe/Vatican
    [Europe/Vaduz] => (GMT+01:00) Europe/Vaduz
    [Europe/Stockholm] => (GMT+01:00) Europe/Stockholm
    [Africa/Brazzaville] => (GMT+01:00) Africa/Brazzaville
    [Europe/Skopje] => (GMT+01:00) Europe/Skopje
    [Europe/Sarajevo] => (GMT+01:00) Europe/Sarajevo
    [Europe/San_Marino] => (GMT+01:00) Europe/San_Marino
    [Europe/Rome] => (GMT+01:00) Europe/Rome
    [Europe/Prague] => (GMT+01:00) Europe/Prague
    [Europe/Paris] => (GMT+01:00) Europe/Paris
    [Europe/Oslo] => (GMT+01:00) Europe/Oslo
    [Europe/Podgorica] => (GMT+01:00) Europe/Podgorica
    [Africa/Douala] => (GMT+01:00) Africa/Douala
    [Arctic/Longyearbyen] => (GMT+01:00) Arctic/Longyearbyen
    [Africa/Malabo] => (GMT+01:00) Africa/Malabo
    [Africa/Kinshasa] => (GMT+01:00) Africa/Kinshasa
    [Africa/Libreville] => (GMT+01:00) Africa/Libreville
    [Africa/Ndjamena] => (GMT+01:00) Africa/Ndjamena
    [Africa/Lagos] => (GMT+01:00) Africa/Lagos
    [Africa/Niamey] => (GMT+01:00) Africa/Niamey
    [Africa/Porto-Novo] => (GMT+01:00) Africa/Porto-Novo
    [Africa/Sao_Tome] => (GMT+01:00) Africa/Sao_Tome
    [Africa/Luanda] => (GMT+01:00) Africa/Luanda
    [Africa/Tunis] => (GMT+01:00) Africa/Tunis
    [Europe/Uzhgorod] => (GMT+02:00) Europe/Uzhgorod
    [Africa/Harare] => (GMT+02:00) Africa/Harare
    [Europe/Mariehamn] => (GMT+02:00) Europe/Mariehamn
    [Africa/Lubumbashi] => (GMT+02:00) Africa/Lubumbashi
    [Asia/Nicosia] => (GMT+02:00) Asia/Nicosia
    [Africa/Windhoek] => (GMT+02:00) Africa/Windhoek
    [Europe/Tallinn] => (GMT+02:00) Europe/Tallinn
    [Europe/Zaporozhye] => (GMT+02:00) Europe/Zaporozhye
    [Africa/Gaborone] => (GMT+02:00) Africa/Gaborone
    [Africa/Mbabane] => (GMT+02:00) Africa/Mbabane
    [Africa/Khartoum] => (GMT+02:00) Africa/Khartoum
    [Africa/Johannesburg] => (GMT+02:00) Africa/Johannesburg
    [Europe/Vilnius] => (GMT+02:00) Europe/Vilnius
    [Africa/Maseru] => (GMT+02:00) Africa/Maseru
    [Africa/Lusaka] => (GMT+02:00) Africa/Lusaka
    [Europe/Riga] => (GMT+02:00) Europe/Riga
    [Africa/Kigali] => (GMT+02:00) Africa/Kigali
    [Europe/Helsinki] => (GMT+02:00) Europe/Helsinki
    [Africa/Maputo] => (GMT+02:00) Africa/Maputo
    [Europe/Chisinau] => (GMT+02:00) Europe/Chisinau
    [Europe/Sofia] => (GMT+02:00) Europe/Sofia
    [Asia/Beirut] => (GMT+02:00) Asia/Beirut
    [Africa/Blantyre] => (GMT+02:00) Africa/Blantyre
    [Asia/Jerusalem] => (GMT+02:00) Asia/Jerusalem
    [Asia/Gaza] => (GMT+02:00) Asia/Gaza
    [Asia/Amman] => (GMT+02:00) Asia/Amman
    [Asia/Famagusta] => (GMT+02:00) Asia/Famagusta
    [Europe/Athens] => (GMT+02:00) Europe/Athens
    [Africa/Bujumbura] => (GMT+02:00) Africa/Bujumbura
    [Asia/Hebron] => (GMT+02:00) Asia/Hebron
    [Europe/Kaliningrad] => (GMT+02:00) Europe/Kaliningrad
    [Africa/Cairo] => (GMT+02:00) Africa/Cairo
    [Europe/Kiev] => (GMT+02:00) Europe/Kiev
    [Europe/Bucharest] => (GMT+02:00) Europe/Bucharest
    [Asia/Damascus] => (GMT+02:00) Asia/Damascus
    [Africa/Tripoli] => (GMT+02:00) Africa/Tripoli
    [Asia/Baghdad] => (GMT+03:00) Asia/Baghdad
    [Africa/Djibouti] => (GMT+03:00) Africa/Djibouti
    [Asia/Aden] => (GMT+03:00) Asia/Aden
    [Asia/Bahrain] => (GMT+03:00) Asia/Bahrain
    [Europe/Istanbul] => (GMT+03:00) Europe/Istanbul
    [Africa/Juba] => (GMT+03:00) Africa/Juba
    [Europe/Kirov] => (GMT+03:00) Europe/Kirov
    [Europe/Moscow] => (GMT+03:00) Europe/Moscow
    [Antarctica/Syowa] => (GMT+03:00) Antarctica/Syowa
    [Europe/Minsk] => (GMT+03:00) Europe/Minsk
    [Africa/Kampala] => (GMT+03:00) Africa/Kampala
    [Africa/Dar_es_Salaam] => (GMT+03:00) Africa/Dar_es_Salaam
    [Europe/Simferopol] => (GMT+03:00) Europe/Simferopol
    [Asia/Riyadh] => (GMT+03:00) Asia/Riyadh
    [Indian/Antananarivo] => (GMT+03:00) Indian/Antananarivo
    [Asia/Kuwait] => (GMT+03:00) Asia/Kuwait
    [Africa/Nairobi] => (GMT+03:00) Africa/Nairobi
    [Indian/Mayotte] => (GMT+03:00) Indian/Mayotte
    [Africa/Mogadishu] => (GMT+03:00) Africa/Mogadishu
    [Asia/Qatar] => (GMT+03:00) Asia/Qatar
    [Europe/Volgograd] => (GMT+03:00) Europe/Volgograd
    [Africa/Asmara] => (GMT+03:00) Africa/Asmara
    [Africa/Addis_Ababa] => (GMT+03:00) Africa/Addis_Ababa
    [Indian/Comoro] => (GMT+03:00) Indian/Comoro
    [Asia/Tehran] => (GMT+03:30) Asia/Tehran
    [Europe/Saratov] => (GMT+04:00) Europe/Saratov
    [Indian/Reunion] => (GMT+04:00) Indian/Reunion
    [Europe/Astrakhan] => (GMT+04:00) Europe/Astrakhan
    [Asia/Baku] => (GMT+04:00) Asia/Baku
    [Asia/Dubai] => (GMT+04:00) Asia/Dubai
    [Indian/Mauritius] => (GMT+04:00) Indian/Mauritius
    [Indian/Mahe] => (GMT+04:00) Indian/Mahe
    [Asia/Tbilisi] => (GMT+04:00) Asia/Tbilisi
    [Asia/Yerevan] => (GMT+04:00) Asia/Yerevan
    [Asia/Muscat] => (GMT+04:00) Asia/Muscat
    [Europe/Samara] => (GMT+04:00) Europe/Samara
    [Europe/Ulyanovsk] => (GMT+04:00) Europe/Ulyanovsk
    [Asia/Kabul] => (GMT+04:30) Asia/Kabul
    [Antarctica/Mawson] => (GMT+05:00) Antarctica/Mawson
    [Asia/Samarkand] => (GMT+05:00) Asia/Samarkand
    [Asia/Aqtobe] => (GMT+05:00) Asia/Aqtobe
    [Indian/Maldives] => (GMT+05:00) Indian/Maldives
    [Asia/Ashgabat] => (GMT+05:00) Asia/Ashgabat
    [Asia/Atyrau] => (GMT+05:00) Asia/Atyrau
    [Asia/Dushanbe] => (GMT+05:00) Asia/Dushanbe
    [Asia/Yekaterinburg] => (GMT+05:00) Asia/Yekaterinburg
    [Asia/Oral] => (GMT+05:00) Asia/Oral
    [Asia/Aqtau] => (GMT+05:00) Asia/Aqtau
    [Asia/Karachi] => (GMT+05:00) Asia/Karachi
    [Asia/Tashkent] => (GMT+05:00) Asia/Tashkent
    [Indian/Kerguelen] => (GMT+05:00) Indian/Kerguelen
    [Asia/Colombo] => (GMT+05:30) Asia/Colombo
    [Asia/Kolkata] => (GMT+05:30) Asia/Kolkata
    [Asia/Kathmandu] => (GMT+05:45) Asia/Kathmandu
    [Antarctica/Vostok] => (GMT+06:00) Antarctica/Vostok
    [Indian/Chagos] => (GMT+06:00) Indian/Chagos
    [Asia/Almaty] => (GMT+06:00) Asia/Almaty
    [Asia/Omsk] => (GMT+06:00) Asia/Omsk
    [Asia/Dhaka] => (GMT+06:00) Asia/Dhaka
    [Asia/Bishkek] => (GMT+06:00) Asia/Bishkek
    [Asia/Urumqi] => (GMT+06:00) Asia/Urumqi
    [Asia/Thimphu] => (GMT+06:00) Asia/Thimphu
    [Asia/Qyzylorda] => (GMT+06:00) Asia/Qyzylorda
    [Indian/Cocos] => (GMT+06:30) Indian/Cocos
    [Asia/Yangon] => (GMT+06:30) Asia/Yangon
    [Asia/Novokuznetsk] => (GMT+07:00) Asia/Novokuznetsk
    [Asia/Barnaul] => (GMT+07:00) Asia/Barnaul
    [Antarctica/Davis] => (GMT+07:00) Antarctica/Davis
    [Asia/Novosibirsk] => (GMT+07:00) Asia/Novosibirsk
    [Asia/Krasnoyarsk] => (GMT+07:00) Asia/Krasnoyarsk
    [Asia/Phnom_Penh] => (GMT+07:00) Asia/Phnom_Penh
    [Asia/Pontianak] => (GMT+07:00) Asia/Pontianak
    [Asia/Jakarta] => (GMT+07:00) Asia/Jakarta
    [Asia/Hovd] => (GMT+07:00) Asia/Hovd
    [Asia/Tomsk] => (GMT+07:00) Asia/Tomsk
    [Asia/Ho_Chi_Minh] => (GMT+07:00) Asia/Ho_Chi_Minh
    [Asia/Vientiane] => (GMT+07:00) Asia/Vientiane
    [Indian/Christmas] => (GMT+07:00) Indian/Christmas
    [Asia/Bangkok] => (GMT+07:00) Asia/Bangkok
    [Asia/Choibalsan] => (GMT+08:00) Asia/Choibalsan
    [Asia/Taipei] => (GMT+08:00) Asia/Taipei
    [Asia/Makassar] => (GMT+08:00) Asia/Makassar
    [Asia/Macau] => (GMT+08:00) Asia/Macau
    [Asia/Kuching] => (GMT+08:00) Asia/Kuching
    [Asia/Kuala_Lumpur] => (GMT+08:00) Asia/Kuala_Lumpur
    [Asia/Shanghai] => (GMT+08:00) Asia/Shanghai
    [Asia/Singapore] => (GMT+08:00) Asia/Singapore
    [Asia/Brunei] => (GMT+08:00) Asia/Brunei
    [Asia/Irkutsk] => (GMT+08:00) Asia/Irkutsk
    [Asia/Ulaanbaatar] => (GMT+08:00) Asia/Ulaanbaatar
    [Australia/Perth] => (GMT+08:00) Australia/Perth
    [Asia/Hong_Kong] => (GMT+08:00) Asia/Hong_Kong
    [Antarctica/Casey] => (GMT+08:00) Antarctica/Casey
    [Asia/Manila] => (GMT+08:00) Asia/Manila
    [Australia/Eucla] => (GMT+08:45) Australia/Eucla
    [Asia/Jayapura] => (GMT+09:00) Asia/Jayapura
    [Asia/Khandyga] => (GMT+09:00) Asia/Khandyga
    [Pacific/Palau] => (GMT+09:00) Pacific/Palau
    [Asia/Dili] => (GMT+09:00) Asia/Dili
    [Asia/Yakutsk] => (GMT+09:00) Asia/Yakutsk
    [Asia/Tokyo] => (GMT+09:00) Asia/Tokyo
    [Asia/Seoul] => (GMT+09:00) Asia/Seoul
    [Asia/Chita] => (GMT+09:00) Asia/Chita
    [Asia/Pyongyang] => (GMT+09:00) Asia/Pyongyang
    [Australia/Darwin] => (GMT+09:30) Australia/Darwin
    [Asia/Ust-Nera] => (GMT+10:00) Asia/Ust-Nera
    [Pacific/Chuuk] => (GMT+10:00) Pacific/Chuuk
    [Antarctica/DumontDUrville] => (GMT+10:00) Antarctica/DumontDUrville
    [Pacific/Guam] => (GMT+10:00) Pacific/Guam
    [Pacific/Port_Moresby] => (GMT+10:00) Pacific/Port_Moresby
    [Asia/Vladivostok] => (GMT+10:00) Asia/Vladivostok
    [Australia/Brisbane] => (GMT+10:00) Australia/Brisbane
    [Australia/Lindeman] => (GMT+10:00) Australia/Lindeman
    [Pacific/Saipan] => (GMT+10:00) Pacific/Saipan
    [Australia/Adelaide] => (GMT+10:30) Australia/Adelaide
    [Australia/Broken_Hill] => (GMT+10:30) Australia/Broken_Hill
    [Australia/Sydney] => (GMT+11:00) Australia/Sydney
    [Antarctica/Macquarie] => (GMT+11:00) Antarctica/Macquarie
    [Pacific/Noumea] => (GMT+11:00) Pacific/Noumea
    [Pacific/Norfolk] => (GMT+11:00) Pacific/Norfolk
    [Australia/Melbourne] => (GMT+11:00) Australia/Melbourne
    [Pacific/Kosrae] => (GMT+11:00) Pacific/Kosrae
    [Pacific/Pohnpei] => (GMT+11:00) Pacific/Pohnpei
    [Australia/Currie] => (GMT+11:00) Australia/Currie
    [Pacific/Guadalcanal] => (GMT+11:00) Pacific/Guadalcanal
    [Pacific/Efate] => (GMT+11:00) Pacific/Efate
    [Australia/Hobart] => (GMT+11:00) Australia/Hobart
    [Asia/Magadan] => (GMT+11:00) Asia/Magadan
    [Asia/Sakhalin] => (GMT+11:00) Asia/Sakhalin
    [Pacific/Bougainville] => (GMT+11:00) Pacific/Bougainville
    [Australia/Lord_Howe] => (GMT+11:00) Australia/Lord_Howe
    [Asia/Srednekolymsk] => (GMT+11:00) Asia/Srednekolymsk
    [Pacific/Fiji] => (GMT+12:00) Pacific/Fiji
    [Pacific/Wake] => (GMT+12:00) Pacific/Wake
    [Pacific/Nauru] => (GMT+12:00) Pacific/Nauru
    [Pacific/Majuro] => (GMT+12:00) Pacific/Majuro
    [Asia/Kamchatka] => (GMT+12:00) Asia/Kamchatka
    [Pacific/Kwajalein] => (GMT+12:00) Pacific/Kwajalein
    [Pacific/Funafuti] => (GMT+12:00) Pacific/Funafuti
    [Pacific/Wallis] => (GMT+12:00) Pacific/Wallis
    [Asia/Anadyr] => (GMT+12:00) Asia/Anadyr
    [Pacific/Tarawa] => (GMT+12:00) Pacific/Tarawa
    [Pacific/Fakaofo] => (GMT+13:00) Pacific/Fakaofo
    [Pacific/Enderbury] => (GMT+13:00) Pacific/Enderbury
    [Pacific/Auckland] => (GMT+13:00) Pacific/Auckland
    [Antarctica/McMurdo] => (GMT+13:00) Antarctica/McMurdo
    [Pacific/Tongatapu] => (GMT+13:00) Pacific/Tongatapu
    [Pacific/Chatham] => (GMT+13:45) Pacific/Chatham
    [Pacific/Kiritimati] => (GMT+14:00) Pacific/Kiritimati
    [Pacific/Apia] => (GMT+14:00) Pacific/Apia
)

Disabling enter key for form

The better way I found here:

Dream.In.Code

action="javascript: void(0)" or action="return false;" (doesn't work on me)

Deserializing a JSON file with JavaScriptSerializer()

  1. You need to create a class that holds the user values, just like the response class User.
  2. Add a property to the Response class 'user' with the type of the new class for the user values User.

    public class Response {
    
        public string id { get; set; }
        public string text { get; set; }
        public string url { get; set; }
        public string width { get; set; }
        public string height { get; set; }
        public string size { get; set; }
        public string type { get; set; }
        public string timestamp { get; set; }
        public User user { get; set; }
    
    }
    
    public class User {
    
        public int id { get; set; }
        public string screen_name { get; set; }
    
    }
    

In general you should make sure the property types of the json and your CLR classes match up. It seems that the structure that you're trying to deserialize contains multiple number values (most likely int). I'm not sure if the JavaScriptSerializer is able to deserialize numbers into string fields automatically, but you should try to match your CLR type as close to the actual data as possible anyway.

Mysql select distinct

DISTINCT is not a function that applies only to some columns. It's a query modifier that applies to all columns in the select-list.

That is, DISTINCT reduces rows only if all columns are identical to the columns of another row.

DISTINCT must follow immediately after SELECT (along with other query modifiers, like SQL_CALC_FOUND_ROWS). Then following the query modifiers, you can list columns.

  • RIGHT: SELECT DISTINCT foo, ticket_id FROM table...

    Output a row for each distinct pairing of values across ticket_id and foo.

  • WRONG: SELECT foo, DISTINCT ticket_id FROM table...

    If there are three distinct values of ticket_id, would this return only three rows? What if there are six distinct values of foo? Which three values of the six possible values of foo should be output?
    It's ambiguous as written.

AngularJS routing without the hash '#'

If you are wanting to configure this locally on OS X 10.8 serving Angular with Apache then you might find the following in your .htaccess file helps:

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
    RewriteBase /~yourusername/appname/public/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !.*\.(css|js|html|png|jpg|jpeg|gif|txt)
    RewriteRule (.*) index.html [L]
</IfModule>

Options +FollowSymlinks if not set may give you a forbidden error in the logs like so:

Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden

Rewrite base is required otherwise requests will be resolved to your server root which locally by default is not your project directory unless you have specifically configured your vhosts, so you need to set the path so that the request finds your project root directory. For example on my machine I have a /Users/me/Sites directory where I keep all my projects. Like the old OS X set up.

The next two lines effectively say if the path is not a directory or a file, so you need to make sure you have no files or directories the same as your app route paths.

The next condition says if request not ending with file extensions specified so add what you need there

And the [L] last one is saying to serve the index.html file - your app for all other requests.

If you still have problems then check the apache log, it will probably give you useful hints:

/private/var/log/apache2/error_log

Inject service in app.config

Using $injector to call service methods in config

I had a similar issue and resolved it by using the $injector service as shown above. I tried injecting the service directly but ended up with a circular dependency on $http. The service displays a modal with the error and I am using ui-bootstrap modal which also has a dependency on $https.

    $httpProvider.interceptors.push(function($injector) {
    return {
        "responseError": function(response) {

            console.log("Error Response status: " + response.status);

            if (response.status === 0) {
                var myService= $injector.get("myService");
                myService.showError("An unexpected error occurred. Please refresh the page.")
            }
        }
    }

SQL Server insert if not exists best practice

Normalizing your operational tables as suggested by Transact Charlie, is a good idea, and will save many headaches and problems over time - but there are such things as interface tables, which support integration with external systems, and reporting tables, which support things like analytical processing; and those types of tables should not necessarily be normalized - in fact, very often it is much, much more convenient and performant for them to not be.

In this case, I think Transact Charlie's proposal for your operational tables is a good one.

But I would add an index (not necessarily unique) to CompetitorName in the Competitors table to support efficient joins on CompetitorName for the purposes of integration (loading of data from external sources), and I would put an interface table into the mix: CompetitionResults.

CompetitionResults should contain whatever data your competition results have in it. The point of an interface table like this one is to make it as quick and easy as possible to truncate and reload it from an Excel sheet or a CSV file, or whatever form you have that data in.

That interface table should not be considered part of the normalized set of operational tables. Then you can join with CompetitionResults as suggested by Richard, to insert records into Competitors that don't already exist, and update the ones that do (for example if you actually have more information about competitors, like their phone number or email address).

One thing I would note - in reality, Competitor Name, it seems to me, is very unlikely to be unique in your data. In 200,000 competitors, you may very well have 2 or more David Smiths, for example. So I would recommend that you collect more information from competitors, such as their phone number or an email address, or something which is more likely to be unique.

Your operational table, Competitors, should just have one column for each data item that contributes to a composite natural key; for example it should have one column for a primary email address. But the interface table should have a slot for old and new values for a primary email address, so that the old value can be use to look up the record in Competitors and update that part of it to the new value.

So CompetitionResults should have some "old" and "new" fields - oldEmail, newEmail, oldPhone, newPhone, etc. That way you can form a composite key, in Competitors, from CompetitorName, Email, and Phone.

Then when you have some competition results, you can truncate and reload your CompetitionResults table from your excel sheet or whatever you have, and run a single, efficient insert to insert all the new competitors into the Competitors table, and single, efficient update to update all the information about the existing competitors from the CompetitionResults. And you can do a single insert to insert new rows into the CompetitionCompetitors table. These things can be done in a ProcessCompetitionResults stored procedure, which could be executed after loading the CompetitionResults table.

That's a sort of rudimentary description of what I've seen done over and over in the real world with Oracle Applications, SAP, PeopleSoft, and a laundry list of other enterprise software suites.

One last comment I'd make is one I've made before on SO: If you create a foreign key that insures that a Competitor exists in the Competitors table before you can add a row with that Competitor in it to CompetitionCompetitors, make sure that foreign key is set to cascade updates and deletes. That way if you need to delete a competitor, you can do it and all the rows associated with that competitor will get automatically deleted. Otherwise, by default, the foreign key will require you to delete all the related rows out of CompetitionCompetitors before it will let you delete a Competitor.

(Some people think non-cascading foreign keys are a good safety precaution, but my experience is that they're just a freaking pain in the butt that are more often than not simply a result of an oversight and they create a bunch of make work for DBA's. Dealing with people accidentally deleting stuff is why you have things like "are you sure" dialogs and various types of regular backups and redundant data sources. It's far, far more common to actually want to delete a competitor, whose data is all messed up for example, than it is to accidentally delete one and then go "Oh no! I didn't mean to do that! And now I don't have their competition results! Aaaahh!" The latter is certainly common enough, so, you do need to be prepared for it, but the former is far more common, so the easiest and best way to prepare for the former, imo, is to just make foreign keys cascade updates and deletes.)

How to rename a class and its corresponding file in Eclipse?

To rename file using refactoring (which also updates all occurrences of name in other scripts):

  1. Save changes to file before using refactoring/renaming
  2. In Project Explorer view, right-click file to be renamed and select Refactor | Rename -or- select it and go to Refactor | Rename from the Menu Bar. A Rename File dialog will appear.
  3. Enter the file's new name.
  4. Check the "Update references" box and click Preview.
  5. You can scroll through changes using the Select Next / Previous Change scrolling arrows.
  6. Press OK to rename file and update all occurrences of the script name in other scripts.

See "PHP Developer User Guide > Tasks > Using Refactoring > Renaming Files".

Google Maps API OVER QUERY LIMIT per second limit


This approach is not correct beacuse of Google Server Overload. For more informations see https://gis.stackexchange.com/questions/15052/how-to-avoid-google-map-geocode-limit#answer-15365


By the way, if you wish to proceed anyway, here you can find a code that let you load multiple markers ajax sourced on google maps avoiding OVER_QUERY_LIMIT error.

I've tested on my onw server and it works!:

var lost_addresses = [];
    geocode_count  = 0;
    resNumber = 0;
    map = new GMaps({
       div: '#gmap_marker',
       lat: 43.921493,
       lng: 12.337646,
    });

function loadMarkerTimeout(timeout) {
    setTimeout(loadMarker, timeout)
}

function loadMarker() { 
    map.setZoom(6);         
    $.ajax({
            url: [Insert here your URL] ,
            type:'POST',
            data: {
                "action":   "loadMarker"
            },
            success:function(result){

                /***************************
                 * Assuming your ajax call
                 * return something like: 
                 *   array(
                 *      'status' => 'success',
                 *      'results'=> $resultsArray
                 *   );
                 **************************/

                var res=JSON.parse(result);
                if(res.status == 'success') {
                    resNumber = res.results.length;
                    //Call the geoCoder function
                    getGeoCodeFor(map, res.results);
                }
            }//success
    });//ajax
};//loadMarker()

$().ready(function(e) {
  loadMarker();
});

//Geocoder function
function getGeoCodeFor(maps, addresses) {
        $.each(addresses, function(i,e){                
                GMaps.geocode({
                    address: e.address,
                    callback: function(results, status) {
                            geocode_count++;        

                            if (status == 'OK') {       

                                //if the element is alreay in the array, remove it
                                lost_addresses = jQuery.grep(lost_addresses, function(value) {
                                    return value != e;
                                });


                                latlng = results[0].geometry.location;
                                map.addMarker({
                                        lat: latlng.lat(),
                                        lng: latlng.lng(),
                                        title: 'MyNewMarker',
                                    });//addMarker
                            } else if (status == 'ZERO_RESULTS') {
                                //alert('Sorry, no results found');
                            } else if(status == 'OVER_QUERY_LIMIT') {

                                //if the element is not in the losts_addresses array, add it! 
                                if( jQuery.inArray(e,lost_addresses) == -1) {
                                    lost_addresses.push(e);
                                }

                            } 

                            if(geocode_count == addresses.length) {
                                //set counter == 0 so it wont's stop next round
                                geocode_count = 0;

                                setTimeout(function() {
                                    getGeoCodeFor(maps, lost_addresses);
                                }, 2500);
                            }
                    }//callback
                });//GeoCode
        });//each
};//getGeoCodeFor()

Example:

_x000D_
_x000D_
map = new GMaps({_x000D_
  div: '#gmap_marker',_x000D_
  lat: 43.921493,_x000D_
  lng: 12.337646,_x000D_
});_x000D_
_x000D_
var jsonData = {  _x000D_
   "status":"success",_x000D_
   "results":[  _x000D_
  {  _x000D_
     "customerId":1,_x000D_
     "address":"Via Italia 43, Milano (MI)",_x000D_
     "customerName":"MyAwesomeCustomer1"_x000D_
  },_x000D_
  {  _x000D_
     "customerId":2,_x000D_
     "address":"Via Roma 10, Roma (RM)",_x000D_
     "customerName":"MyAwesomeCustomer2"_x000D_
  }_x000D_
   ]_x000D_
};_x000D_
   _x000D_
function loadMarkerTimeout(timeout) {_x000D_
  setTimeout(loadMarker, timeout)_x000D_
}_x000D_
_x000D_
function loadMarker() { _x000D_
  map.setZoom(6);_x000D_
 _x000D_
  $.ajax({_x000D_
    url: '/echo/html/',_x000D_
    type: "POST",_x000D_
    data: jsonData,_x000D_
    cache: false,_x000D_
    success:function(result){_x000D_
_x000D_
      var res=JSON.parse(result);_x000D_
      if(res.status == 'success') {_x000D_
        resNumber = res.results.length;_x000D_
        //Call the geoCoder function_x000D_
        getGeoCodeFor(map, res.results);_x000D_
      }_x000D_
    }//success_x000D_
  });//ajax_x000D_
  _x000D_
};//loadMarker()_x000D_
_x000D_
$().ready(function(e) {_x000D_
  loadMarker();_x000D_
});_x000D_
_x000D_
//Geocoder function_x000D_
function getGeoCodeFor(maps, addresses) {_x000D_
  $.each(addresses, function(i,e){    _x000D_
    GMaps.geocode({_x000D_
      address: e.address,_x000D_
      callback: function(results, status) {_x000D_
        geocode_count++;  _x000D_
        _x000D_
        console.log('Id: '+e.customerId+' | Status: '+status);_x000D_
        _x000D_
        if (status == 'OK') {  _x000D_
_x000D_
          //if the element is alreay in the array, remove it_x000D_
          lost_addresses = jQuery.grep(lost_addresses, function(value) {_x000D_
            return value != e;_x000D_
          });_x000D_
_x000D_
_x000D_
          latlng = results[0].geometry.location;_x000D_
          map.addMarker({_x000D_
            lat: latlng.lat(),_x000D_
            lng: latlng.lng(),_x000D_
            title: e.customerName,_x000D_
          });//addMarker_x000D_
        } else if (status == 'ZERO_RESULTS') {_x000D_
          //alert('Sorry, no results found');_x000D_
        } else if(status == 'OVER_QUERY_LIMIT') {_x000D_
_x000D_
          //if the element is not in the losts_addresses array, add it! _x000D_
          if( jQuery.inArray(e,lost_addresses) == -1) {_x000D_
            lost_addresses.push(e);_x000D_
          }_x000D_
_x000D_
        } _x000D_
_x000D_
        if(geocode_count == addresses.length) {_x000D_
          //set counter == 0 so it wont's stop next round_x000D_
          geocode_count = 0;_x000D_
_x000D_
          setTimeout(function() {_x000D_
            getGeoCodeFor(maps, lost_addresses);_x000D_
          }, 2500);_x000D_
        }_x000D_
      }//callback_x000D_
    });//GeoCode_x000D_
  });//each_x000D_
};//getGeoCodeFor()
_x000D_
#gmap_marker {_x000D_
  min-height:250px;_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  position: relative; _x000D_
  overflow: hidden;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.min.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<div id="gmap_marker"></div> <!-- /#gmap_marker -->
_x000D_
_x000D_
_x000D_

Javascript add method to object

you need to add it to Foo's prototype:

function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()

gnuplot : plotting data from multiple input files in a single graph

You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.

e.g.

filenames = "first second third fourth fifth"
plot for [file in filenames] file."dat" using 1:2 with lines

and

filename(n) = sprintf("file_%d", n)
plot for [i=1:10] filename(i) using 1:2 with lines

How do I enable/disable log levels in Android?

Stripping out the logging with proguard (see answer from @Christopher ) was easy and fast, but it caused stack traces from production to mismatch the source if there was any debug logging in the file.

Instead, here's a technique that uses different logging levels in development vs. production, assuming that proguard is used only in production. It recognizes production by seeing if proguard has renamed a given class name (in the example, I use "com.foo.Bar"--you would replace this with a fully-qualified class name that you know will be renamed by proguard).

This technique makes use of commons logging.

private void initLogging() {
    Level level = Level.WARNING;
    try {
        // in production, the shrinker/obfuscator proguard will change the
        // name of this class (and many others) so in development, this
        // class WILL exist as named, and we will have debug level
        Class.forName("com.foo.Bar");
        level = Level.FINE;
    } catch (Throwable t) {
        // no problem, we are in production mode
    }
    Handler[] handlers = Logger.getLogger("").getHandlers();
    for (Handler handler : handlers) {
        Log.d("log init", "handler: " + handler.getClass().getName());
        handler.setLevel(level);
    }
}

Laravel Eloquent get results grouped by days

You could also solve this problem in following way:

$totalView =  View::select(DB::raw('Date(read_at) as date'), DB::raw('count(*) as Views'))
        ->groupBy(DB::raw('Date(read_at)'))
        ->orderBy(DB::raw('Date(read_at)'))
        ->get();

How do I find the width & height of a terminal window?

There are some cases where your rows/LINES and columns do not match the actual size of the "terminal" being used. Perhaps you may not have a "tput" or "stty" available.

Here is a bash function you can use to visually check the size. This will work up to 140 columns x 80 rows. You can adjust the maximums as needed.

function term_size
{
    local i=0 digits='' tens_fmt='' tens_args=()
    for i in {80..8}
    do
        echo $i $(( i - 2 ))
    done
    echo "If columns below wrap, LINES is first number in highest line above,"
    echo "If truncated, LINES is second number."
    for i in {1..14}
    do
        digits="${digits}1234567890"
        tens_fmt="${tens_fmt}%10d"
        tens_args=("${tens_args[@]}" $i)
    done
    printf "$tens_fmt\n" "${tens_args[@]}"
    echo "$digits"
}

How to use C++ in Go

Seems that currently SWIG is best solution for this:

http://www.swig.org/Doc2.0/Go.html

It supports inheritance and even allows to subclass C++ class with Go struct so when overridden methods are called in C++ code, Go code is fired.

Section about C++ in Go FAQ is updated and now mentions SWIG and no longer says "because Go is garbage-collected it will be unwise to do so, at least naively".

Pass parameter to controller from @Html.ActionLink MVC 4

The problem must be with the value Model.Id which is null. You can confirm by assigning a value, e.g

@{         
     var blogPostId = 1;          
 }

If the error disappers, then u need to make sure that your model Id has a value before passing it to the view

Get Client Machine Name in PHP

In opposite to the most comments, I think it is possible to get the client's hostname (machine name) in plain PHP, but it's a little bit "dirty".

By requesting "NTLM" authorization via HTTP header...

if (!isset($headers['AUTHORIZATION']) || substr($headers['AUTHORIZATION'],0,4) !== 'NTLM'){
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: NTLM');
    exit;
}

You can force the client to send authorization credentials via NTLM format. The NTLM hash sent by the client to server contains, besides the login credtials, the clients machine name. This works cross-browser and PHP only.

$auth = $headers['AUTHORIZATION'];

if (substr($auth,0,5) == 'NTLM ') {
    $msg = base64_decode(substr($auth, 5));
    if (substr($msg, 0, 8) != "NTLMSSPx00")
            die('error header not recognised');

    if ($msg[8] == "x01") {
            $msg2 = "NTLMSSPx00x02"."x00x00x00x00".
                    "x00x00x00x00".
                    "x01x02x81x01".
                    "x00x00x00x00x00x00x00x00".
                    "x00x00x00x00x00x00x00x00".
                    "x00x00x00x00x30x00x00x00";

            header('HTTP/1.1 401 Unauthorized');
            header('WWW-Authenticate: NTLM '.trim(base64_encode($msg2)));
            exit;
    }
    else if ($msg[8] == "x03") {
            function get_msg_str($msg, $start, $unicode = true) {
                    $len = (ord($msg[$start+1]) * 256) + ord($msg[$start]);
                    $off = (ord($msg[$start+5]) * 256) + ord($msg[$start+4]);
                    if ($unicode)
                            return str_replace("\0", '', substr($msg, $off, $len));
                    else
                            return substr($msg, $off, $len);
            }
            $user = get_msg_str($msg, 36);
            $domain = get_msg_str($msg, 28);
            $workstation = get_msg_str($msg, 44);
            print "You are $user from $workstation.$domain";
    }
}

And yes, it's not a plain and easy "read the machine name function", because the user is prompted with an dialog, but it's an example, that it is indeed possible (against the other statements here).

Full code can be found here: https://en.code-bude.net/2017/05/07/how-to-read-client-hostname-in-php/

selenium - chromedriver executable needs to be in PATH

You can download ChromeDriver here: https://sites.google.com/a/chromium.org/chromedriver/downloads

Then you have multiple options:

  • add it to your system path
  • put it in the same directory as your python script
  • specify the location directly via executable_path

    driver = webdriver.Chrome(executable_path='C:/path/to/chromedriver.exe')
    

Variable that has the path to the current ansible-playbook that is executing?

Unfortunately there isn't. In fact the absolute path is a bit meaningless (and potentially confusing) in the context of how Ansible runs. In a nutshell, when you invoke a playbook then for each task Ansible physically copies the module associated with the task to a temporary directory on the target machine and then invokes the module with the necessary parameters. So the absolute path on the target machine is just a temporary directory that only contains a few temporary files within it, and it doesn't even include the full playbook. Also, knowing a full path of a file on the Ansible server is pretty much useless on a target machine unless you're replicating your entire Ansible directory tree on the targets.

To see all the variables that are defined by Ansible you can simply run the following command:

$ ansible -m setup hostname

What is the reason you think you need to know the absolute path to the playbook?

IIS7 folder permissions for web application

If it's any help to anyone, give permission to "IIS_IUSRS" group.

Note that if you can't find "IIS_IUSRS", try prepending it with your server's name, like "MySexyServer\IIS_IUSRS".

How to connect to a docker container from outside the host (same network) [Windows]

TLDR: If you have Windows Firewall enabled, make sure that there is an exception for "vpnkit" on private networks.

For my particular case, I discovered that Windows Firewall was blocking my connection when I tried visiting my container's published port from another machine on my local network, because disabling it made everything work.

However, I didn't want to disable the firewall entirely just so I could access my container's service. This begged the question of which "app" was listening on behalf of my container's service. After finding another SO thread that taught me to use netstat -a -b to discover the apps behind the listening sockets on my machine, I learned that it was vpnkit.exe, which already had an entry in my Windows Firewall settings: but "private networks" was disabled on it, and once I enabled it, I was able to visit my container's service from another machine without having to completely disable the firewall.

How to use SearchView in Toolbar Android

If you would like to setup the search facility inside your Fragment, just add these few lines:

Step 1 - Add the search field to you toolbar:

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    app:showAsAction="always|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:title="Search"/>

Step 2 - Add the logic to your onCreateOptionsMenu()

import android.support.v7.widget.SearchView; // not the default !

@Override
public boolean onCreateOptionsMenu( Menu menu) {
    getMenuInflater().inflate( R.menu.main, menu);

    MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
    searchView = (SearchView) myActionMenuItem.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            // Toast like print
            UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
            if( ! searchView.isIconified()) {
                searchView.setIconified(true);
            }
            myActionMenuItem.collapseActionView();
            return false;
        }
        @Override
        public boolean onQueryTextChange(String s) {
            // UserFeedback.show( "SearchOnQueryTextChanged: " + s);
            return false;
        }
    });
    return true;
}

Join String list elements with a delimiter in one step

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

Pythonic way to check if a file exists?

It seems to me that all other answers here (so far) fail to address the race-condition that occurs with their proposed solutions.

Any code where you first check for the files existence, and then, a few lines later in your program, you create it, runs the risk of the file being created while you weren't looking and causing you problems (or you causing the owner of "that other file" problems).

If you want to avoid this sort of thing, I would suggest something like the following (untested):

import os

def open_if_not_exists(filename):
    try:
        fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except OSError, e:
        if e.errno == 17:
            print e
            return None
        else:
            raise
    else:
        return os.fdopen(fd, 'w')

This should open your file for writing if it doesn't exist already, and return a file-object. If it does exists, it will print "Ooops" and return None (untested, and based solely on reading the python documentation, so might not be 100% correct).

Create File If File Does Not Exist

This will enable appending to file using StreamWriter

 using (StreamWriter stream = new StreamWriter("YourFilePath", true)) {...}

This is default mode, not append to file and create a new file.

using (StreamWriter stream = new StreamWriter("YourFilePath", false)){...}
                           or
using (StreamWriter stream = new StreamWriter("YourFilePath")){...}

Anyhow if you want to check if the file exists and then do other things,you can use

using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
            {...}

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

How do I retrieve a textbox value using JQuery?

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

var txt=$('input:text[name=DrugDurationLength]').val();

How to retrieve Jenkins build parameters using the Groovy API?

Get all of the parameters:

System.getenv().each{
  println it
}

Or more sophisticated:

def myvariables = getBinding().getVariables()
for (v in myvariables) {
   echo "${v} " + myvariables.get(v)
}

You will need to disable "Use Groovy Sandbox" for both.

Add a common Legend for combined ggplots

If the legend is the same for both plots, there is a simple solution using grid.arrange(assuming you want your legend to align with both plots either vertically or horizontally). Simply keep the legend for the bottom-most or right-most plot while omitting the legend for the other. Adding a legend to just one plot, however, alters the size of one plot relative to the other. To avoid this use the heights command to manually adjust and keep them the same size. You can even use grid.arrange to make common axis titles. Note that this will require library(grid) in addition to library(gridExtra). For vertical plots:

y_title <- expression(paste(italic("E. coli"), " (CFU/100mL)"))

grid.arrange(arrangeGrob(p1, theme(legend.position="none"), ncol=1), 
   arrangeGrob(p2, theme(legend.position="bottom"), ncol=1), 
   heights=c(1,1.2), left=textGrob(y_title, rot=90, gp=gpar(fontsize=20)))

Here is the result for a similar graph for a project I was working on: enter image description here

Update a table using JOIN in SQL Server?

Aaron's approach above worked perfectly for me. My update statement was slightly different because I needed to join based on two fields concatenated in one table to match a field in another table.

 --update clients table cell field from custom table containing mobile numbers

update clients
set cell = m.Phone
from clients as c
inner join [dbo].[COSStaffMobileNumbers] as m 
on c.Last_Name + c.First_Name = m.Name

How to go back to previous page if back button is pressed in WebView?

The first answer by FoamyGuy is correct but I have some additions; low reputations cannot allow me to do comments. If for some reasons your page fails to load, ensure that you set a flag to take note of the failure and then check it on the onBackPressed override. Otherwise your canGoBack() will be forever executed without heading to the actual back activity if it was there:

//flag with class wide access 
public boolean ploadFailFlag = false;

//your error handling override
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
    onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
    ploadFailFlag = true;       //note this change 
    .....
    .....
}

//finally to the answer to this question:
@Override
public void onBackPressed() {
    if(checkinWebView.canGoBack()){
        //if page load fails, go back for web view will not go back - no page to go to - yet overriding the super 
        if(ploadFailFlag){
            super.onBackPressed();
        }else {
            checkinWebView.goBack();
        }
    }else {
        Toast.makeText(getBaseContext(), "super:", Toast.LENGTH_LONG).show();
        super.onBackPressed();
    }
}

/bin/sh: pushd: not found

pushd is a bash enhancement to the POSIX-specified Bourne Shell. pushd cannot be easily implemented as a command, because the current working directory is a feature of a process that cannot be changed by child processes. (A hypothetical pushd command might do the chdir(2) call and then start a new shell, but ... it wouldn't be very usable.) pushd is a shell builtin, just like cd.

So, either change your script to start with #!/bin/bash or store the current working directory in a variable, do your work, then change back. Depends if you want a shell script that works on very reduced systems (say, a Debian build server) or if you're fine always requiring bash.

Python - How to concatenate to a string in a for loop?

While "".join is more pythonic, and the correct answer for this problem, it is indeed possible to use a for loop.

If this is a homework assignment (please add a tag if this is so!), and you are required to use a for loop then what will work (although is not pythonic, and shouldn't really be done this way if you are a professional programmer writing python) is this:

endstring = ""
mylist = ['first', 'second', 'other']
for word in mylist:
  print "This is the word I am adding: " + word
  endstring = endstring + word
print "This is the answer I get: " + endstring

You don't need the 'prints', I just threw them in there so you can see what is happening.

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

How do I check if file exists in Makefile so I can delete it?

It's strange to see so many people using shell scripting for this. I was looking for a way to use native makefile syntax, because I'm writing this outside of any target. You can use the wildcard function to check if file exists:

 ifeq ($(UNAME),Darwin)
     SHELL := /opt/local/bin/bash
     OS_X  := true
 else ifneq (,$(wildcard /etc/redhat-release))
     OS_RHEL := true
 else
     OS_DEB  := true
     SHELL := /bin/bash
 endif 

Update:

I found a way which is really working for me:

ifneq ("$(wildcard $(PATH_TO_FILE))","")
    FILE_EXISTS = 1
else
    FILE_EXISTS = 0
endif

case in sql stored procedure on SQL Server

Try this

If @NewStatus  = 'InOffice' 
BEGIN
     Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'OutOffice'
BEGIN
    Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'Home'
BEGIN
    Update tblEmployee set Home = -1 where EmpID = @EmpID
END

Invalid URI: The format of the URI could not be determined

Better use Uri.IsWellFormedUriString(string uriString, UriKind uriKind). http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx

Example :-

 if(Uri.IsWellFormedUriString(slct.Text,UriKind.Absolute))
 {
        Uri uri = new Uri(slct.Text);
        if (DeleteFileOnServer(uri))
        {
          nn.BalloonTipText = slct.Text + " has been deleted.";
          nn.ShowBalloonTip(30);
        }
 }

ERROR! MySQL manager or server PID file could not be found! QNAP

Nothing of this worked for me. I tried everything and nothing worked.

I just did :

brew unlink mysql && brew install mariadb

My concern was if I would lost all the data, but luckily everything was there.

Hope it works for somebody else

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

How can I make a checkbox readonly? not disabled?

document.getElementById("your checkbox id").disabled=true;

Send response to all clients except sender

From the @LearnRPG answer but with 1.0:

 // send to current request socket client
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); //still works
 //or
 io.emit('message', 'this is a test');

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');

 // sending to all clients in 'game' room(channel), include sender
 // docs says "simply use to or in when broadcasting or emitting"
 io.in('game').emit('message', 'cool game');

 // sending to individual socketid, socketid is like a room
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');

To answer @Crashalot comment, socketid comes from:

var io = require('socket.io')(server);
io.on('connection', function(socket) { console.log(socket.id); })

How to return data from PHP to a jQuery ajax call

It's an argument passed to your success function:

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function(data) {
    alert(data);
    }
});

The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)

Removing single-quote from a string in php

$replace_str = array('"', "'", ",");
$FileName = str_replace($replace_str, "", $UserInput);

Add border-bottom to table row <tr>

Use border-collapse:collapse on table and border-bottom: 1pt solid black; on the tr

Is it possible to hide the cursor in a webpage using CSS or Javascript?

If you want to do it in CSS:

#ID { cursor: none !important; }

Fast and simple String encrypt/decrypt in JAVA

Update

the library already have Java/Kotlin support, see github.


Original

To simplify I did a class to be used simply, I added it on Encryption library to use it you just do as follow:

Add the gradle library:

compile 'se.simbio.encryption:library:2.0.0'

and use it:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

if you not want add the Encryption library you can just copy the following class to your project. If you are in an android project you need to import android Base64 in this class, if you are in a pure java project you need to add this class manually you can get it here

Encryption.java

package se.simbio.encryption;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * A class to make more easy and simple the encrypt routines, this is the core of Encryption library
 */
public class Encryption {

    /**
     * The Builder used to create the Encryption instance and that contains the information about
     * encryption specifications, this instance need to be private and careful managed
     */
    private final Builder mBuilder;

    /**
     * The private and unique constructor, you should use the Encryption.Builder to build your own
     * instance or get the default proving just the sensible information about encryption
     */
    private Encryption(Builder builder) {
        mBuilder = builder;
    }

    /**
     * @return an default encryption instance or {@code null} if occur some Exception, you can
     * create yur own Encryption instance using the Encryption.Builder
     */
    public static Encryption getDefault(String key, String salt, byte[] iv) {
        try {
            return Builder.getDefaultBuilder(key, salt, iv).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Encrypt a String
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
    }

    /**
     * This is a sugar method that calls encrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     */
    public String encryptOrNull(String data) {
        try {
            return encrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls encrypt method in background, it is a good idea to use this
     * one instead the default method because encryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be encrypted
     * @param callback the Callback to handle the results
     */
    public void encryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String encrypt = encrypt(data);
                    if (encrypt == null) {
                        callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(encrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * Decrypt a String
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
        return new String(dataBytesDecrypted);
    }

    /**
     * This is a sugar method that calls decrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     */
    public String decryptOrNull(String data) {
        try {
            return decrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls decrypt method in background, it is a good idea to use this
     * one instead the default method because decryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be decrypted
     * @param callback the Callback to handle the results
     */
    public void decryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String decrypt = decrypt(data);
                    if (decrypt == null) {
                        callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(decrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * creates a 128bit salted aes key
     *
     * @param key encoded input key
     *
     * @return aes 128 bit salted key
     *
     * @throws NoSuchAlgorithmException     if no installed provider that can provide the requested
     *                                      by the Builder secret key type
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws InvalidKeySpecException      if the specified key specification cannot be used to
     *                                      generate a secret key
     * @throws NullPointerException         if the specified Builder secret key type is {@code null}
     */
    private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
        KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
        SecretKey tmp = factory.generateSecret(spec);
        return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
    }

    /**
     * takes in a simple string and performs an sha1 hash
     * that is 128 bits long...we then base64 encode it
     * and return the char array
     *
     * @param key simple inputted string
     *
     * @return sha1 base64 encoded representation
     *
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws NoSuchAlgorithmException     if the Builder digest algorithm is not available
     * @throws NullPointerException         if the Builder digest algorithm is {@code null}
     */
    private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
        messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
        return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
    }

    /**
     * When you encrypt or decrypt in callback mode you get noticed of result using this interface
     */
    public interface Callback {

        /**
         * Called when encrypt or decrypt job ends and the process was a success
         *
         * @param result the encrypted or decrypted String
         */
        void onSuccess(String result);

        /**
         * Called when encrypt or decrypt job ends and has occurred an error in the process
         *
         * @param exception the Exception related to the error
         */
        void onError(Exception exception);

    }

    /**
     * This class is used to create an Encryption instance, you should provide ALL data or start
     * with the Default Builder provided by the getDefaultBuilder method
     */
    public static class Builder {

        private byte[] mIv;
        private int mKeyLength;
        private int mBase64Mode;
        private int mIterationCount;
        private String mSalt;
        private String mKey;
        private String mAlgorithm;
        private String mKeyAlgorithm;
        private String mCharsetName;
        private String mSecretKeyType;
        private String mDigestAlgorithm;
        private String mSecureRandomAlgorithm;
        private SecureRandom mSecureRandom;
        private IvParameterSpec mIvParameterSpec;

        /**
         * @return an default builder with the follow defaults:
         * the default char set is UTF-8
         * the default base mode is Base64
         * the Secret Key Type is the PBKDF2WithHmacSHA1
         * the default salt is "some_salt" but can be anything
         * the default length of key is 128
         * the default iteration count is 65536
         * the default algorithm is AES in CBC mode and PKCS 5 Padding
         * the default secure random algorithm is SHA1PRNG
         * the default message digest algorithm SHA1
         */
        public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
            return new Builder()
                    .setIv(iv)
                    .setKey(key)
                    .setSalt(salt)
                    .setKeyLength(128)
                    .setKeyAlgorithm("AES")
                    .setCharsetName("UTF8")
                    .setIterationCount(1)
                    .setDigestAlgorithm("SHA1")
                    .setBase64Mode(Base64.DEFAULT)
                    .setAlgorithm("AES/CBC/PKCS5Padding")
                    .setSecureRandomAlgorithm("SHA1PRNG")
                    .setSecretKeyType("PBKDF2WithHmacSHA1");
        }

        /**
         * Build the Encryption with the provided information
         *
         * @return a new Encryption instance with provided information
         *
         * @throws NoSuchAlgorithmException if the specified SecureRandomAlgorithm is not available
         * @throws NullPointerException     if the SecureRandomAlgorithm is {@code null} or if the
         *                                  IV byte array is null
         */
        public Encryption build() throws NoSuchAlgorithmException {
            setSecureRandom(SecureRandom.getInstance(getSecureRandomAlgorithm()));
            setIvParameterSpec(new IvParameterSpec(getIv()));
            return new Encryption(this);
        }

        /**
         * @return the charset name
         */
        private String getCharsetName() {
            return mCharsetName;
        }

        /**
         * @param charsetName the new charset name
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setCharsetName(String charsetName) {
            mCharsetName = charsetName;
            return this;
        }

        /**
         * @return the algorithm
         */
        private String getAlgorithm() {
            return mAlgorithm;
        }

        /**
         * @param algorithm the algorithm to be used
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setAlgorithm(String algorithm) {
            mAlgorithm = algorithm;
            return this;
        }

        /**
         * @return the key algorithm
         */
        private String getKeyAlgorithm() {
            return mKeyAlgorithm;
        }

        /**
         * @param keyAlgorithm the keyAlgorithm to be used in keys
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyAlgorithm(String keyAlgorithm) {
            mKeyAlgorithm = keyAlgorithm;
            return this;
        }

        /**
         * @return the Base 64 mode
         */
        private int getBase64Mode() {
            return mBase64Mode;
        }

        /**
         * @param base64Mode set the base 64 mode
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setBase64Mode(int base64Mode) {
            mBase64Mode = base64Mode;
            return this;
        }

        /**
         * @return the type of aes key that will be created, on KITKAT+ the API has changed, if you
         * are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         */
        private String getSecretKeyType() {
            return mSecretKeyType;
        }

        /**
         * @param secretKeyType the type of AES key that will be created, on KITKAT+ the API has
         *                      changed, if you are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecretKeyType(String secretKeyType) {
            mSecretKeyType = secretKeyType;
            return this;
        }

        /**
         * @return the value used for salting
         */
        private String getSalt() {
            return mSalt;
        }

        /**
         * @param salt the value used for salting
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSalt(String salt) {
            mSalt = salt;
            return this;
        }

        /**
         * @return the key
         */
        private String getKey() {
            return mKey;
        }

        /**
         * @param key the key.
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKey(String key) {
            mKey = key;
            return this;
        }

        /**
         * @return the length of key
         */
        private int getKeyLength() {
            return mKeyLength;
        }

        /**
         * @param keyLength the length of key
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyLength(int keyLength) {
            mKeyLength = keyLength;
            return this;
        }

        /**
         * @return the number of times the password is hashed
         */
        private int getIterationCount() {
            return mIterationCount;
        }

        /**
         * @param iterationCount the number of times the password is hashed
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIterationCount(int iterationCount) {
            mIterationCount = iterationCount;
            return this;
        }

        /**
         * @return the algorithm used to generate the secure random
         */
        private String getSecureRandomAlgorithm() {
            return mSecureRandomAlgorithm;
        }

        /**
         * @param secureRandomAlgorithm the algorithm to generate the secure random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
            mSecureRandomAlgorithm = secureRandomAlgorithm;
            return this;
        }

        /**
         * @return the IvParameterSpec bytes array
         */
        private byte[] getIv() {
            return mIv;
        }

        /**
         * @param iv the byte array to create a new IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIv(byte[] iv) {
            mIv = iv;
            return this;
        }

        /**
         * @return the SecureRandom
         */
        private SecureRandom getSecureRandom() {
            return mSecureRandom;
        }

        /**
         * @param secureRandom the Secure Random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandom(SecureRandom secureRandom) {
            mSecureRandom = secureRandom;
            return this;
        }

        /**
         * @return the IvParameterSpec
         */
        private IvParameterSpec getIvParameterSpec() {
            return mIvParameterSpec;
        }

        /**
         * @param ivParameterSpec the IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
            mIvParameterSpec = ivParameterSpec;
            return this;
        }

        /**
         * @return the message digest algorithm
         */
        private String getDigestAlgorithm() {
            return mDigestAlgorithm;
        }

        /**
         * @param digestAlgorithm the algorithm to be used to get message digest instance
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setDigestAlgorithm(String digestAlgorithm) {
            mDigestAlgorithm = digestAlgorithm;
            return this;
        }

    }

}    

Jmeter - get current date and time

Use __time function:

  • ${__time(dd/MM/yyyy,)}

  • ${__time(hh:mm a,)}

Since JMeter 3.3, there are two new functions that let you compute a time:

__timeShift

  "The timeShift function returns a date in the given format with the specified amount of seconds, minutes, hours, days or months added" and 

__RandomDate

  "The RandomDate function returns a random date that lies between the given start date and end date values." 

Since JMeter 4.0:

dateTimeConvert

Convert a date or time from source to target format

If you're looking to learn jmeter correctly, this book will help you.

Does it matter what extension is used for SQLite database files?

If you have settled on a particular set of tools to access / modify your databases, I would go with whatever extension they expect you to use. This will avoid needless friction when doing development tasks.

For instance, SQLiteStudio v3.1.1 defaults to looking for files with the following extensions:

enter image description here

(db|sdb|sqlite|db3|s3db|sqlite3|sl3|db2|s2db|sqlite2|sl2)

If necessary for deployment your installation mechanism could rename the file if obscuring the file type seems useful to you (as some other answers have suggested). Filename requirements for development and deployment can be different.

Is there a way to detect if a browser window is not currently active?

Here is a solid, modern solution. (Short a sweet )

document.addEventListener("visibilitychange", () => {
  console.log( document.hasFocus() )
})

This will setup a listener to trigger when any visibility event is fired which could be a focus or blur.

IIS Express gives Access Denied error when debugging ASP.NET MVC

I just fixed this exact problem in IIS EXPRESS fixed it by editing the application host .config to the location section specific to the below. I had set Windows Authentication in Visual Studio 2012 but when I went into the XML it looked like this.

the windows auth tag needed to be added below as shown.

<windowsAuthentication enabled="true" />

<location path="MyApplicationbeingDebugged">
        ``<system.webServer>
            <security>
                <authentication>
                    <anonymousAuthentication enabled="false" />
                    <!-- INSERT TAG HERE --> 
                </authentication>
            </security>
        </system.webServer>
</location>

Print current call stack from a method in Python code

If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".

So at the top of your program

import pdb

Then in the code where you want to see what is happening

pdb.set_trace()

and you get dropped into a prompt

How to list all AWS S3 objects in a bucket using Java

Try this one out

public void getObjectList(){
        System.out.println("Listing objects");
        ObjectListing objectListing = s3.listObjects(new ListObjectsRequest()
                .withBucketName(bucketName)
                .withPrefix("ads"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(" - " + objectSummary.getKey() + "  " +
                               "(size = " + objectSummary.getSize() + ")");
        }
    }

You can all the objects within the bucket with specific prefix.

Android refresh current activity

This is a refresh button method, but it works well in my application. in finish() you kill the instances

public void refresh(View view){          //refresh is onClick name given to the button
    onRestart();
}

@Override
protected void onRestart() {

    // TODO Auto-generated method stub
    super.onRestart();
    Intent i = new Intent(lala.this, lala.class);  //your class
    startActivity(i);
    finish();

}

Can't install laravel installer via composer

I am using WSL with ubuntu 16.04 LTS version with php 7.3 and laravel 5.7

sudo apt-get install php7.3-zip

Work for me

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

The usage of org.apache.commons.httpclient.URI is not strictly an issue; what is an issue is that you target the wrong constructor, which is depreciated.

Using just

new URI( [string] );

Will indeed flag it as depreciated. What is needed is to provide at minimum one additional argument (the first, below), and ideally two:

  1. escaped: true if URI character sequence is in escaped form. false otherwise.
  2. charset: the charset string to do escape encoding, if required

This will target a non-depreciated constructor within that class. So an ideal usage would be as such:

new URI( [string], true, StandardCharsets.UTF_8.toString() );

A bit crazy-late in the game (a hair over 11 years later - egad!), but I hope this helps someone else, especially if the method at the far end is still expecting a URI, such as org.apache.commons.httpclient.setURI().

Can you have multiple $(document).ready(function(){ ... }); sections?

You can use multiple. But you can also use multiple functions inside one document.ready as well:

$(document).ready(function() {
    // Jquery
    $('.hide').hide();
    $('.test').each(function() {
       $(this).fadeIn();
    });

    // Reqular JS
    function test(word) {
       alert(word);
    }
    test('hello!');
});

JPA entity without id

If there is a one to one mapping between entity and entity_property you can use entity_id as the identifier.

Mongoose, Select a specific field with find

DB Data

[
  {
    "_id": "70001",
    "name": "peter"
  },
  {
    "_id": "70002",
    "name": "john"
  },
  {
    "_id": "70003",
    "name": "joseph"
  }
]

Query

db.collection.find({},
{
  "_id": 0,
  "name": 1
}).exec((Result)=>{
    console.log(Result);
})

Output:

[
  {
    "name": "peter"
  },
  {
    "name": "john"
  },
  {
    "name": "joseph"
  }
]

Working sample playground

link

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

[UPDATED privacy keys list to iOS 13 - see below]

There is a list of all Cocoa Keys that you can specify in your Info.plist file:

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

(Xcode: Target -> Info -> Custom iOS Target Properties)

iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).

Privacy keys with example description: cheatsheet

Source

Alternatively, you can open Info.plist as source code: source code

Source

And add privacy keys like this:

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>

List of all privacy keys: [UPDATED to iOS 13]

NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription

Update 2019:

In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.

I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo to ${PRODUCT_NAME} need access to the camera to update your avatar even though the app context was obvious (user tapped on the avatar).

It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

All PLEASE note what Tyler said

Note that if you want to edit this file make sure you use a 64 bit text editor like notepad. If you use a 32 bit one like Notepad++ it will automatically edit a different copy of the file in SysWOW64 instead. Hours of my life I won't get back

Send POST data on redirect with JavaScript/jQuery?

var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};

Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/

Going to try this and other suggestions for my work.

Is there any other way to do the same ?

Python display text with font & color?

Yes. It is possible to draw text in pygame:

# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error
myfont = pygame.font.SysFont("monospace", 15)

# render text
label = myfont.render("Some text!", 1, (255,255,0))
screen.blit(label, (100, 100))

Random float number generation

rand() can be used to generate pseudo-random numbers in C++. In combination with RAND_MAX and a little math, you can generate random numbers in any arbitrary interval you choose. This is sufficient for learning purposes and toy programs. If you need truly random numbers with normal distribution, you'll need to employ a more advanced method.


This will generate a number from 0.0 to 1.0, inclusive.

float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);

This will generate a number from 0.0 to some arbitrary float, X:

float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));

This will generate a number from some arbitrary LO to some arbitrary HI:

float r3 = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));

Note that the rand() function will often not be sufficient if you need truly random numbers.


Before calling rand(), you must first "seed" the random number generator by calling srand(). This should be done once during your program's run -- not once every time you call rand(). This is often done like this:

srand (static_cast <unsigned> (time(0)));

In order to call rand or srand you must #include <cstdlib>.

In order to call time, you must #include <ctime>.

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

Getting and removing the first character of a string

substring is definitely best, but here's one strsplit alternative, since I haven't seen one yet.

> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"

or equivalently

> unlist(strsplit(x, ''))[1]
## [1] "h"

And you can paste the rest of the string back together.

> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"

Python coding standards/best practices

PEP 8 is good, the only thing that i wish it came down harder on was the Tabs-vs-Spaces holy war.

Basically if you are starting a project in python, you need to choose Tabs or Spaces and then shoot all offenders on sight.

How to initialize an array in one step using Ruby?

You can simply do this with %w notation in ruby arrays.

array = %w(1 2 3)

It will add the array values 1,2,3 to the arrayand print out the output as ["1", "2", "3"]

What does "atomic" mean in programming?

If you have several threads executing the methods m1 and m2 in the code below:

class SomeClass {
    private int i = 0;

    public void m1() { i = 5; }
    public int m2() { return i; }
}

you have the guarantee that any thread calling m2 will either read 0 or 5.

On the other hand, with this code (where i is a long):

class SomeClass {
    private long i = 0;

    public void m1() { i = 1234567890L; }
    public long m2() { return i; }
}

a thread calling m2 could read 0, 1234567890L, or some other random value because the statement i = 1234567890L is not guaranteed to be atomic for a long (a JVM could write the first 32 bits and the last 32 bits in two operations and a thread might observe i in between).

Which type of folder structure should be used with Angular 2?

I think structuring the project by functionalities is a practical method. It makes the project scalable and maintainable easily. And it makes each part of the project working in a total autonomy. Let me know what you think about this structure below: ANGULAR TYPESCRIPT PROJECT STRUCTURE – ANGULAR 2

source : http://www.angulartypescript.com/angular-typescript-project-structure/

How to enumerate an enum

When you have a bit enum like this

enum DemoFlags
{
    DemoFlag = 1,
    OtherFlag = 2,
    TestFlag = 4,
    LastFlag = 8,
}

With this assignement

DemoFlags demoFlags = DemoFlags.DemoFlag | DemoFlags.TestFlag;

and need a result like this

"DemoFlag | TestFlag"

this method helps:

public static string ConvertToEnumString<T>(T enumToConvert, string separator = " | ") where T : Enum
{
    StringBuilder convertedEnums = new StringBuilder();

    foreach (T enumValue in Enum.GetValues(typeof(T)))
    {
        if (enumToConvert.HasFlag(enumValue)) convertedEnums.Append($"{ enumValue }{separator}");
    }

    if (convertedEnums.Length > 0) convertedEnums.Length -= separator.Length;

    return convertedEnums.ToString();
}

Java - Getting Data from MySQL database

Here you go :

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");

Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) { 
 int id = rs.getInt("first_column_name"); 
 String str1 = rs.getString("second_column_name");
}

con.close();

In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.

UPDATE : rs.next

boolean next() throws SQLException

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.

If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

Returns: true if the new current row is valid; false if there are no more rows Throws: SQLException - if a database access error occurs or this method is called on a closed result set

reference

ORACLE IIF Statement

In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE function.

SET SERVEROUTPUT ON

DECLARE
    x   VARCHAR2(10);
BEGIN
    x := owa_util.ite('a' = 'b','T','F');
    dbms_output.put_line(x);
END;
/

F

PL/SQL procedure successfully completed.

How to copy a file to another path?

TO Copy The Folder I Use Two Text Box To Know The Place Of Folder And Anther Text Box To Know What The Folder To Copy It And This Is The Code

MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
          if (Fromtb.Text=="")
        {
            MessageBox.Show("Ples You Should Write All Text Box");
            Fromtb.Select();
            return;
        }
        else if (Nametb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Third Text Box");
            Nametb.Select();
            return;
        }
        else if (Totb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Second Text Box");
            Totb.Select();
            return;
        }

        string fileName = Nametb.Text;
        string sourcePath = @"" + Fromtb.Text;
        string targetPath = @"" + Totb.Text;


        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
        string destFile = System.IO.Path.Combine(targetPath, fileName);


        if (!System.IO.Directory.Exists(targetPath))
        {
            System.IO.Directory.CreateDirectory(targetPath);
            //when The User Write The New Folder It Will Create 
            MessageBox.Show("The File is Create in "+" "+Totb.Text);
        }


        System.IO.File.Copy(sourceFile, destFile, true);


        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);


            foreach (string s in files)
            {
                fileName = System.IO.Path.GetFileName(s);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile, true);

            }
            MessageBox.Show("The File is copy To " + Totb.Text);

        }

How to use type: "POST" in jsonp ajax call

Use json in dataType and send like this:

    $.ajax({
        url: "your url which return json",
        type: "POST",
        crossDomain: true,
        data: data,
        dataType: "json",
        success:function(result){
            alert(JSON.stringify(result));
        },
        error:function(xhr,status,error){
            alert(status);
        }
    });

and put this lines in your server side file:

if PHP:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');

if java:

response.addHeader( "Access-Control-Allow-Origin", "*" ); 
response.addHeader( "Access-Control-Allow-Methods", "POST" ); 
response.addHeader( "Access-Control-Max-Age", "1000" );

Does Index of Array Exist

The answers here are straightforward but only apply to a 1 dimensional array. For multi-dimensional arrays, checking for null is a straightforward way to tell if the element exists. Example code here checks for null. Note the try/catch block is [probably] overkill but it makes the block bomb-proof.

public ItemContext GetThisElement(int row,
    int col)
{
    ItemContext ctx = null;
    if (rgItemCtx[row, col] != null)
    {
        try
        {
          ctx = rgItemCtx[row, col];
        }
        catch (SystemException sex)
        {
          ctx = null;
          // perhaps do something with sex properties
        }
    }

    return (ctx);
}

Comparing arrays in C#

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

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };
        
Console.WriteLine (a1 == a2);        // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2));  // False (because arrays is reference types)
        
IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer)); 

How can I make a CSS table fit the screen width?

table { width: 100%; }

Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.

$("#tableid").width($(window).width());

If not, use this snippet

<style>
    body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
    <tr>
        <td>Just a Test
        </td>
    </tr>
</table>

You will notice that the width is perfectly covering the page.

The main thing is too nullify the margin and padding as I have shown at the body, then you are set.

How to check if a folder exists

File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;

How to keep the console window open in Visual C++?

The standard way is cin.get() before your return statement.

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World";
    cin.get();
    return 0;
}

Insert default value when parameter is null

The easiest way to do this is to modify the table declaration to be

CREATE TABLE Demo
(
    MyColumn VARCHAR(10) NOT NULL DEFAULT 'Me'
)

Now, in your stored procedure you can do something like.

CREATE PROCEDURE InsertDemo
    @MyColumn VARCHAR(10) = null
AS
INSERT INTO Demo (MyColumn) VALUES(@MyColumn)

However, this method ONLY works if you can't have a null, otherwise, your stored procedure would have to use a different form of insert to trigger a default.

async/await - when to return a Task vs void?

My answer is simple you can not await void method

Error   CS4008  Cannot await 'void' TestAsync   e:\test\TestAsync\TestAsyncProgram.cs

So if the method is async it is better to be awaitable, because you can loose async advantage.

What is the difference between map and flatMap and a good use case for each?

It boils down to your initial question: what you mean by flattening ?

When you use flatMap, a "multi-dimensional" collection becomes "one-dimensional" collection.

val array1d = Array ("1,2,3", "4,5,6", "7,8,9")  
//array1d is an array of strings

val array2d = array1d.map(x => x.split(","))
//array2d will be : Array( Array(1,2,3), Array(4,5,6), Array(7,8,9) )

val flatArray = array1d.flatMap(x => x.split(","))
//flatArray will be : Array (1,2,3,4,5,6,7,8,9)

You want to use a flatMap when,

  • your map function results in creating multi layered structures
  • but all you want is a simple - flat - one dimensional structure, by removing ALL the internal groupings

Calling another method java GUI

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

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

Difference between static memory allocation and dynamic memory allocation

Static memory allocation is allocated memory before execution pf program during compile time. Dynamic memory alocation is alocated memory during execution of program at run time.

Get index of array element faster than O(n)

Why not use index or rindex?

array = %w( a b c d e)
# get FIRST index of element searched
puts array.index('a')
# get LAST index of element searched
puts array.rindex('a')

index: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index

rindex: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-rindex

PHP - Merging two arrays into one array (also Remove Duplicates)

It will merger two array and remove duplicate

<?php
 $first = 'your first array';
 $second = 'your second array';
 $result = array_merge($first,$second);
 print_r($result);
 $result1= array_unique($result);
 print_r($result1);
 ?>

Try this link link1

Attribute Error: 'list' object has no attribute 'split'

The problem is that readlines is a list of strings, each of which is a line of filename. Perhaps you meant:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]
    print(x,y)

Set HTML dropdown selected option using JSTL

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>

Get generic type of class at runtime

If you have a class like:

public class GenericClass<T> {
    private T data;
}

with T variable, then you can print T name:

System.out.println(data.getClass().getSimpleName()); // "String", "Integer", etc.

Export javascript data to CSV file without server interaction

See adeneo's answer, but to make this work in Excel in all countries you should add "SEP=," to the first line of the file. This will set the standard separator in Excel and will not show up in the actual document

var csvString = "SEP=, \n" + csvRows.join("\r\n");

Scroll Element into View with Selenium

You can use the org.openqa.selenium.interactions.Actions class to move to an element.

Java:

WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

Python:

from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()

Postman: sending nested JSON object

Select the body tab and select application/json in the Content-Type drop-down and add a body like this:

{
  "Username":"ABC",
  "Password":"ABC"
}

enter image description here

nginx: send all requests to a single html page

Using just try_files didn't work for me - it caused a rewrite or internal redirection cycle error in my logs.

The Nginx docs had some additional details:

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

So I ended up using the following:

root /var/www/mysite;

location / {
    try_files $uri /base.html;
}

location = /base.html {
    expires 30s;
}

Git SSH error: "Connect to host: Bad file number"

The key information is written in @Sam's answer but not really salient, so let's make it clear.

"Bad file number" is not informative, it's only a sign of running git's ssh on Windows.

The line which appears even without -v switch:

ssh: connect to host (some host or IP address) port 22: Bad file number

is actually irrelevant.

If you focus on it you'll waste your time as it is not a hint about what the actual problem is, just an effect of running git's ssh on Windows. It's not even a sign that the git or ssh install or configuration is wrong. Really, ignore it.

The very same command on Linux produced instead this message for me, which gave an actual hint about the problem:

ssh: connect to host (some host or IP address) port 22: Connection timed out

Actual solution: ignore "bad file number" and get more information

Focus on lines being added with -v on command line. In my case it was:

debug1: connect to address (some host or IP address) port 22: Attempt to connect timed out without establishing a connection

My problem was a typo in the IP address, but yours may be different.

Is this question about "bad file number", or about the many reasons why a connection could time out ?

If someone can prove that "bad file number" only appears when the actual reason is "connection time out" then it makes some sense to address why connection could time out.

Until that, "bad file number" is only a generic error message and this question is fully answered by saying "ignore it and look for other error messages".

EDIT: Qwertie mentioned that the error message is indeed generic, as it can happen on "Connection refused" also. This confirms the analysis.

Please don't clutter this question with general hints and answer, they have nothing to do with the actual topic (and title) of this question which is "Git SSH error: “Connect to host: Bad file number”". If using -v you have more informative message that deserve their own question, then open another question, then you can make a link to it.

Copy data from another Workbook through VBA

There's very little reason not to open multiple workbooks in Excel. Key lines of code are:

Application.EnableEvents = False
Application.ScreenUpdating = False

...then you won't see anything whilst the code runs, and no code will run that is associated with the opening of the second workbook. Then there are...

Application.DisplayAlerts = False
Application.Calculation = xlManual

...so as to stop you getting pop-up messages associated with the content of the second file, and to avoid any slow re-calculations. Ensure you set back to True/xlAutomatic at end of your programming

If opening the second workbook is not going to cause performance issues, you may as well do it. In fact, having the second workbook open will make it very beneficial when attempting to debug your code if some of the secondary files do not conform to the expected format

Here is some expert guidance on using multiple Excel files that gives an overview of the different methods available for referencing data

An extension question would be how to cycle through multiple files contained in the same folder. You can use the Windows folder picker using:

With Application.FileDialog(msoFileDialogFolderPicker)
.Show
     If .Selected.Items.Count = 1 the InputFolder = .SelectedItems(1)
End With

FName = VBA.Dir(InputFolder)

Do While FName <> ""
'''Do function here
FName = VBA.Dir()
Loop

Hopefully some of the above will be of use

Jquery Ajax Posting json to webservice

I tried Dave Ward's solution. The data part was not being sent from the browser in the payload part of the post request as the contentType is set to "application/json". Once I removed this line everything worked great.

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },

               { "position": "235.1944023323615", "markerPosition": "19" },

               { "position": "42.5978231292517", "markerPosition": "-3" }];

$.ajax({

    type: "POST",
    url: "/webservices/PodcastService.asmx/CreateMarkers",
    // The key needs to match your method's input parameter (case-sensitive).
    data: JSON.stringify({ Markers: markers }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    failure: function(errMsg) {
        alert(errMsg);
    }
});

How to truncate string using SQL server

You could also use the below, the iif avoids the case statement and only adds ellipses when required (only good in SQL Server 2012 and later) and the case statement is more ANSI compliant (but more verbose)

SELECT 
  col, LEN(col), 
  col2, LEN(col2), 
  col3, LEN(col3) FROM (
  SELECT 
    col, 
    LEFT(x.col, 15) + (IIF(len(x.col) > 15, '...', '')) AS col2, 
    LEFT(x.col, 15) + (CASE WHEN len(x.col) > 15 THEN '...' ELSE '' END) AS col3 
  from (
      select 'this is a long string. One that is longer than 15 characters' as col
      UNION 
      SELECT 'short string' AS col
      UNION 
      SELECT 'string==15 char' AS col
      UNION 
      SELECT NULL AS col
      UNION 
      SELECT '' AS col
) x
) y

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Put novalidate="novalidate" on <form> tag.

<form novalidate="novalidate">
...
</form>

In XHTML, attribute minimization is forbidden, and the novalidate attribute must be defined as <form novalidate="novalidate">.

http://www.w3schools.com/tags/att_form_novalidate.asp

How to get exit code when using Python subprocess communicate method?

You should first make sure that the process has completed running and the return code has been read out using the .wait method. This will return the code. If you want access to it later, it's stored as .returncode in the Popen object.

How to force IE10 to render page in IE9 document mode

Do you mean you want to tell your copy of IE 10 to render the pages it views in IE 9 mode?

Or do you mean you want your website to force IE 10 to render it in IE 9 mode?

For the former:

To force a webpage you are viewing in Internet Explorer 10 into a particular document compatibility mode, first open F12 Tools by pressing the F12 key. Then, on the Browser Mode menu, click Internet Explorer 10, and on the Document Mode menu, click Standards.

http://msdn.microsoft.com/en-gb/library/ie/hh920756(v=vs.85).aspx

For the latter, the other answers are correct, but I wouldn't advise doing that. IE 10 is more standards-compliant (i.e. more similar to other browsers) than IE 9.

Update rows in one table with data from another table based on one column in each being equal

merge into t2 t2 
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
   t2.c1 = t1.c1
,  t2.c2 = t1.c2

Find out free space on tablespace

column pct_free format 999.99
select
     used.tablespace_name,
     (reserv.maxbytes - used.bytes)*100/reserv.maxbytes pct_free,
     used.bytes/1024/1024/1024 used_gb,
     reserv.maxbytes/1024/1024/1024 maxgb,
     reserv.bytes/1024/1024/1024 gb,
     (reserv.maxbytes - used.bytes)/1024/1024/1024 "max free bytes",
     reserv.datafiles
from
    (select tablespace_name, count(1) datafiles, sum(greatest(maxbytes,bytes)) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
    (select tablespace_name, sum(bytes) bytes from dba_segments group by tablespace_name) used
where used.tablespace_name = reserv.tablespace_name
order by 2
/

How to create timer in angular2

If you look to run a method on ngOnInit you could do something like this:

import this 2 libraries from RXJS:

import {Observable} from 'rxjs/Rx';
import {Subscription} from "rxjs";

Then declare timer and private subscription, example:

timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc
private subscription: Subscription;

Last but not least run method when timer stops

ngOnInit() {
  this.subscription = this.timer.subscribe(ticks=> {
    this.populatecombobox();  //example calling a method that populates a combobox
    this.subscription.unsubscribe();  //you need to unsubscribe or it will run infinite times
  });
}

That's all, Angular 5

Microsoft.Office.Core Reference Missing

After installing the Office PIA (primary interop assemblies), add a reference to your project -> its on the .NET tab - component name "Office"

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

Why javascript when you can use just css?

_x000D_
_x000D_
a[aria-expanded="true"]{_x000D_
  background-color: #42DCA3;_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_

How do you reinstall an app's dependencies using npm?

You can do this with one simple command:

npm ci

Documentation:

npm ci
Install a project with a clean slate

ValueError: all the input arrays must have same number of dimensions

You can also cast (n,) to (n,1) by enclosing within brackets [ ].

e.g. Instead of np.append(b,a,axis=0) use np.append(b,[a],axis=0)

a=[1,2]
b=[[5,6],[7,8]]
np.append(b,[a],axis=0)

returns

array([[5, 6],
       [7, 8],
       [1, 2]])

Is there any way to prevent input type="number" getting negative values?

I was not satisfied with @Abhrabm answer because:

It was only preventing negative numbers from being entered from up/down arrows, whereas user can type negative number from keyboard.

Solution is to prevent with key code:

_x000D_
_x000D_
// Select your input element._x000D_
var number = document.getElementById('number');_x000D_
_x000D_
// Listen for input event on numInput._x000D_
number.onkeydown = function(e) {_x000D_
    if(!((e.keyCode > 95 && e.keyCode < 106)_x000D_
      || (e.keyCode > 47 && e.keyCode < 58) _x000D_
      || e.keyCode == 8)) {_x000D_
        return false;_x000D_
    }_x000D_
}
_x000D_
<form action="" method="post">_x000D_
  <input type="number" id="number" min="0" />_x000D_
  <input type="submit" value="Click me!"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Clarification provided by @Hugh Guiney:

What key codes are being checked:

  • 95, < 106 corresponds to Numpad 0 through 9;
  • 47, < 58 corresponds to 0 through 9 on the Number Row; and 8 is Backspace.

So this script is preventing invalid key from being entered in input.

Close dialog on click (anywhere)

When creating a JQuery Dialog window, JQuery inserts a ui-widget-overlay class. If you bind a click function to that class to close the dialog, it should provide the functionality you are looking for.

Code will be something like this (untested):

$('.ui-widget-overlay').click(function() { $("#dialog").dialog("close"); });

Edit: The following has been tested for Kendo as well:

$('.k-overlay').click(function () {
            var popup = $("#dialogId").data("kendoWindow");
            if (popup)
                popup.close();
        });

How do I consume the JSON POST data in an Express application

A beginner's mistake...i was using app.use(express.json()); in a local module instead of the main file (entry point).

Select element based on multiple classes

You can use these solutions :

CSS rules applies to all tags that have following two classes :

.left.ui-class-selector {
    /*style here*/
}

CSS rules applies to all tags that have <li> with following two classes :

li.left.ui-class-selector {
   /*style here*/
}

jQuery solution :

$("li.left.ui-class-selector").css("color", "red");

Javascript solution :

document.querySelector("li.left.ui-class-selector").style.color = "red";

how to install multiple versions of IE on the same system?

I would use VMs. Create an XP (or whatever) VM using VMware Workstation or similar product, and snapshot it. That is your oldest version. Then perform the upgrades one at a time, and snapshot each time. Then you can switch to any snapshot you need later, or clone independent VMs based on all the snapshots so you can run them all at once. You probably want to test on different operating systems as well as different versions, so VMs generalize that solution as well rather than some one-off solution of hacking multiple IEs to coexist on a single instance of Windows.

How to use "like" and "not like" in SQL MSAccess for the same field?

Try this:

filed like "*AA*" and filed not like "*BB*"

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {
    display:table-cell;
    vertical-align:middle;
    float:none;
}

http://bootply.com/94394


Option 2 is display:flex to vertical align the row with flexbox:

.row.center {
   display: flex;
   align-items: center;
}

http://www.bootply.com/7rAuLpMCwr


Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456

What is the syntax to insert one list into another list in python?

Do you mean append?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]

Or merge?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6] 

Rotation of 3D vector?

I just wanted to mention that if speed is required, wrapping unutbu's code in scipy's weave.inline and passing an already existing matrix as a parameter yields a 20-fold decrease in the running time.

The code (in rotation_matrix_test.py):

import numpy as np
import timeit

from math import cos, sin, sqrt
import numpy.random as nr

from scipy import weave

def rotation_matrix_weave(axis, theta, mat = None):
    if mat == None:
        mat = np.eye(3,3)

    support = "#include <math.h>"
    code = """
        double x = sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]);
        double a = cos(theta / 2.0);
        double b = -(axis[0] / x) * sin(theta / 2.0);
        double c = -(axis[1] / x) * sin(theta / 2.0);
        double d = -(axis[2] / x) * sin(theta / 2.0);

        mat[0] = a*a + b*b - c*c - d*d;
        mat[1] = 2 * (b*c - a*d);
        mat[2] = 2 * (b*d + a*c);

        mat[3*1 + 0] = 2*(b*c+a*d);
        mat[3*1 + 1] = a*a+c*c-b*b-d*d;
        mat[3*1 + 2] = 2*(c*d-a*b);

        mat[3*2 + 0] = 2*(b*d-a*c);
        mat[3*2 + 1] = 2*(c*d+a*b);
        mat[3*2 + 2] = a*a+d*d-b*b-c*c;
    """

    weave.inline(code, ['axis', 'theta', 'mat'], support_code = support, libraries = ['m'])

    return mat

def rotation_matrix_numpy(axis, theta):
    mat = np.eye(3,3)
    axis = axis/sqrt(np.dot(axis, axis))
    a = cos(theta/2.)
    b, c, d = -axis*sin(theta/2.)

    return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],
                  [2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],
                  [2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]])

The timing:

>>> import timeit
>>> 
>>> setup = """
... import numpy as np
... import numpy.random as nr
... 
... from rotation_matrix_test import rotation_matrix_weave
... from rotation_matrix_test import rotation_matrix_numpy
... 
... mat1 = np.eye(3,3)
... theta = nr.random()
... axis = nr.random(3)
... """
>>> 
>>> timeit.repeat("rotation_matrix_weave(axis, theta, mat1)", setup=setup, number=100000)
[0.36641597747802734, 0.34883809089660645, 0.3459300994873047]
>>> timeit.repeat("rotation_matrix_numpy(axis, theta)", setup=setup, number=100000)
[7.180983066558838, 7.172032117843628, 7.180462837219238]

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

Delete all local git branches

I wrote a shell script in order to remove all local branches except develop

branches=$(git branch | tr -d " *")
output=""
for branch in $branches 
do
  if [[ $branch != "develop" ]]; then
    output="$output $branch"
  fi
done
git branch -d $output

python dictionary sorting in descending order based on values

You can use dictRysan library. I think that will solve your task.

import dictRysan as ry

d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }

changed_d=ry.nested_2L_value_sort(d,"key3",True)
print(changed_d)

Differences between Ant and Maven

In Maven: The Definitive Guide, I wrote about the differences between Maven and Ant in the introduction the section title is "The Differences Between Ant and Maven". Here's an answer that is a combination of the info in that introduction with some additional notes.

A Simple Comparison

I'm only showing you this to illustrate the idea that, at the most basic level, Maven has built-in conventions. Here's a simple Ant build file:

<project name="my-project" default="dist" basedir=".">
    <description>
        simple example build file
    </description>   
    <!-- set global properties for this build -->   
    <property name="src" location="src/main/java"/>
    <property name="build" location="target/classes"/>
    <property name="dist"  location="target"/>

    <target name="init">
      <!-- Create the time stamp -->
      <tstamp/>
      <!-- Create the build directory structure used by compile -->
      <mkdir dir="${build}"/>   
    </target>

    <target name="compile" depends="init"
        description="compile the source " >
      <!-- Compile the java code from ${src} into ${build} -->
      <javac srcdir="${src}" destdir="${build}"/>  
    </target>

    <target name="dist" depends="compile"
        description="generate the distribution" >
      <!-- Create the distribution directory -->
      <mkdir dir="${dist}/lib"/>

      <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file
-->
      <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
   </target>

   <target name="clean"
        description="clean up" >
     <!-- Delete the ${build} and ${dist} directory trees -->
     <delete dir="${build}"/>
     <delete dir="${dist}"/>
   </target>
 </project>

In this simple Ant example, you can see how you have to tell Ant exactly what to do. There is a compile goal which includes the javac task that compiles the source in the src/main/java directory to the target/classes directory. You have to tell Ant exactly where your source is, where you want the resulting bytecode to be stored, and how to package this all into a JAR file. While there are some recent developments that help make Ant less procedural, a developer's experience with Ant is in coding a procedural language written in XML.

Contrast the previous Ant example with a Maven example. In Maven, to create a JAR file from some Java source, all you need to do is create a simple pom.xml, place your source code in ${basedir}/src/main/java and then run mvn install from the command line. The example Maven pom.xml that achieves the same results.

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.sonatype.mavenbook</groupId>
  <artifactId>my-project</artifactId>
  <version>1.0</version>
</project>

That's all you need in your pom.xml. Running mvn install from the command line will process resources, compile source, execute unit tests, create a JAR, and install the JAR in a local repository for reuse in other projects. Without modification, you can run mvn site and then find an index.html file in target/site that contains links to JavaDoc and a few reports about your source code.

Admittedly, this is the simplest possible example project. A project which only contains source code and which produces a JAR. A project which follows Maven conventions and doesn't require any dependencies or customization. If we wanted to start customizing the behavior, our pom.xml is going to grow in size, and in the largest of projects you can see collections of very complex Maven POMs which contain a great deal of plugin customization and dependency declarations. But, even when your project's POM files become more substantial, they hold an entirely different kind of information from the build file of a similarly sized project using Ant. Maven POMs contain declarations: "This is a JAR project", and "The source code is in src/main/java". Ant build files contain explicit instructions: "This is project", "The source is in src/main/java", "Run javac against this directory", "Put the results in target/classses", "Create a JAR from the ....", etc. Where Ant had to be explicit about the process, there was something "built-in" to Maven that just knew where the source code was and how it should be processed.

High-level Comparison

The differences between Ant and Maven in this example? Ant...

  • doesn't have formal conventions like a common project directory structure, you have to tell Ant exactly where to find the source and where to put the output. Informal conventions have emerged over time, but they haven't been codified into the product.
  • is procedural, you have to tell Ant exactly what to do and when to do it. You had to tell it to compile, then copy, then compress.
  • doesn't have a lifecycle, you had to define goals and goal dependencies. You had to attach a sequence of tasks to each goal manually.

Where Maven...

  • has conventions, it already knew where your source code was because you followed the convention. It put the bytecode in target/classes, and it produced a JAR file in target.
  • is declarative. All you had to do was create a pom.xml file and put your source in the default directory. Maven took care of the rest.
  • has a lifecycle, which you invoked when you executed mvn install. This command told Maven to execute a series of sequence steps until it reached the lifecycle. As a side-effect of this journey through the lifecycle, Maven executed a number of default plugin goals which did things like compile and create a JAR.

What About Ivy?

Right, so someone like Steve Loughran is going to read that comparison and call foul. He's going to talk about how the answer completely ignores something called Ivy and the fact that Ant can reuse build logic in the more recent releases of Ant. This is true. If you have a bunch of smart people using Ant + antlibs + Ivy, you'll end up with a well designed build that works. Even though, I'm very much convinced that Maven makes sense, I'd happily use Ant + Ivy with a project team that had a very sharp build engineer. That being said, I do think you'll end up missing out on a number of valuable plugins such as the Jetty plugin and that you'll end up doing a whole bunch of work that you didn't need to do over time.

More Important than Maven vs. Ant

  1. Is that you use a Repository Manager to keep track of software artifacts. I'd suggest downloading Nexus. You can use Nexus to proxy remote repositories and to provide a place for your team to deploy internal artifacts.
  2. You have appropriate modularization of software components. One big monolithic component rarely scales over time. As your project develops, you'll want to have the concept of modules and sub-modules. Maven lends itself to this approach very well.
  3. You adopt some conventions for your build. Even if you use Ant, you should strive to adopt some form of convention that is consistent with other projects. When a project uses Maven, it means that anyone familiar with Maven can pick up the build and start running with it without having to fiddle with configuration just to figure out how to get the thing to compile.

Check Postgres access for a user

Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.

SELECT grantee,table_catalog, table_schema, table_name, privilege_type
FROM   information_schema.table_privileges 
WHERE  grantee not in ('pg_monitor','PUBLIC');

How to install easy_install in Python 2.7.1 on Windows 7

I usually just run ez_setup.py. IIRC, that works fine, at least with UAC off.

It also creates an easy_install executable in your Python\scripts subdirectory, which should be in your PATH.

UPDATE: I highly recommend not to bother with easy_install anymore! Jump right to pip, it's better in every regard!
Installation is just as simple: from the installation instructions page, you can download get-pip.py and run it. Works just like the ez_setup.py mentioned above.

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

How to install xgboost in Anaconda Python (Windows platform)?

GUYS ITS NOT THAT EASY:- PLEASE FOLLOW BELOW STEP TO GET TO MARK

So here's what I did to finish a 64-bit build on Windows:

Download and install MinGW-64: sourceforge.net /projects/mingw-w64/

On the first screen of the install prompt make sure you set the Architecture to x86_64 and the Threads to win32 I installed to C:\mingw64 (to avoid spaces in the file path) so I added this to my PATH environment variable: C:\ mingw64 \ mingw64 \ bin(Please remove spaces)

I also noticed that the make utility that is included in bin\mingw64 is called mingw32-make so to simplify things I just renamed this to make

Open a Windows command prompt and type gcc. You should see something like "fatal error: no input file"

Next type make. You should see something like "No targets specified and no makefile found"

Type git. If you don't have git, install it and add it to your PATH. These should be all the tools you need to build the xgboost project. To get the source code run these lines:

  • cd c:\
  • git clone --recursive https://github.com/dmlc/xgboost
  • cd xgboost
  • git submodule init
  • git submodule update
  • cp make/mingw64.mk config.mk
  • make -j4 Note that I ran this part from a Cygwin shell. If you are using the Windows command prompt you should be able to change cp to copy and arrive at the same result. However, if the build fails on you for any reason I would recommend trying again using cygwin.

If the build finishes successfully, you should have a file called xgboost.exe located in the project root. To install the Python package, do the following:

  • cd python-package
  • python setup.py install Now you should be good to go. Open up Python, and you can import the package with:

  • import xgboost as xgb To test the installation, I went ahead and ran the basic_walkthrough.py file that was included in the demo/guide-python folder of the project and didn't get any errors.

Clear History and Reload Page on Login/Logout Using Ionic Framework

Reload the page isn't the best approach.

you can handle state change events for reload data without reload the view itself.

read about ionicView life-cycle here:

http://blog.ionic.io/navigating-the-changes/

and handle the event beforeEnter for data reload.

$scope.$on('$ionicView.beforeEnter', function(){
  // Any thing you can think of
});

indexOf and lastIndexOf in PHP?

This is the best way to do it, very simple.

$msg = "Hello this is a string";
$first_index_of_i = stripos($msg,'i');
$last_index_of_i = strripos($msg, 'i');

echo "First i : " . $first_index_of_i . PHP_EOL ."Last i : " . $last_index_of_i;

Fastest way to copy a file in Node.js

I was not able to get the createReadStream/createWriteStream method working for some reason, but using the fs-extra npm module it worked right away. I am not sure of the performance difference though.

npm install --save fs-extra

var fs = require('fs-extra');

fs.copySync(path.resolve(__dirname, './init/xxx.json'), 'xxx.json');

Removing element from array in component state

As mentioned in a comment to ephrion's answer above, filter() can be slow, especially with large arrays, as it loops to look for an index that appears to have been determined already. This is a clean, but inefficient solution.

As an alternative one can simply 'slice' out the desired element and concatenate the fragments.

var dummyArray = [];    
this.setState({data: dummyArray.concat(this.state.data.slice(0, index), this.state.data.slice(index))})

Hope this helps!

Java double comparison epsilon

Floating point numbers only have so many significant digits, but they can go much higher. If your app will ever handle large numbers, you will notice the epsilon value should be different.

0.001+0.001 = 0.002 BUT 12,345,678,900,000,000,000,000+1=12,345,678,900,000,000,000,000 if you are using floating point and double. It's not a good representation of money, unless you are damn sure you'll never handle more than a million dollars in this system.

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

How to get Wikipedia content using Wikipedia's API?

If you need to do this for a large number of articles, then instead of querying the website directly, consider downloading a Wikipedia database dump and then accessing it through an API such as JWPL.

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Using 'make' on OS X

There is now another way to install the gcc toolchain on OS X through the osx-gcc-installer this includes:

  • GCC
  • LLVM
  • Clang
  • Developer CLI Tools (purge, make, etc)
  • DevSDK (headers, etc)

The download is 282MB vs 3GB for Xcode.

Font-awesome, input type 'submit'

You can use font awesome utf cheatsheet

<input type="submit" class="btn btn-success" value="&#xf011; Login"/>

here is the link for the cheatsheet http://fortawesome.github.io/Font-Awesome/cheatsheet/

How can a Javascript object refer to values in itself?

One alternative would be to use a getter/setter methods.

For instance, if you only care about reading the calculated value:

var book  = {}

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true },
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + " works!";
        }
    }
});

console.log(book.key2); //prints "it works!"

The above code, though, won't let you define another value for key2.

So, the things become a bit more complicated if you would like to also redefine the value of key2. It will always be a calculated value. Most likely that's what you want.

However, if you would like to be able to redefine the value of key2, then you will need a place to cache its value independently of the calculation.

Somewhat like this:

var book  = { _key2: " works!" }

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true},
    _key2: { enumerable: false},
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + this._key2;
        },
        set: function(newValue){
            this._key2 = newValue;
        }
    }
});

console.log(book.key2); //it works!

book.key2 = " doesn't work!";
console.log(book.key2); //it doesn't work!

for(var key in book){
    //prints both key1 and key2, but not _key2
    console.log(key + ":" + book[key]); 
}

Another interesting alternative is to use a self-initializing object:

var obj = ({
  x: "it",
  init: function(){
    this.y = this.x + " works!";
    return this;
  }
}).init();

console.log(obj.y); //it works!

Execution failed for task ':app:processDebugResources' even with latest build tools

Error:Execution failed for task com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:

finished with non-zero exit value 1

One reason for this error to occure is that the file path to a resource file is to long:

Error: File path too long on Windows, keep below 240 characters 

Fix: Move your project folder closer to the root of your disk

Don't:// folder/folder/folder/folder/very_long_folder_name/MyProject...

Do://folder/short_name/MyProject


Another reason could be duplicated resources or name spaces

Example:

  <style name="MyButton" parent="android:Widget.Button">
      <item name="android:textColor">@color/accent_color</item>
      <item name="android:textColor">#000000</item>
  </style>

And make sure all file names and extensions are in lowercase

Wrong

myimage.PNG
myImage.png

Correct

my_image.png

Make sure to Clean/Rebuild project

(delete the 'build' folder)

I want to vertical-align text in select box

The nearest general solution i know uses box-align property, as described here. Working example is here (i can test it only on Chrome, believe that has equivalent for other browsers too).

CSS:

select{
  display:-webkit-box;
  display:-moz-box;
  display:box;
  height: 30px;;
}
select:nth-child(1){
  -webkit-box-align:start;
  -moz-box-align:start;
  box-align:start;
}
select:nth-child(2){
  -webkit-box-align:center;
  -moz-box-align:center;
  box-align:center;
}
select:nth-child(3){
  -webkit-box-align:end;
  -moz-box-align:end;
  box-align:end;
}

JavaScript: undefined !== undefined?

var a;

typeof a === 'undefined'; // true
a === undefined; // true
typeof a === typeof undefined; // true
typeof a === typeof sdfuwehflj; // true

Dynamically add event listener

Renderer has been deprecated in Angular 4.0.0-rc.1, read the update below

The angular2 way is to use listen or listenGlobal from Renderer

For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement)

constructor(elementRef: ElementRef, renderer: Renderer) {

    // Listen to click events in the component
    renderer.listen(elementRef.nativeElement, 'click', (event) => {
      // Do something with 'event'
    })
);

You can use listenGlobal that will give you access to document, body, etc.

renderer.listenGlobal('document', 'click', (event) => {
  // Do something with 'event'
});

Note that since beta.2 both listen and listenGlobal return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).

So to remove the listener we added dynamically we must assign listen or listenGlobal to a variable that will hold the function returned, and then we execute it.

// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;

// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;

constructor(elementRef: ElementRef, renderer: Renderer) {
    
    // We cache the function "listen" returns
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        // Do something with 'event'
    });

    // We cache the function "listenGlobal" returns
    this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
        // Do something with 'event'
    });
}

ngOnDestroy() {
    // We execute both functions to remove the respectives listeners

    // Removes "listen" listener
    this.listenFunc();
    
    // Removs "listenGlobal" listener
    this.globalListenFunc();
}

Here's a plnkr with an example working. The example contains the usage of listen and listenGlobal.

Using RendererV2 with Angular 4.0.0-rc.1+ (Renderer2 since 4.0.0-rc.3)

  • 25/02/2017: Renderer has been deprecated, now we should use RendererV2 (see line below). See the commit.

  • 10/03/2017: RendererV2 was renamed to Renderer2. See the breaking changes.

RendererV2 has no more listenGlobal function for global events (document, body, window). It only has a listen function which achieves both functionalities.

For reference, I'm copy & pasting the source code of the DOM Renderer implementation since it may change (yes, it's angular!).

listen(target: 'window'|'document'|'body'|any, event: string, callback: (event: any) => boolean):
      () => void {
    if (typeof target === 'string') {
      return <() => void>this.eventManager.addGlobalEventListener(
          target, event, decoratePreventDefault(callback));
    }
    return <() => void>this.eventManager.addEventListener(
               target, event, decoratePreventDefault(callback)) as() => void;
  }

As you can see, now it verifies if we're passing a string (document, body or window), in which case it will use an internal addGlobalEventListener function. In any other case, when we pass an element (nativeElement) it will use a simple addEventListener

To remove the listener it's the same as it was with Renderer in angular 2.x. listen returns a function, then call that function.

Example

// Add listeners
let global = this.renderer.listen('document', 'click', (evt) => {
  console.log('Clicking the document', evt);
})

let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
  console.log('Clicking the button', evt);
});

// Remove listeners
global();
simple();

plnkr with Angular 4.0.0-rc.1 using RendererV2

plnkr with Angular 4.0.0-rc.3 using Renderer2

How should I edit an Entity Framework connection string?

You normally define your connection strings in Web.config. After generating the edmx the connection string will get stored in the App.Config. If you want to change the connection string go to the app.config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.

In the output window it will show something like this,

Generated model file: UpostDataModel.edmx. Loading metadata from the database took 00:00:00.4258157. Generating the model took 00:00:01.5623765. Added the connection string to the App.Config file.

Markdown: continue numbered list

If you don't want the lines in between the list items to be indented, like user Mars mentioned in his comment, you can use pandoc's example_lists feature. From their docs:

(@)  My first example will be numbered (1).
(@)  My second example will be numbered (2).

Explanation of examples.

(@)  My third example will be numbered (3).

How to vertically align text with icon font?

There are already a few answers here but I found flexbox to be the cleanest and least "hacky" solution:

parent-element {
  display: flex;
  align-items: center;
}

To support Safari < 8, Firefox < 21 and Internet Explorer < 10 (Use this polyfill to support IE8+9) you'll need vendor prefixes:

parent-element {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

What is a practical, real world example of the Linked List?

What is a practical, real world example of the Linked List?

The simplest and most straightforward is a train.

Train cars are linked in a specific order so that they may be loaded, unloaded, transferred, dropped off, and picked up in the most efficient manner possible.

For instance, the Jiffy Mix plant needs sugar, flour, cornmeal, etc. Just around the bend might be a paper processing plant that needs chlorine, sulfuric acid, and hydrogen.

Now, we can stop the train, unload each car of its contents, then let the train go on, but then everything else on the train has to sit while flour is sucked out of the caisson, then the sugar, etc.

Instead, the cars are loaded on the train in order so that a whole chunk of it can be detached, and the remainder of the train moves on.

The end of the train is easier to detach than a portion in the middle, and vastly easier than detaching a few cars in one spot, and a few cars in another spot.

If needed, however, you can insert and remove items at any point in the train.

Much like a linked list.

-Adam

ASP.Net MVC: Calling a method from a view

Controller not supposed to be called from view. That's the whole idea of MVC - clear separation of concerns.

If you need to call controller from View - you are doing something wrong. Time for refactoring.

How to trim white spaces of array values in php

If you want to trim and print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:

foreach($array as $key => $value)
{
    $array[$key] = trim($value);
    print("-");
    print($array[$key]);
    print("-");
    print("<br>");
}

If you want to trim but do not want to print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:

$array = array_map('trim', $array);

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

As mobrule indicates, you could use the following instead for a small savings:

if (defined $name && $name ne '') {
    # do something with $name
}

You could ditch the defined check and get something even shorter, e.g.:

if ($name ne '') {
    # do something with $name
}

But in the case where $name is not defined, although the logic flow will work just as intended, if you are using warnings (and you should be), then you'll get the following admonishment:

Use of uninitialized value in string ne

So, if there's a chance that $name might not be defined, you really do need to check for definedness first and foremost in order to avoid that warning. As Sinan Ünür points out, you can use Scalar::MoreUtils to get code that does exactly that (checks for definedness, then checks for zero length) out of the box, via the empty() method:

use Scalar::MoreUtils qw(empty);
if(not empty($name)) {
    # do something with $name 
}

Convert ASCII number to ASCII Character in C

If i is the int, then

char c = i;

makes it a char. You might want to add a check that the value is <128 if it comes from an untrusted source. This is best done with isascii from <ctype.h>, if available on your system (see @Steve Jessop's comment to this answer).

Sending JSON object to Web API

I believe you need quotes around the model:

JSON.stringify({ "model": source })

How can I list all of the files in a directory with Perl?

If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir:

opendir my $dir, "/some/path" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;

You can also use:

my @files = glob( $dir . '/*' );

But in my opinion it is not as good - mostly because glob is quite complex thing (can filter results automatically) and using it to get all elements of directory seems as a too simple task.

On the other hand, if you need to get content from all of the directories and subdirectories, there is basically one standard solution:

use File::Find;

my @content;
find( \&wanted, '/some/path');
do_something_with( @content );

exit;

sub wanted {
  push @content, $File::Find::name;
  return;
}

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

It should be CascadeType.Merge, in that case it will update if the record already exists.

How to read values from the querystring with ASP.NET Core?

  1. Startup.cs add this service services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  2. Your view add inject @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
  3. get your value

Code

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{
    var id = HttpContextAccessor.HttpContext.Request.RouteValues["id"];

    if (id != null)
    {
        // parameter exist in your URL 
    }

    string navigation = await Navigation.WebNavigation(activeTab);
}

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

Simple example of threading in C++

Create a function that you want the thread to execute, eg:

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

Now create the thread object that will ultimately invoke the function above like so:

std::thread t1(task1, "Hello");

(You need to #include <thread> to access the std::thread class)

The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.

If later on you want to wait for the thread to be done executing the function, call:

t1.join(); 

(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).


The Code

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

More information about std::thread here

  • On GCC, compile with -std=c++0x -pthread.
  • This should work for any operating-system, granted your compiler supports this (C++11) feature.

Hive load CSV with commas in quoted fields

As of Hive 0.14, the CSV SerDe is a standard part of the Hive install

ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'

(See: https://cwiki.apache.org/confluence/display/Hive/CSV+Serde)