Programs & Examples On #Jms

The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. JMS is a part of the Java Platform, Enterprise Edition, and is defined by a specification developed under the Java Community Process.

Real world use of JMS/message queues?

Apache Camel used in conjunction with ActiveMQ is great way to do Enterprise Integration Patterns

JMS Topic vs Queues

As for the order preservation, see this ActiveMQ page. In short: order is preserved for single consumers, but with multiple consumers order of delivery is not guaranteed.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

And one more:

#!/bin/bash

# We have:
#
# 1) $KEY : Secret key in PEM format ("-----BEGIN RSA PRIVATE KEY-----") 
# 2) $LEAFCERT : Certificate for secret key obtained from some
#    certification outfit, also in PEM format ("-----BEGIN CERTIFICATE-----")   
# 3) $CHAINCERT : Intermediate certificate linking $LEAFCERT to a trusted
#    Self-Signed Root CA Certificate 
#
# We want to create a fresh Java "keystore" $TARGET_KEYSTORE with the
# password $TARGET_STOREPW, to be used by Tomcat for HTTPS Connector.
#
# The keystore must contain: $KEY, $LEAFCERT, $CHAINCERT
# The Self-Signed Root CA Certificate is obtained by Tomcat from the
# JDK's truststore in /etc/pki/java/cacerts

# The non-APR HTTPS connector (APR uses OpenSSL-like configuration, much
# easier than this) in server.xml looks like this 
# (See: https://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html):
#
#  <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
#                SSLEnabled="true"
#                maxThreads="150" scheme="https" secure="true"
#                clientAuth="false" sslProtocol="TLS"
#                keystoreFile="/etc/tomcat6/etl-web.keystore.jks"
#                keystorePass="changeit" />
#

# Let's roll:    

TARGET_KEYSTORE=/etc/tomcat6/foo-server.keystore.jks
TARGET_STOREPW=changeit

TLS=/etc/pki/tls

KEY=$TLS/private/httpd/foo-server.example.com.key
LEAFCERT=$TLS/certs/httpd/foo-server.example.com.pem
CHAINCERT=$TLS/certs/httpd/chain.cert.pem

# ----
# Create PKCS#12 file to import using keytool later
# ----

# From https://www.sslshopper.com/ssl-converter.html:
# The PKCS#12 or PFX format is a binary format for storing the server certificate,
# any intermediate certificates, and the private key in one encryptable file. PFX
# files usually have extensions such as .pfx and .p12. PFX files are typically used 
# on Windows machines to import and export certificates and private keys.

TMPPW=$$ # Some random password

PKCS12FILE=`mktemp`

if [[ $? != 0 ]]; then
  echo "Creation of temporary PKCS12 file failed -- exiting" >&2; exit 1
fi

TRANSITFILE=`mktemp`

if [[ $? != 0 ]]; then
  echo "Creation of temporary transit file failed -- exiting" >&2; exit 1
fi

cat "$KEY" "$LEAFCERT" > "$TRANSITFILE"

openssl pkcs12 -export -passout "pass:$TMPPW" -in "$TRANSITFILE" -name etl-web > "$PKCS12FILE"

/bin/rm "$TRANSITFILE"

# Print out result for fun! Bug in doc (I think): "-pass " arg does not work, need "-passin"

openssl pkcs12 -passin "pass:$TMPPW" -passout "pass:$TMPPW" -in "$PKCS12FILE" -info

# ----
# Import contents of PKCS12FILE into a Java keystore. WTF, Sun, what were you thinking?
# ----

if [[ -f "$TARGET_KEYSTORE" ]]; then
  /bin/rm "$TARGET_KEYSTORE"
fi

keytool -importkeystore \
   -deststorepass  "$TARGET_STOREPW" \
   -destkeypass    "$TARGET_STOREPW" \
   -destkeystore   "$TARGET_KEYSTORE" \
   -srckeystore    "$PKCS12FILE" \
   -srcstoretype  PKCS12 \
   -srcstorepass  "$TMPPW" \
   -alias foo-the-server

/bin/rm "$PKCS12FILE"

# ----
# Import the chain certificate. This works empirically, it is not at all clear from the doc whether this is correct
# ----

echo "Importing chain"

TT=-trustcacerts

keytool -import $TT -storepass "$TARGET_STOREPW" -file "$CHAINCERT" -keystore "$TARGET_KEYSTORE" -alias chain

# ----
# Print contents
# ----

echo "Listing result"

keytool -list -storepass "$TARGET_STOREPW" -keystore "$TARGET_KEYSTORE"

ActiveMQ or RabbitMQ or ZeroMQ or

I have not used ActiveMQ or RabbitMQ but have used ZeroMQ. The big difference as I see it between ZeroMQ and ActiveMQ etc. is that 0MQ is brokerless and does not have built in reliabilty for message delivery. If you are looking for an easy to use messaging API supporting many messaging patterns,transports, platforms and language bindings then 0MQ is definitely worth a look. If you are looking for a full blown messaging platform then 0MQ may not fit the bill.

See www.zeromq.org/docs:cookbook for plenty examples of how 0MQ can be used.

I an successfully using 0MQ for message passing in an electricity usage monitoring application (see http://rwscott.co.uk/2010/06/14/currentcost-envi-cc128-part-1/)

Access-control-allow-origin with multiple domains

Try this:

<add name="Access-Control-Allow-Origin" value="['URL1','URL2',...]" />

Loading scripts after page load?

http://jsfiddle.net/c725wcn9/2/embedded

You will need to inspect the DOM to check this works. Jquery is needed.

$(document).ready(function(){
   var el = document.createElement('script');
   el.type = 'application/ld+json';
   el.text = JSON.stringify({ "@context": "http://schema.org",  "@type": "Recipe", "name": "My recipe name" });

   document.querySelector('head').appendChild(el);
});

Angular 6 Material mat-select change method removed

For:

1) mat-select (selectionChange)="myFunction()" works in angular as:

sample.component.html

 <mat-select placeholder="Select your option" [(ngModel)]="option" name="action" 
      (selectionChange)="onChange()">
     <mat-option *ngFor="let option of actions" [value]="option">
       {{option}}
     </mat-option>
 </mat-select>

sample.component.ts

actions=['A','B','C'];
onChange() {
  //Do something
}

2) Simple html select (change)="myFunction()" works in angular as:

sample.component.html

<select (change)="onChange()" [(ngModel)]="regObj.status">
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

sample.component.ts

onChange() {
  //Do something
}

How can I connect to MySQL in Python 3 on Windows?

On my mac os maverick i try this:

After that, enter in the python3 interpreter and type:

  1. import pymysql. If there is no error your installation is ok. For verification write a script to connect to mysql with this form:

  2. # a simple script for MySQL connection import pymysql db = pymysql.connect(host="localhost", user="root", passwd="*", db="biblioteca") #Sure, this is information for my db # close the connection db.close ()*

Give it a name ("con.py" for example) and save it on desktop. In Terminal type "cd desktop" and then $python con.py If there is no error, you are connected with MySQL server. Good luck!

Get selected value of a dropdown's item using jQuery

Try this:

 $('#dropDownId option').filter(':selected').text();     

 $('#dropDownId option').filter(':selected').val();

Insert data into hive table

Although there is an accepted answer I would want to add that as of Hive 0.14, record level operations are allowed. The correct syntax and query would be:

INSERT INTO TABLE tweet_table VALUES ('data');

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

This is the most restrictive and safest way I've found, as explained here for hypothetical ~/my/web/root/ directory for your web content:

  • For each parent directory leading to your web root (e.g. ~/my, ~/my/web, ~/my/web/root):
    • chmod go-rwx DIR (nobody other than owner can access content)
    • chmod go+x DIR (to allow "users" including _www to "enter" the dir)
  • sudo chgrp -R _www ~/my/web/root (all web content is now group _www)
  • chmod -R go-rwx ~/my/web/root (nobody other than owner can access web content)
  • chmod -R g+rx ~/my/web/root (all web content is now readable/executable/enterable by _www)

All other solutions leave files open to other local users (who are part of the "staff" group as well as obviously being in the "o"/others group). These users may then freely browse and access DB configurations, source code, or other sensitive details in your web config files and scripts if such are part of your content. If this is not an issue for you, then by all means go with one of the simpler solutions.

TreeMap sort by value

A lot of people hear adviced to use List and i prefer to use it as well

here are two methods you need to sort the entries of the Map according to their values.

    static final Comparator<Entry<?, Double>> DOUBLE_VALUE_COMPARATOR = 
        new Comparator<Entry<?, Double>>() {
            @Override
            public int compare(Entry<?, Double> o1, Entry<?, Double> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        };

        static final List<Entry<?, Double>> sortHashMapByDoubleValue(HashMap temp)
        {
            Set<Entry<?, Double>> entryOfMap = temp.entrySet();

            List<Entry<?, Double>> entries = new ArrayList<Entry<?, Double>>(entryOfMap);
            Collections.sort(entries, DOUBLE_VALUE_COMPARATOR);
            return entries;
        }

How to get column values in one comma separated value

MYSQL: To get column values as one comma separated value use GROUP_CONCAT( ) function as

GROUP_CONCAT(  `column_name` )

for example

SELECT GROUP_CONCAT(  `column_name` ) 
FROM  `table_name` 
WHERE 1 
LIMIT 0 , 30

Defining an abstract class without any abstract methods

YES You can create abstract class with out any abstract method the best example of abstract class without abstract method is HttpServlet
Abstract Method is a method which have no body, If you declared at least one method into the class, the class must be declared as an abstract its mandatory BUT if you declared the abstract class its not mandatory to declared the abstract method inside the class.

You cannot create objects of abstract class, which means that it cannot be instantiated.

How can I use custom fonts on a website?

First, you gotta put your font as either a .otf or .ttf somewhere on your server.

Then use CSS to declare the new font family like this:

@font-face {
    font-family: MyFont;
    src: url('pathway/myfont.otf'); 
    }

If you link your document to the CSS file that you declared your font family in, you can use that font just like any other font.

How to make audio autoplay on chrome

Google changed their policies last month regarding auto-play inside Chrome. Please see this announcement.

They do, however, allow auto-play if you are embedding a video and it is muted. You can add the muted property and it should allow the video to start playing.

<video autoplay controls muted>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>

VBA Convert String to Date

I used this code:

ws.Range("A:A").FormulaR1C1 = "=DATEVALUE(RC[1])"

column A will be mm/dd/yyyy

RC[1] is column B, the TEXT string, eg, 01/30/12, THIS IS NOT DATE TYPE

How do I get the application exit code from a Windows command line?

Testing ErrorLevel works for console applications, but as hinted at by dmihailescu, this won't work if you're trying to run a windowed application (e.g. Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.

Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt's START /WAIT command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel.

start /wait something.exe
echo %errorlevel%

Convert Char to String in C

Using fgetc(fp) only to be able to call strcpy(buffer,c); doesn't seem right.

You could simply build this buffer on your own:

char buffer[MAX_SIZE_OF_MY_BUFFER];

int i = 0;
char ch;
while (i < MAX_SIZE_OF_MY_BUFFER - 1 && (ch = fgetc(fp)) != EOF) {
    buffer[i++] = ch;
}
buffer[i] = '\0';  // terminating character

Note that this relies on the fact that you will read less than MAX_SIZE_OF_MY_BUFFER characters

How can I read inputs as numbers?

For multiple integer in a single line, map might be better.

arr = map(int, raw_input().split())

If the number is already known, (like 2 integers), you can use

num1, num2 = map(int, raw_input().split())

How to calculate distance between two locations using their longitude and latitude value

private String getDistanceOnRoad(double latitude, double longitude,
        double prelatitute, double prelongitude) {
    String result_in_kms = "";
    String url = "http://maps.google.com/maps/api/directions/xml?origin="
            + latitude + "," + longitude + "&destination=" + prelatitute
            + "," + prelongitude + "&sensor=false&units=metric";
    String tag[] = { "text" };
    HttpResponse response = null;
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        response = httpClient.execute(httpPost, localContext);
        InputStream is = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document doc = builder.parse(is);
        if (doc != null) {
            NodeList nl;
            ArrayList args = new ArrayList();
            for (String s : tag) {
                nl = doc.getElementsByTagName(s);
                if (nl.getLength() > 0) {
                    Node node = nl.item(nl.getLength() - 1);
                    args.add(node.getTextContent());
                } else {
                    args.add(" - ");
                }
            }
            result_in_kms = String.format("%s", args.get(0));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result_in_kms;
}

How do you kill all current connections to a SQL Server 2005 database?

I use sp_who to get list of all process in database. This is better because you may want to review which process to kill.

declare @proc table(
    SPID bigint,
    Status nvarchar(255),
    Login nvarchar(255),
    HostName nvarchar(255),
    BlkBy nvarchar(255),
    DBName nvarchar(255),
    Command nvarchar(MAX),
    CPUTime bigint,
    DiskIO bigint,
    LastBatch nvarchar(255),
    ProgramName nvarchar(255),
    SPID2 bigint,
    REQUESTID bigint
)

insert into @proc
exec sp_who2

select  *, KillCommand = concat('kill ', SPID, ';')
from    @proc

Result
You can use command in KillCommand column to kill the process you want to.

SPID    KillCommand
26      kill 26;
27      kill 27;
28      kill 28;

How to sort an array in Bash

tl;dr:

Sort array a_in and store the result in a_out (elements must not have embedded newlines[1] ):

Bash v4+:

readarray -t a_out < <(printf '%s\n' "${a_in[@]}" | sort)

Bash v3:

IFS=$'\n' read -d '' -r -a a_out < <(printf '%s\n' "${a_in[@]}" | sort)

Advantages over antak's solution:

  • You needn't worry about accidental globbing (accidental interpretation of the array elements as filename patterns), so no extra command is needed to disable globbing (set -f, and set +f to restore it later).

  • You needn't worry about resetting IFS with unset IFS.[2]


Optional reading: explanation and sample code

The above combines Bash code with external utility sort for a solution that works with arbitrary single-line elements and either lexical or numerical sorting (optionally by field):

  • Performance: For around 20 elements or more, this will be faster than a pure Bash solution - significantly and increasingly so once you get beyond around 100 elements.
    (The exact thresholds will depend on your specific input, machine, and platform.)

    • The reason it is fast is that it avoids Bash loops.
  • printf '%s\n' "${a_in[@]}" | sort performs the sorting (lexically, by default - see sort's POSIX spec):

    • "${a_in[@]}" safely expands to the elements of array a_in as individual arguments, whatever they contain (including whitespace).

    • printf '%s\n' then prints each argument - i.e., each array element - on its own line, as-is.

  • Note the use of a process substitution (<(...)) to provide the sorted output as input to read / readarray (via redirection to stdin, <), because read / readarray must run in the current shell (must not run in a subshell) in order for output variable a_out to be visible to the current shell (for the variable to remain defined in the remainder of the script).

  • Reading sort's output into an array variable:

    • Bash v4+: readarray -t a_out reads the individual lines output by sort into the elements of array variable a_out, without including the trailing \n in each element (-t).

    • Bash v3: readarray doesn't exist, so read must be used:
      IFS=$'\n' read -d '' -r -a a_out tells read to read into array (-a) variable a_out, reading the entire input, across lines (-d ''), but splitting it into array elements by newlines (IFS=$'\n'. $'\n', which produces a literal newline (LF), is a so-called ANSI C-quoted string).
      (-r, an option that should virtually always be used with read, disables unexpected handling of \ characters.)

Annotated sample code:

#!/usr/bin/env bash

# Define input array `a_in`:
# Note the element with embedded whitespace ('a c')and the element that looks like
# a glob ('*'), chosen to demonstrate that elements with line-internal whitespace
# and glob-like contents are correctly preserved.
a_in=( 'a c' b f 5 '*' 10 )

# Sort and store output in array `a_out`
# Saving back into `a_in` is also an option.
IFS=$'\n' read -d '' -r -a a_out < <(printf '%s\n' "${a_in[@]}" | sort)
# Bash 4.x: use the simpler `readarray -t`:
# readarray -t a_out < <(printf '%s\n' "${a_in[@]}" | sort)

# Print sorted output array, line by line:
printf '%s\n' "${a_out[@]}"

Due to use of sort without options, this yields lexical sorting (digits sort before letters, and digit sequences are treated lexically, not as numbers):

*
10
5
a c
b
f

If you wanted numerical sorting by the 1st field, you'd use sort -k1,1n instead of just sort, which yields (non-numbers sort before numbers, and numbers sort correctly):

*
a c
b
f
5
10

[1] To handle elements with embedded newlines, use the following variant (Bash v4+, with GNU sort):
readarray -d '' -t a_out < <(printf '%s\0' "${a_in[@]}" | sort -z).
Michal Górny's helpful answer has a Bash v3 solution.

[2] While IFS is set in the Bash v3 variant, the change is scoped to the command.
By contrast, what follows IFS=$'\n'  in antak's answer is an assignment rather than a command, in which case the IFS change is global.

select2 changing items dynamically

In my project I use following code:

$('#attribute').select2();
$('#attribute').bind('change', function(){
    var $options = $();
    for (var i in data) {
        $options = $options.add(
            $('<option>').attr('value', data[i].id).html(data[i].text)
        );
    }
    $('#value').html($options).trigger('change');
});

Try to comment out the select2 part. The rest of the code will still work.

Converting time stamps in excel to dates

This DATE-thing won't work in all Excel-versions.

=CELL_ID/(60 * 60 * 24) + "1/1/1970"

is a save bet instead.
The quotes are necessary to prevent Excel from calculating the term.

Check if object value exists within a Javascript array of objects and if not add a new object to array

Let's assume we have an array of objects and you want to check if value of name is defined like this,

let persons = [ {"name" : "test1"},{"name": "test2"}];

if(persons.some(person => person.name == 'test1')) {
    ... here your code in case person.name is defined and available
}

how to get current location in google map android

I think that better way now is:

Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

Documentation. Getting the Last Known Location

Running Windows batch file commands asynchronously

There's a third (and potentially much easier) option. If you want to spin up multiple instances of a single program, using a Unix-style command processor like Xargs or GNU Parallel can make that a fairly straightforward process.

There's a win32 Xargs clone called PPX2 that makes this fairly straightforward.

For instance, if you wanted to transcode a directory of video files, you could run the command:

dir /b *.mpg |ppx2 -P 4 -I {} -L 1 ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"

Picking this apart, dir /b *.mpg grabs a list of .mpg files in my current directory, the | operator pipes this list into ppx2, which then builds a series of commands to be executed in parallel; 4 at a time, as specified here by the -P 4 operator. The -L 1 operator tells ppx2 to only send one line of our directory listing to ffmpeg at a time.

After that, you just write your command line (ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"), and {} gets automatically substituted for each line of your directory listing.

It's not universally applicable to every case, but is a whole lot easier than using the batch file workarounds detailed above. Of course, if you're not dealing with a list of files, you could also pipe the contents of a textfile or any other program into the input of pxx2.

How to run a python script from IDLE interactive shell?

In IDLE, the following works :-

_x000D_
_x000D_
import helloworld
_x000D_
_x000D_
_x000D_

I don't know much about why it works, but it does..

How to read numbers from file in Python?

Not sure why do you need w,h. If these values are actually required and mean that only specified number of rows and cols should be read than you can try the following:

output = []
with open(r'c:\file.txt', 'r') as f:
    w, h  = map(int, f.readline().split())
    tmp = []
    for i, line in enumerate(f):
        if i == h:
            break
        tmp.append(map(int, line.split()[:w]))
    output.append(tmp)

How to launch an Activity from another Application in Android

Since kotlin is becoming very popular these days, I think it's appropriate to provide a simple solution in Kotlin as well.

    var launchIntent: Intent? = null
    try {
        launchIntent = packageManager.getLaunchIntentForPackage("applicationId")
    } catch (ignored: Exception) {
    }
    if (launchIntent == null) {
        startActivity(Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")))
    } else {
        startActivity(launchIntent)
    }

log4j:WARN No appenders could be found for logger (running jar file, not web app)

put the folder which has the properties file for log in java build path source. You can add it by right clicking the project ----> build path -----> configure build path ------> add t

What is the use of the %n format specifier in C?

Those who want to use %n Format Specifier may want to look at this:

Do Not Use the "%n" Format String Specifier

Abstract

Careless use of "%n" format strings can introduce a vulnerability.

Description

There are many kinds of vulnerability that can be caused by misusing format strings. Most of these are covered elsewhere, but this document covers one specific kind of format string vulnerability that is entirely unique for format strings. Documents in the public are inconsistent in coverage of these vulnerabilities.

In C, use of the "%n" format specification in printf() and sprintf() type functions can change memory values. Inappropriate design/implementation of these formats can lead to a vulnerability generated by changes in memory content. Many format vulnerabilities, particularly those with specifiers other than "%n", lead to traditional failures such as segmentation fault. The "%n" specifier has generated more damaging vulnerabilities. The "%n" vulnerabilities may have secondary impacts, since they can also be a significant consumer of computing and networking resources because large guantities of data may have to be transferred to generate the desired pointer value for the exploit.

Avoid using the "%n" format specifier. Use other means to accomplish your purpose.

Source: link

How to check if a table contains an element in Lua?

You can put the values as the table's keys. For example:

function addToSet(set, key)
    set[key] = true
end

function removeFromSet(set, key)
    set[key] = nil
end

function setContains(set, key)
    return set[key] ~= nil
end

There's a more fully-featured example here.

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

All of these are kinds of indices.

primary: must be unique, is an index, is (likely) the physical index, can be only one per table.

unique: as it says. You can't have more than one row with a tuple of this value. Note that since a unique key can be over more than one column, this doesn't necessarily mean that each individual column in the index is unique, but that each combination of values across these columns is unique.

index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.

fulltext: a more specialized form of indexing that allows full text search. Think of it as (essentially) creating an "index" for each "word" in the specified column.

How do I add slashes to a string in Javascript?

replace works for the first quote, so you need a tiny regular expression:

str = str.replace(/'/g, "\\'");

PHP preg replace only allow numbers

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api

Simple DatePicker-like Calendar

this datepicker is an excellent solution. datepickers are a must if you want to avoid code injection.

How to check the version of scipy

on command line

 example$:python
 >>> import scipy
 >>> scipy.__version__
 '0.9.0'

JOIN two SELECT statement results

SELECT t1.ks, t1.[# Tasks], COALESCE(t2.[# Late], 0) AS [# Late]
FROM 
    (SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
LEFT JOIN
    (SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON (t1.ks = t2.ks);

How do I format currencies in a Vue component?

The comment by @RoyJ has a great suggestion. In the template you can just use built-in localized strings:

<small>
     Total: <b>{{ item.total.toLocaleString() }}</b>
</small>

It's not supported in some of the older browsers, but if you're targeting IE 11 and later, you should be fine.

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

This also happened to me when I had a default document of the same name (like index.aspx) specified in both my web.config file AND my IIS website. I ended up removing the entry from the IIS website and kept the web.config entry like below:

<system.webServer>
  <defaultDocument>
    <files>
      <add value="index.aspx" />
    </files>
  </defaultDocument>...

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

space between divs - display table-cell

Well, the above does work, here is my solution that requires a little less markup and is more flexible.

_x000D_
_x000D_
.cells {_x000D_
  display: inline-block;_x000D_
  float: left;_x000D_
  padding: 1px;_x000D_
}_x000D_
.cells>.content {_x000D_
  background: #EEE;_x000D_
  display: table-cell;_x000D_
  float: left;_x000D_
  padding: 3px;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<div id="div1" class="cells"><div class="content">My Cell 1</div></div>_x000D_
<div id="div2" class="cells"><div class="content">My Cell 2</div></div>
_x000D_
_x000D_
_x000D_

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

Pressed <button> selector

You can do this with php if the button opens a new page.

For example if the button link to a page named pagename.php as, url: www.website.com/pagename.php the button will stay red as long as you stay on that page.

I exploded the url by '/' an got something like:

url[0] = pagename.php

<? $url = explode('/', substr($_SERVER['REQUEST_URI'], strpos('/',$_SERVER['REQUEST_URI'] )+1,strlen($_SERVER['REQUEST_URI']))); ?>


<html>
<head>
  <style>
    .btn{
     background:white;
     }
    .btn:hover,
    .btn-on{
     background:red;
     }
  </style>
</head>
<body>
   <a href="/pagename.php" class="btn <? if (url[0]='pagename.php') {echo 'btn-on';} ?>">Click Me</a>
</body>
</html>

note: I didn't try this code. It might need adjustments.

Reactjs convert html string to jsx

i start using npm package called react-html-parser

MySQL foreign key constraints, cascade delete

I think (I'm not certain) that foreign key constraints won't do precisely what you want given your table design. Perhaps the best thing to do is to define a stored procedure that will delete a category the way you want, and then call that procedure whenever you want to delete a category.

CREATE PROCEDURE `DeleteCategory` (IN category_ID INT)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
BEGIN

DELETE FROM
    `products`
WHERE
    `id` IN (
        SELECT `products_id`
        FROM `categories_products`
        WHERE `categories_id` = category_ID
    )
;

DELETE FROM `categories`
WHERE `id` = category_ID;

END

You also need to add the following foreign key constraints to the linking table:

ALTER TABLE `categories_products` ADD
    CONSTRAINT `Constr_categoriesproducts_categories_fk`
    FOREIGN KEY `categories_fk` (`categories_id`) REFERENCES `categories` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT `Constr_categoriesproducts_products_fk`
    FOREIGN KEY `products_fk` (`products_id`) REFERENCES `products` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE

The CONSTRAINT clause can, of course, also appear in the CREATE TABLE statement.

Having created these schema objects, you can delete a category and get the behaviour you want by issuing CALL DeleteCategory(category_ID) (where category_ID is the category to be deleted), and it will behave how you want. But don't issue a normal DELETE FROM query, unless you want more standard behaviour (i.e. delete from the linking table only, and leave the products table alone).

How could I convert data from string to long in c#

This answer no longer works, and I cannot come up with anything better then the other answers (see below) listed here. Please review and up-vote them.

Convert.ToInt64("1100.25")

Method signature from MSDN:

public static long ToInt64(
    string value
)

How to use systemctl in Ubuntu 14.04

Ubuntu 14 and lower does not have "systemctl" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot

Configure Docker to start on boot:

Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.

1) systemd (Ubuntu 16 and above):

$ sudo systemctl enable docker

To disable this behavior, use disable instead.

$ sudo systemctl disable docker

2) upstart (Ubuntu 14 and below):

Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:

$ echo manual | sudo tee /etc/init/docker.override
chkconfig

$ sudo chkconfig docker on

Done.

Parsing CSV files in C#, with header

In a business application, i use the Open Source project on codeproject.com, CSVReader.

It works well, and has good performance. There is some benchmarking on the link i provided.

A simple example, copied from the project page:

using (CsvReader csv = new CsvReader(new StreamReader("data.csv"), true))
{
    int fieldCount = csv.FieldCount;
    string[] headers = csv.GetFieldHeaders();

    while (csv.ReadNextRecord())
    {
        for (int i = 0; i < fieldCount; i++)
            Console.Write(string.Format("{0} = {1};", headers[i], csv[i]));

        Console.WriteLine();
    }
}

As you can see, it's very easy to work with.

Making interface implementations async

Better solution is to introduce another interface for async operations. New interface must inherit from original interface.

Example:

interface IIO
{
    void DoOperation();
}

interface IIOAsync : IIO
{
    Task DoOperationAsync();
}


class ClsAsync : IIOAsync
{
    public void DoOperation()
    {
        DoOperationAsync().GetAwaiter().GetResult();
    }

    public async Task DoOperationAsync()
    {
        //just an async code demo
        await Task.Delay(1000);
    }
}


class Program
{
    static void Main(string[] args)
    {
        IIOAsync asAsync = new ClsAsync();
        IIO asSync = asAsync;

        Console.WriteLine(DateTime.Now.Second);

        asAsync.DoOperation();
        Console.WriteLine("After call to sync func using Async iface: {0}", 
            DateTime.Now.Second);

        asAsync.DoOperationAsync().GetAwaiter().GetResult();
        Console.WriteLine("After call to async func using Async iface: {0}", 
            DateTime.Now.Second);

        asSync.DoOperation();
        Console.WriteLine("After call to sync func using Sync iface: {0}", 
            DateTime.Now.Second);

        Console.ReadKey(true);
    }
}

P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.

How to change environment's font size?

Currently it is not possible to change the font family or size outside the editor. You can however zoom the entire user interface in and out from the View menu.

Update for our VS Code 1.0 release:

A newly introduced setting window.zoomLevel allows to persist the zoom level for good! It can have both negative and positive values to zoom in or out.

Java current machine name and logged in user?

To get the currently logged in user path:

System.getProperty("user.home");

How to export and import a .sql file from command line with options?

mysqldump will not dump database events, triggers and routines unless explicitly stated when dumping individual databases;

mysqldump -uuser -p db_name --events --triggers --routines > db_name.sql

Create folder with batch but only if it doesn't already exist

i created this for my script I use in my work for eyebeam.

:CREATES A CHECK VARIABLE

set lookup=0

:CHECKS IF THE FOLDER ALREADY EXIST"

IF EXIST "%UserProfile%\AppData\Local\CounterPath\RegNow Enhanced\default_user\" (set lookup=1)

:IF CHECK is still 0 which means does not exist. It creates the folder

IF %lookup%==0 START "" mkdir "%UserProfile%\AppData\Local\CounterPath\RegNow Enhanced\default_user\"

New line in Sql Query

-- Access: 
SELECT CHR(13) & CHR(10) 

-- SQL Server: 
SELECT CHAR(13) + CHAR(10)

How can I change the text color with jQuery?

Place the following in your jQuery mouseover event handler:

$(this).css('color', 'red');

To set both color and size at the same time:

$(this).css({ 'color': 'red', 'font-size': '150%' });

You can set any CSS attribute using the .css() jQuery function.

psql: FATAL: role "postgres" does not exist

For MAC:

  1. Install Homebrew
  2. brew install postgres
  3. initdb /usr/local/var/postgres
  4. /usr/local/Cellar/postgresql/<version>/bin/createuser -s postgres or /usr/local/opt/postgres/bin/createuser -s postgres which will just use the latest version.
  5. start postgres server manually: pg_ctl -D /usr/local/var/postgres start

To start server at startup

  • mkdir -p ~/Library/LaunchAgents
  • ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
  • launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

Now, it is set up, login using psql -U postgres -h localhost or use PgAdmin for GUI.

By default user postgres will not have any login password.

Check this site for more articles like this: https://medium.com/@Nithanaroy/installing-postgres-on-mac-18f017c5d3f7

Get url parameters from a string in .NET

Or if you don't know the URL (so as to avoid hardcoding, use the AbsoluteUri

Example ...

        //get the full URL
        Uri myUri = new Uri(Request.Url.AbsoluteUri);
        //get any parameters
        string strStatus = HttpUtility.ParseQueryString(myUri.Query).Get("status");
        string strMsg = HttpUtility.ParseQueryString(myUri.Query).Get("message");
        switch (strStatus.ToUpper())
        {
            case "OK":
                webMessageBox.Show("EMAILS SENT!");
                break;
            case "ER":
                webMessageBox.Show("EMAILS SENT, BUT ... " + strMsg);
                break;
        }

How to get TimeZone from android mobile?

Try this code-

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

It will return user selected timezone.

How do I execute a bash script in Terminal?

You could do:
sh scriptname.sh

How to get a JavaScript object's class?

There is one another technique to identify your class You can store ref to your class in instance like bellow.

class MyClass {
    static myStaticProperty = 'default';
    constructor() {
        this.__class__ = new.target;
        this.showStaticProperty = function() {
            console.log(this.__class__.myStaticProperty);
        }
    }
}

class MyChildClass extends MyClass {
    static myStaticProperty = 'custom';
}

let myClass = new MyClass();
let child = new MyChildClass();

myClass.showStaticProperty(); // default
child.showStaticProperty(); // custom

myClass.__class__ === MyClass; // true
child.__class__ === MyClass; // false
child.__class__ === MyChildClass; // true

Create patch or diff file from git repository and apply it to another different git repository

To produce patch for several commits, you should use format-patch git command, e.g.

git format-patch -k --stdout R1..R2

This will export your commits into patch file in mailbox format.

To generate patch for the last commit, run:

git format-patch -k --stdout HEAD^

Then in another repository apply the patch by am git command, e.g.

git am -3 -k file.patch

See: man git-format-patch and git-am.

Eclipse interface icons very small on high resolution screen in Windows 8.1

I figured that one solution would be to run a batch operation on the Eclipse JAR's which contain the icons and double their size. After a bit of tinkering, it worked. Results are pretty good - there's still a few "stubborn" icons which are tiny but most look good.

Eclipse After Processing on QHD

I put together the code into a small project: https://github.com/davidglevy/eclipse-icon-enlarger

The project works by:

  1. Iterating over every file in the eclipse base directory (specified in argument line)
  2. If a file is a directory, create a new directory under the present one in the output folder (specified in the argument line)
  3. If a file is a PNG or GIF, double
  4. If a file is another type copy
  5. If a file is a JAR or ZIP, create a target file and process the contents using a similar process: a. Images are doubled b. Other files are copied across into the ZipOutputStream as is.

The only problem I've found with this solution is that it really only works once - if you need to download plugins then do so in the original location and re-apply the icon increase batch process.

On the Dell XPS it takes about 5 minutes to run.

Happy for suggestions/improvements but this is really just an adhoc solution while we wait for the Eclipse team to get a fix out.

CASE .. WHEN expression in Oracle SQL

You can only check the first character of the status. For this you use substring function.

substr(status, 1,1)

In your case past.

auto create database in Entity Framework Core

If you want both of EnsureCreated and Migrate use this code:

     using (var context = new YourDbContext())
            {
                if (context.Database.EnsureCreated())
                {
                    //auto migration when database created first time

                    //add migration history table

                    string createEFMigrationsHistoryCommand = $@"
USE [{context.Database.GetDbConnection().Database}];
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
CREATE TABLE [dbo].[__EFMigrationsHistory](
    [MigrationId] [nvarchar](150) NOT NULL,
    [ProductVersion] [nvarchar](32) NOT NULL,
 CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY CLUSTERED 
(
    [MigrationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY];
";
                    context.Database.ExecuteSqlRaw(createEFMigrationsHistoryCommand);

                    //insert all of migrations
                    var dbAssebmly = context.GetType().GetAssembly();
                    foreach (var item in dbAssebmly.GetTypes())
                    {
                        if (item.BaseType == typeof(Migration))
                        {
                            string migrationName = item.GetCustomAttributes<MigrationAttribute>().First().Id;
                            var version = typeof(Migration).Assembly.GetName().Version;
                            string efVersion = $"{version.Major}.{version.Minor}.{version.Build}";
                            context.Database.ExecuteSqlRaw("INSERT INTO __EFMigrationsHistory(MigrationId,ProductVersion) VALUES ({0},{1})", migrationName, efVersion);
                        }
                    }
                }
                context.Database.Migrate();
            }

Scanning Java annotations at runtime

You can use Java Pluggable Annotation Processing API to write annotation processor which will be executed during the compilation process and will collect all annotated classes and build the index file for runtime use.

This is the fastest way possible to do annotated class discovery because you don't need to scan your classpath at runtime, which is usually very slow operation. Also this approach works with any classloader and not only with URLClassLoaders usually supported by runtime scanners.

The above mechanism is already implemented in ClassIndex library.

To use it annotate your custom annotation with @IndexAnnotated meta-annotation. This will create at compile time an index file: META-INF/annotations/com/test/YourCustomAnnotation listing all annotated classes. You can acccess the index at runtime by executing:

ClassIndex.getAnnotated(com.test.YourCustomAnnotation.class)

How to configure a HTTP proxy for svn

In windows 7, you may have to edit this file

C:\Users\<UserName>\AppData\Roaming\Subversion\servers

[global]
http-proxy-host = ip.add.re.ss
http-proxy-port = 3128

Why can't I use the 'await' operator within the body of a lock statement?

Basically it would be the wrong thing to do.

There are two ways this could be implemented:

  • Keep hold of the lock, only releasing it at the end of the block.
    This is a really bad idea as you don't know how long the asynchronous operation is going to take. You should only hold locks for minimal amounts of time. It's also potentially impossible, as a thread owns a lock, not a method - and you may not even execute the rest of the asynchronous method on the same thread (depending on the task scheduler).

  • Release the lock in the await, and reacquire it when the await returns
    This violates the principle of least astonishment IMO, where the asynchronous method should behave as closely as possible like the equivalent synchronous code - unless you use Monitor.Wait in a lock block, you expect to own the lock for the duration of the block.

So basically there are two competing requirements here - you shouldn't be trying to do the first here, and if you want to take the second approach you can make the code much clearer by having two separated lock blocks separated by the await expression:

// Now it's clear where the locks will be acquired and released
lock (foo)
{
}
var result = await something;
lock (foo)
{
}

So by prohibiting you from awaiting in the lock block itself, the language is forcing you to think about what you really want to do, and making that choice clearer in the code that you write.

Copy data from another Workbook through VBA

The best (and easiest) way to copy data from a workbook to another is to use the object model of Excel.

Option Explicit
Sub test()
    Dim wb As Workbook, wb2 As Workbook
    Dim ws As Worksheet
    Dim vFile As Variant

    'Set source workbook
    Set wb = ActiveWorkbook
    'Open the target workbook
    vFile = Application.GetOpenFilename("Excel-files,*.xls", _
        1, "Select One File To Open", , False)
    'if the user didn't select a file, exit sub
    If TypeName(vFile) = "Boolean" Then Exit Sub
    Workbooks.Open vFile
    'Set targetworkbook
    Set wb2 = ActiveWorkbook

    'For instance, copy data from a range in the first workbook to another range in the other workbook
    wb2.Worksheets("Sheet2").Range("C3:D4").Value = wb.Worksheets("Sheet1").Range("A1:B2").Value
End Sub

What is the best way to create a string array in python?

strlist =[{}]*10
strlist[0] = set()
strlist[0].add("Beef")
strlist[0].add("Fish")
strlist[1] = {"Apple", "Banana"}
strlist[1].add("Cherry")
print(strlist[0])
print(strlist[1])
print(strlist[2])
print("Array size:", len(strlist))
print(strlist)

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

You only need the async pipe:

<li *ngFor="let afd of afdeling | async">
    {{afd.patientid}}
</li>

always use the async pipe when dealing with Observables directly without explicitly unsubscribe.

Delete ActionLink with confirm dialog

Using webgrid you can found it here, the action links could look like the following.

enter image description here

    grid.Column(header: "Action", format: (item) => new HtmlString(
                     Html.ActionLink(" ", "Details", new { Id = item.Id }, new { @class = "glyphicon glyphicon-info-sign" }).ToString() + " | " +
                     Html.ActionLink(" ", "Edit", new { Id = item.Id }, new { @class = "glyphicon glyphicon-edit" }).ToString() + " | " +
                     Html.ActionLink(" ", "Delete", new { Id = item.Id }, new { onclick = "return confirm('Are you sure you wish to delete this property?');", @class = "glyphicon glyphicon-trash" }).ToString()
                )

Hide keyboard in react-native

The problem with keyboard not dismissing gets more severe if you have keyboardType='numeric', as there is no way to dismiss it.

Replacing View with ScrollView is not a correct solution, as if you have multiple textInputs or buttons, tapping on them while the keyboard is up will only dismiss the keyboard.

Correct way is to encapsulate View with TouchableWithoutFeedback and calling Keyboard.dismiss()

EDIT: You can now use ScrollView with keyboardShouldPersistTaps='handled' to only dismiss the keyboard when the tap is not handled by the children (ie. tapping on other textInputs or buttons)

If you have

<View style={{flex: 1}}>
    <TextInput keyboardType='numeric'/>
</View>

Change it to

<ScrollView contentContainerStyle={{flexGrow: 1}}
  keyboardShouldPersistTaps='handled'
>
  <TextInput keyboardType='numeric'/>
</ScrollView>

or

import {Keyboard} from 'react-native'

<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
    <View style={{flex: 1}}>
        <TextInput keyboardType='numeric'/>
    </View>
</TouchableWithoutFeedback>

EDIT: You can also create a Higher Order Component to dismiss the keyboard.

import React from 'react';
import { TouchableWithoutFeedback, Keyboard, View } from 'react-native';

const DismissKeyboardHOC = (Comp) => {
  return ({ children, ...props }) => (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
      <Comp {...props}>
        {children}
      </Comp>
    </TouchableWithoutFeedback>
  );
};
const DismissKeyboardView = DismissKeyboardHOC(View)

Simply use it like this

...
render() {
    <DismissKeyboardView>
        <TextInput keyboardType='numeric'/>
    </DismissKeyboardView>
}

NOTE: the accessible={false} is required to make the input form continue to be accessible through VoiceOver. Visually impaired people will thank you!

Telegram Bot - how to get a group chat id?

IMHO the best way to do this is using TeleThon, but given that the answer by apadana is outdated beyond repair, I will write the working solution here:

import os
import sys
from telethon import TelegramClient
from telethon.utils import get_display_name

import nest_asyncio
nest_asyncio.apply()

session_name = "<session_name>"
api_id = <api_id>
api_hash = "<api_hash>"
dialog_count = 10 # you may change this

if f"{session_name}.session" in os.listdir():
    os.remove(f"{session_name}.session")

client = TelegramClient(session_name, api_id, api_hash)

async def main():
    dialogs = await client.get_dialogs(dialog_count)
    for dialog in dialogs:
        print(get_display_name(dialog.entity), dialog.entity.id)

async with client:
    client.loop.run_until_complete(main())

this snippet will give you the first 10 chats in your Telegram.

Assumptions:

  • you have telethon and nest_asyncio installed
  • you have api_id and api_hash from my.telegram.org

How to set specific window (frame) size in java swing?

Try this, but you can adjust frame size with bounds and edit title.

package co.form.Try;

import javax.swing.JFrame;

public class Form {

    public static void main(String[] args) {
        JFrame obj =new JFrame();
        obj.setBounds(10,10,700,600); 
        obj.setTitle("Application Form");
        obj.setResizable(false);                
        obj.setVisible(true);       
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

Shortcut to Apply a Formula to an Entire Column in Excel

If the formula already exists in a cell you can fill it down as follows:

  • Select the cell containing the formula and press CTRL+SHIFT+DOWN to select the rest of the column (CTRL+SHIFT+END to select up to the last row where there is data)
  • Fill down by pressing CTRL+D
  • Use CTRL+UP to return up

On Mac, use CMD instead of CTRL.

An alternative if the formula is in the first cell of a column:

  • Select the entire column by clicking the column header or selecting any cell in the column and pressing CTRL+SPACE
  • Fill down by pressing CTRL+D

await is only valid in async function

"await is only valid in async function"

But why? 'await' explicitly turns an async call into a synchronous call, and therefore the caller cannot be async (or asyncable) - at least, not because of the call being made at 'await'.

How to check 'undefined' value in jQuery

If you have names of the element and not id we can achieve the undefined check on all text elements (for example) as below and fill them with a default value say 0.0:

var aFieldsCannotBeNull=['ast_chkacc_bwr','ast_savacc_bwr'];
 jQuery.each(aFieldsCannotBeNull,function(nShowIndex,sShowKey) {
   var $_oField = jQuery("input[name='"+sShowKey+"']");
   if($_oField.val().trim().length === 0){
       $_oField.val('0.0')
    }
  })

Using a RegEx to match IP addresses in Python

If you really want to use RegExs, the following code may filter the non-valid ip addresses in a file, no matter the organiqation of the file, one or more per line, even if there are more text (concept itself of RegExs) :

def getIps(filename):
    ips = []
    with open(filename) as file:
        for line in file:
            ipFound = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").findall(line)
            hasIncorrectBytes = False
            try:
                    for ipAddr in ipFound:
                        for byte in ipAddr:
                            if int(byte) not in range(1, 255):
                                hasIncorrectBytes = True
                                break
                            else:
                                pass
                    if not hasIncorrectBytes:
                        ips.append(ipAddr)
            except:
                hasIncorrectBytes = True

    return ips

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

psql: could not connect to server: No such file or directory (Mac OS X)

SUPER NEWBIE ALERT: I'm just learning web development and the particular tutorial I was following mentioned I have to install Postgres but didn't actually mention I have to run it as well... Once I opened the Postgres application everything was fine and dandy.

Matplotlib - global legend and title aside subplots

In addition to the orbeckst answer one might also want to shift the subplots down. Here's an MWE in OOP style:

import matplotlib.pyplot as plt

fig = plt.figure()
st = fig.suptitle("suptitle", fontsize="x-large")

ax1 = fig.add_subplot(311)
ax1.plot([1,2,3])
ax1.set_title("ax1")

ax2 = fig.add_subplot(312)
ax2.plot([1,2,3])
ax2.set_title("ax2")

ax3 = fig.add_subplot(313)
ax3.plot([1,2,3])
ax3.set_title("ax3")

fig.tight_layout()

# shift subplots down:
st.set_y(0.95)
fig.subplots_adjust(top=0.85)

fig.savefig("test.png")

gives:

enter image description here

Possible to perform cross-database queries with PostgreSQL?

see https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/ [published 2017]

These days you also have the option to use https://prestodb.io/

You can run SQL on that PrestoDB node and it will distribute the SQL query as required. It can connect to the same node twice for different databases, or it might be connecting to different nodes on different hosts.

It does not support:

DELETE
ALTER TABLE
CREATE TABLE (CREATE TABLE AS is supported)
GRANT
REVOKE
SHOW GRANTS
SHOW ROLES
SHOW ROLE GRANTS

So you should only use it for SELECT and JOIN needs. Connect directly to each database for the above needs. (It looks like you can also INSERT or UPDATE which is nice)

Client applications connect to PrestoDB primarily using JDBC, but other types of connection are possible including a Tableu compatible web API

This is an open source tool governed by the Linux Foundation and Presto Foundation.

The founding members of the Presto Foundation are: Facebook, Uber, Twitter, and Alibaba.

The current members are: Facebook, Uber, Twitter, Alibaba, Alluxio, Ahana, Upsolver, and Intel.

How to yum install Node.JS on Amazon Linux

https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions

curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash - sudo yum -y install nodejs

SASS :not selector

I tried re-creating this, and .someclass.notip was being generated for me but .someclass:not(.notip) was not, for as long as I did not have the @mixin tip() defined. Once I had that, it all worked.

http://sassmeister.com/gist/9775949

$dropdown-width: 100px;
$comp-tip: true;

@mixin tip($pos:right) {

}

@mixin dropdown-pos($pos:right) {
  &:not(.notip) {
    @if $comp-tip == true{
      @if $pos == right {
        top:$dropdown-width * -0.6;
        background-color: #f00;
        @include tip($pos:$pos);
      }
    }
  }
  &.notip {
    @if $pos == right {
      top: 0;
      left:$dropdown-width * 0.8;
      background-color: #00f;
    }
  }
}

.someclass { @include dropdown-pos(); }

EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'. it what I get when I remove @mixin tip($pos:right) { }

Python list / sublist selection -1 weirdness

-1 isn't special in the sense that the sequence is read backwards, it rather wraps around the ends. Such that minus one means zero minus one, exclusive (and, for a positive step value, the sequence is read "from left to right".

so for i = [1, 2, 3, 4], i[2:-1] means from item two to the beginning minus one (or, 'around to the end'), which results in [3]. The -1th element, or element 0 backwards 1 is the last 4, but since it's exclusive, we get 3.

I hope this is somewhat understandable.

Microsoft.ReportViewer.Common Version=12.0.0.0

I worked on this issue for a few days. Installed all packages, modified web.config and still had the same problem. I finally removed

<assemblies>
<add assembly="Microsoft.ReportViewer.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</assemblies>

from the web.config and it worked. No exactly sure why it didn't work with the tags in the web.config file. My guess there is a conflict with the GAC and the BIN folder.

Here is my web.config file:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <httpHandlers>
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />     
    </httpHandlers>    
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />      
    </handlers>
  </system.webServer>
</configuration>

Programmatically scroll a UIScrollView

Here is another use case which worked well for me.

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

Code: Swift 5.3

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

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

HTML Code for text checkbox '?'

Just make sure that your HTML file is encoded with UTF-8 and that your web server sends a HTTP header with that charset, then you just can write that character directly into your HTMl file.

http://www.w3.org/International/O-HTTP-charset

If you can't use UTF-8 for some reason, you can look up the codes in a unicode list such as http://en.wikipedia.org/wiki/List_of_Unicode_characters and use &#xABCD; where ABCD is the hexcode from that list (U+ABCD).

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

There's an even simpler solution - delete the cache folder at user/.android/built-cache and go back to android studio and sync with gradle again, if that still doesn't work delete the cache folder again, and restart android studio and re-import the project

Multiple arguments to function called by pthread_create()?

Use:

struct arg_struct *args = malloc(sizeof(struct arg_struct));

And pass this arguments like this:

pthread_create(&tr, NULL, print_the_arguments, (void *)args);

Don't forget free args! ;)

How to open a new HTML page using jQuery?

use window.open("file2.html"); to open on new window,

or use window.location.href = "file2.html" to open on same window.

How do I get hour and minutes from NSDate?

This seems to me to be what the question is after, no need for formatters:

NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

Nginx -- static file serving confusion with root & alias

Just a quick addendum to @good_computer's very helpful answer, I wanted to replace to root of the URL with a folder, but only if it matched a subfolder containing static files (which I wanted to retain as part of the path).

For example if file requested is in /app/js or /app/css, look in /app/location/public/[that folder].

I got this to work using a regex.

 location ~ ^/app/((images/|stylesheets/|javascripts/).*)$ {
     alias /home/user/sites/app/public/$1;
     access_log off;
     expires max;
 }

Maximum number of rows of CSV data in excel sheet

Using the Excel Text import wizard to import it if it is a text file, like a CSV file, is another option and can be done based on which row number to which row numbers you specify. See: This link

How do you close/hide the Android soft keyboard using Java?

Using AndroidX, we are going to get an amazing way to show/ hide keyboards. Read the Release Notes - 1.5.0-alpha02. Now how to hide/ show Keyboard

val controller = view.windowInsetsController

// Show the keyboard
controller.show(Type.ime())
// Hide the keyboard
controller.hide(Type.ime())

Linking my own answer How to check visibility of software keyboard in Android? and an Amazing blog which includes more of this change (even more than it).

SQL Client for Mac OS X that works with MS SQL Server

Let's work together on a canonical answer.

Native Apps

Java-Based

Electron-Based

(TODO: Add others mentioned below)

Java creating .jar file

Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.

I.e.:

$query = "SELECT col1 FROM table WHERE col_x = ?";

Then trying to access more columns/rows inside a loop.

I.e.:

print_r($row['col1']);
print_r($row['col2']); // undefined index thrown

or in a while loop:

while( $row = fetching_function($query) ) {

    echo $row['col1'];
    echo "<br>";
    echo $row['col2']; // undefined index thrown
    echo "<br>";
    echo $row['col3']; // undefined index thrown

}

Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.

Consult the followning Q&A's on Stack:

What uses are there for "placement new"?

I've used it for storing objects with memory mapped files.
The specific example was an image database which processed vey large numbers of large images (more than could fit in memory).

Gradle project refresh failed after Android Studio update

Check the Gradle home path after the update to version 1.5. It should be ../gradle-2.8.

enter image description here

Get textarea text with javascript or Jquery

To get the value from a textarea with an id you just have to do

Edited

$("#area1").val();

If you are having more than one element with the same id in the document then the HTML is invalid.

Why does this CSS margin-top style not work?

You're actually seeing the top margin of the #inner element collapse into the top edge of the #outer element, leaving only the #outer margin intact (albeit not shown in your images). The top edges of both boxes are flush against each other because their margins are equal.

Here are the relevant points from the W3C spec:

8.3.1 Collapsing margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Adjoining vertical margins collapse [...]

Two margins are adjoining if and only if:

  • both belong to in-flow block-level boxes that participate in the same block formatting context
  • no line boxes, no clearance, no padding and no border separate them
  • both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
    • top margin of a box and top margin of its first in-flow child

You can do any of the following to prevent the margin from collapsing:

The reason the above options prevent the margin from collapsing is because:

  • Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
  • Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
  • Margins of inline-block boxes do not collapse (not even with their in-flow children).

The left and right margins behave as you expect because:

Horizontal margins never collapse.

If (Array.Length == 0)

This is the best way. Please note Array is an object in NET so you need to check for null before.

How can I convert a .py to .exe for Python?

The best and easiest way is auto-py-to-exe for sure, and I have given all the steps and red flags below which will take you just 5 mins to get a final .exe file as you don't have to learn anything to use it.

1.) It may not work for python 3.9 on some devices I guess.

2.) While installing python, if you had selected 'add python 3.x to path', open command prompt from start menu and you will have to type pip install auto-py-to-exe to install it. You will have to press enter on command prompt to get the result of the line that you are typing.

3.) Once it is installed, on command prompt itself, you can simply type just auto-py-to-exe to open it. It will open a new window. It may take up to a minute the first time. Also, closing command prompt will close auto-py-to-exe also so don't close it till you have your .exe file ready.

4.) There will be buttons for everything you need to make a .exe file and the screenshot of it is shared below. Also, for the icon, you need a .ico file instead of an image so to convert it, you can use https://convertio.co/

5.) If your script uses external files, you can add them through auto-py-to-exe and in the script, you will have to do some changes to their path. First, you have to write import sys if not written already, second, you have to make a variable for eg, location=getattr(sys,"_MEIPASS",".")+"/", third, the location of example.png would be location+"/example.png" if it is not in any folder.

6.) If it is showing any error, it may probably be because of a module called setuptools not being at the latest version. To upgrade it to the latest version, on command prompt, you will have to write pip install --upgrade setuptools. Also, in the script, writing import setuptools may help. If the version of setuptools is more than 50.0.0 then everything should be fine.

7.) After all these steps, in auto-py-to-exe, when the conversion is complete, the .exe file will be in the folder that you would have chosen (by default, it is 'c:/users/name/output') or it would have been removed by your antivirus if you have one. Every antivirus has different methods to restore a file so just experiment if you don't know.

Here is how the simple GUI of auto-py-to-exe can be used to make a .exe file.

enter image description here

Python read JSON file and modify

try this script:

with open("data.json") as f:
    data = json.load(f)
    data["id"] = 134
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "name":"mynamme",
    "id":134
}

Just the arrangement is different, You can solve the problem by converting the "data" type to a list, then arranging it as you wish, then returning it and saving the file, like that:

index_add = 0
with open("data.json") as f:
    data = json.load(f)
    data_li = [[k, v] for k, v in data.items()]
    data_li.insert(index_add, ["id", 134])
    data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "id":134,
    "name":"myname"
}

you can add if condition in order not to repeat the key, just change it, like that:

index_add = 0
n_k = "id"
n_v = 134
with open("data.json") as f:
    data = json.load(f)
    if n_k in data:
        data[n_k] = n_v
    else:
       data_li = [[k, v] for k, v in data.items()]
       data_li.insert(index_add, [n_k, n_v])
       data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

How do I terminate a thread in C++11?

I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job. I would suggest using a "naive" way.

Define some global boolean:

std::atomic_bool stop_thread_1 = false;

Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:

if (stop_thread_1)
    return;

Then to stop the thread from another (main) thread:

stop_thread_1 = true;
thread1.join ();
stop_thread_1 = false; //(for next time. this can be when starting the thread instead)

How to debug on a real device (using Eclipse/ADT)

in devices which has Android 4.3 and above you should follow these steps:

How to enable Developer Options:

Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.

In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.

Consistency of hashCode() on a Java string

I found something about JDK 1.0 and 1.1 and >= 1.2:

In JDK 1.0.x and 1.1.x the hashCode function for long Strings worked by sampling every nth character. This pretty well guaranteed you would have many Strings hashing to the same value, thus slowing down Hashtable lookup. In JDK 1.2 the function has been improved to multiply the result so far by 31 then add the next character in sequence. This is a little slower, but is much better at avoiding collisions. Source: http://mindprod.com/jgloss/hashcode.html

Something different, because you seem to need a number: How about using CRC32 or MD5 instead of hashcode and you are good to go - no discussions and no worries at all...

SyntaxError: cannot assign to operator

What do you think this is supposed to be: ((t[1])/length) * t[1] += string

Python can't parse this, it's a syntax error.

jQuery: how to trigger anchor link's click event

You cannot open in a new tab programmatically, it's a browser functionality. You can open a link in an external window . Have a look here

How to find all combinations of coins when given some dollar value

I would favor a recursive solution. You have some list of denominations, if the smallest one can evenly divide any remaining currency amount, this should work fine.

Basically, you move from largest to smallest denominations.
Recursively,

  1. You have a current total to fill, and a largest denomination (with more than 1 left). If there is only 1 denomination left, there is only one way to fill the total. You can use 0 to k copies of your current denomination such that k * cur denomination <= total.
  2. For 0 to k, call the function with the modified total and new largest denomination.
  3. Add up the results from 0 to k. That's how many ways you can fill your total from the current denomination on down. Return this number.

Here's my python version of your stated problem, for 200 cents. I get 1463 ways. This version prints all the combinations and the final count total.

#!/usr/bin/python

# find the number of ways to reach a total with the given number of combinations

cents = 200
denominations = [25, 10, 5, 1]
names = {25: "quarter(s)", 10: "dime(s)", 5 : "nickel(s)", 1 : "pennies"}

def count_combs(left, i, comb, add):
    if add: comb.append(add)
    if left == 0 or (i+1) == len(denominations):
        if (i+1) == len(denominations) and left > 0:
           if left % denominations[i]:
               return 0
           comb.append( (left/denominations[i], demoninations[i]) )
           i += 1
        while i < len(denominations):
            comb.append( (0, denominations[i]) )
            i += 1
        print(" ".join("%d %s" % (n,names[c]) for (n,c) in comb))
        return 1
    cur = denominations[i]
    return sum(count_combs(left-x*cur, i+1, comb[:], (x,cur)) for x in range(0, int(left/cur)+1))

count_combs(cents, 0, [], None)

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Use the following extensions and just pass the action like:

_frmx.PerformSafely(() => _frmx.Show());
_frmx.PerformSafely(() => _frmx.Location = new Point(x,y));

Extension class:

public static class CrossThreadExtensions
{
    public static void PerformSafely(this Control target, Action action)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action);
        }
        else
        {
            action();
        }
    }

    public static void PerformSafely<T1>(this Control target, Action<T1> action,T1 parameter)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, parameter);
        }
        else
        {
            action(parameter);
        }
    }

    public static void PerformSafely<T1,T2>(this Control target, Action<T1,T2> action, T1 p1,T2 p2)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, p1,p2);
        }
        else
        {
            action(p1,p2);
        }
    }
}

how to bind datatable to datagridview in c#

// I built my datatable first, and populated it, columns, rows and all. //Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.

 BindingSource SBind = new BindingSource();
 SBind.DataSource = dtSourceData;

 ADGView1.AutoGenerateColumns = true;  //must be "true" here
 ADGView1.Columns.Clear();
 ADGView1.DataSource = SBind;

 //set DGV's column names and headings from the Datatable properties
 for (int i = 0; i < ADGView1.Columns.Count; i++)
 {
       ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
       ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
 }
 ADGView1.Enabled = true;
 ADGView1.Refresh();

Iterate through string array in Java

I would argue instead of testing i less than elements.length - 1 testing i + 1 less than elements.length. You aren't changing the domain of the array that you are looking at (i.e. ignoring the last element), but rather changing the greatest element you are looking at in each iteration.

String[] elements = { "a", "a","a","a" };

for(int i = 0; i + 1 < elements.length; i++) {
    String first = elements[i];
    String second = elements[i+1];
    //do something with the two strings
}

Is Ruby pass by reference or by value?

Lots of great answers diving into the theory of how Ruby's "pass-reference-by-value" works. But I learn and understand everything much better by example. Hopefully, this will be helpful.

def foo(bar)
  puts "bar (#{bar}) entering foo with object_id #{bar.object_id}"
  bar =  "reference"
  puts "bar (#{bar}) leaving foo with object_id #{bar.object_id}"
end

bar = "value"
puts "bar (#{bar}) before foo with object_id #{bar.object_id}"
foo(bar)
puts "bar (#{bar}) after foo with object_id #{bar.object_id}"

# Output
bar (value) before foo with object_id 60
bar (value) entering foo with object_id 60
bar (reference) leaving foo with object_id 80 # <-----
bar (value) after foo with object_id 60 # <-----

As you can see when we entered the method, our bar was still pointing to the string "value". But then we assigned a string object "reference" to bar, which has a new object_id. In this case bar inside of foo, has a different scope, and whatever we passed inside the method, is no longer accessed by bar as we re-assigned it and point it to a new place in memory that holds String "reference".

Now consider this same method. The only difference is what with do inside the method

def foo(bar)
  puts "bar (#{bar}) entering foo with object_id #{bar.object_id}"
  bar.replace "reference"
  puts "bar (#{bar}) leaving foo with object_id #{bar.object_id}"
end

bar = "value"
puts "bar (#{bar}) before foo with object_id #{bar.object_id}"
foo(bar)
puts "bar (#{bar}) after foo with object_id #{bar.object_id}"

# Output
bar (value) before foo with object_id 60
bar (value) entering foo with object_id 60
bar (reference) leaving foo with object_id 60 # <-----
bar (reference) after foo with object_id 60 # <-----

Notice the difference? What we did here was: we modified the contents of the String object, that variable was pointing to. The scope of bar is still different inside of the method.

So be careful how you treat the variable passed into methods. And if you modify passed-in variables-in-place (gsub!, replace, etc), then indicate so in the name of the method with a bang !, like so "def foo!"

P.S.:

It's important to keep in mind that the "bar"s inside and outside of foo, are "different" "bar". Their scope is different. Inside the method, you could rename "bar" to "club" and the result would be the same.

I often see variables re-used inside and outside of methods, and while it's fine, it takes away from the readability of the code and is a code smell IMHO. I highly recommend not to do what I did in my example above :) and rather do this

def foo(fiz)
  puts "fiz (#{fiz}) entering foo with object_id #{fiz.object_id}"
  fiz =  "reference"
  puts "fiz (#{fiz}) leaving foo with object_id #{fiz.object_id}"
end

bar = "value"
puts "bar (#{bar}) before foo with object_id #{bar.object_id}"
foo(bar)
puts "bar (#{bar}) after foo with object_id #{bar.object_id}"

# Output
bar (value) before foo with object_id 60
fiz (value) entering foo with object_id 60
fiz (reference) leaving foo with object_id 80
bar (value) after foo with object_id 60

Why aren't programs written in Assembly more often?

As a developer who spends most of his time in the embedded programming world, I would argue that assembly is far from a dead/obsolete language. There is a certain close-to-the-metal level of coding (for example, in drivers) that sometimes cannot be expressed as accurately or efficiently in a higher-level language. We write nearly all of our hardware interface routines in assembler.

That being said, this assembly code is wrapped such that it can be called from C code and is treated like a library. We don't write the entire program in assembly for many reasons. First and foremost is portability; our code base is used on several products that use different architectures and we want to maximize the amount of code that can be shared between them. Second is developer familiarity. Simply put, schools don't teach assembly like they used to, and our developers are far more productive in C than in assembly. Also, we have a wide variety of "extras" (things like libraries, debuggers, static analysis tools, etc) available for our C code that aren't available for assembly language code. Even if we wanted to write a pure-assembly program, we would not be able to because several critical hardware libraries are only available as C libs. In one sense, it's a chicken/egg problem. People are driven away from assembly because there aren't as many libraries and development/debug tools available for it, but the libs/tools don't exist because not enough people use assembly to warrant the effort creating them.

In the end, there is a time and a place for just about any language. People use what they are most familiar and productive with. There will probably always be a place in a programmer's repertoire for assembly, but most programmers will find that they can write code in a higher-level language that is almost as efficient in far less time.

VBA: Convert Text to Number

For large datasets a faster solution is required.

Making use of 'Text to Columns' functionality provides a fast solution.

Example based on column F, starting range at 25 to LastRow

Sub ConvTxt2Nr()

Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long

Set sht = ThisWorkbook.Sheets("DumpDB")

LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row

Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)

SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True

End Sub

Why is processing a sorted array faster than processing an unsorted array?

You are a victim of branch prediction fail.


What is Branch Prediction?

Consider a railroad junction:

Image showing a railroad junction Image by Mecanismo, via Wikimedia Commons. Used under the CC-By-SA 3.0 license.

Now for the sake of argument, suppose this is back in the 1800s - before long distance or radio communication.

You are the operator of a junction and you hear a train coming. You have no idea which way it is supposed to go. You stop the train to ask the driver which direction they want. And then you set the switch appropriately.

Trains are heavy and have a lot of inertia. So they take forever to start up and slow down.

Is there a better way? You guess which direction the train will go!

  • If you guessed right, it continues on.
  • If you guessed wrong, the captain will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.

If you guess right every time, the train will never have to stop.
If you guess wrong too often, the train will spend a lot of time stopping, backing up, and restarting.


Consider an if-statement: At the processor level, it is a branch instruction:

Screenshot of compiled code containing an if statement

You are a processor and you see a branch. You have no idea which way it will go. What do you do? You halt execution and wait until the previous instructions are complete. Then you continue down the correct path.

Modern processors are complicated and have long pipelines. So they take forever to "warm up" and "slow down".

Is there a better way? You guess which direction the branch will go!

  • If you guessed right, you continue executing.
  • If you guessed wrong, you need to flush the pipeline and roll back to the branch. Then you can restart down the other path.

If you guess right every time, the execution will never have to stop.
If you guess wrong too often, you spend a lot of time stalling, rolling back, and restarting.


This is branch prediction. I admit it's not the best analogy since the train could just signal the direction with a flag. But in computers, the processor doesn't know which direction a branch will go until the last moment.

So how would you strategically guess to minimize the number of times that the train must back up and go down the other path? You look at the past history! If the train goes left 99% of the time, then you guess left. If it alternates, then you alternate your guesses. If it goes one way every three times, you guess the same...

In other words, you try to identify a pattern and follow it. This is more or less how branch predictors work.

Most applications have well-behaved branches. So modern branch predictors will typically achieve >90% hit rates. But when faced with unpredictable branches with no recognizable patterns, branch predictors are virtually useless.

Further reading: "Branch predictor" article on Wikipedia.


As hinted from above, the culprit is this if-statement:

if (data[c] >= 128)
    sum += data[c];

Notice that the data is evenly distributed between 0 and 255. When the data is sorted, roughly the first half of the iterations will not enter the if-statement. After that, they will all enter the if-statement.

This is very friendly to the branch predictor since the branch consecutively goes the same direction many times. Even a simple saturating counter will correctly predict the branch except for the few iterations after it switches direction.

Quick visualization:

T = branch taken
N = branch not taken

data[] = 0, 1, 2, 3, 4, ... 126, 127, 128, 129, 130, ... 250, 251, 252, ...
branch = N  N  N  N  N  ...   N    N    T    T    T  ...   T    T    T  ...

       = NNNNNNNNNNNN ... NNNNNNNTTTTTTTTT ... TTTTTTTTTT  (easy to predict)

However, when the data is completely random, the branch predictor is rendered useless, because it can't predict random data. Thus there will probably be around 50% misprediction (no better than random guessing).

data[] = 226, 185, 125, 158, 198, 144, 217, 79, 202, 118,  14, 150, 177, 182, ...
branch =   T,   T,   N,   T,   T,   T,   T,  N,   T,   N,   N,   T,   T,   T  ...

       = TTNTTTTNTNNTTT ...   (completely random - impossible to predict)

So what can be done?

If the compiler isn't able to optimize the branch into a conditional move, you can try some hacks if you are willing to sacrifice readability for performance.

Replace:

if (data[c] >= 128)
    sum += data[c];

with:

int t = (data[c] - 128) >> 31;
sum += ~t & data[c];

This eliminates the branch and replaces it with some bitwise operations.

(Note that this hack is not strictly equivalent to the original if-statement. But in this case, it's valid for all the input values of data[].)

Benchmarks: Core i7 920 @ 3.5 GHz

C++ - Visual Studio 2010 - x64 Release

Scenario Time (seconds)
Branching - Random data 11.777
Branching - Sorted data 2.352
Branchless - Random data 2.564
Branchless - Sorted data 2.587

Java - NetBeans 7.1.1 JDK 7 - x64

Scenario Time (seconds)
Branching - Random data 10.93293813
Branching - Sorted data 5.643797077
Branchless - Random data 3.113581453
Branchless - Sorted data 3.186068823

Observations:

  • With the Branch: There is a huge difference between the sorted and unsorted data.
  • With the Hack: There is no difference between sorted and unsorted data.
  • In the C++ case, the hack is actually a tad slower than with the branch when the data is sorted.

A general rule of thumb is to avoid data-dependent branching in critical loops (such as in this example).


Update:

  • GCC 4.6.1 with -O3 or -ftree-vectorize on x64 is able to generate a conditional move. So there is no difference between the sorted and unsorted data - both are fast.

    (Or somewhat fast: for the already-sorted case, cmov can be slower especially if GCC puts it on the critical path instead of just add, especially on Intel before Broadwell where cmov has 2 cycle latency: gcc optimization flag -O3 makes code slower than -O2)

  • VC++ 2010 is unable to generate conditional moves for this branch even under /Ox.

  • Intel C++ Compiler (ICC) 11 does something miraculous. It interchanges the two loops, thereby hoisting the unpredictable branch to the outer loop. So not only is it immune to the mispredictions, it is also twice as fast as whatever VC++ and GCC can generate! In other words, ICC took advantage of the test-loop to defeat the benchmark...

  • If you give the Intel compiler the branchless code, it just out-right vectorizes it... and is just as fast as with the branch (with the loop interchange).

This goes to show that even mature modern compilers can vary wildly in their ability to optimize code...

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

Declare multiple module.exports in Node.js

use this

(function()
{
  var exports = module.exports = {};
  exports.yourMethod =  function (success)
  {

  }
  exports.yourMethod2 =  function (success)
  {

  }


})();

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

As the error says your router link should match the existing routes configured

It should be just routerLink="/about"

Which port(s) does XMPP use?

According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.

The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.

What's the difference between Invoke() and BeginInvoke()

Delegate.BeginInvoke() asynchronously queues the call of a delegate and returns control immediately. When using Delegate.BeginInvoke(), you should call Delegate.EndInvoke() in the callback method to get the results.

Delegate.Invoke() synchronously calls the delegate in the same thread.

MSDN Article

regular expression for Indian mobile numbers

i have used this regex in my projects and this works fine.

pattern="[6-9]{1}[0-9]{9}"

How to create a DataFrame of random integers with Pandas?

numpy.random.randint accepts a third argument (size) , in which you can specify the size of the output array. You can use this to create your DataFrame -

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Here - np.random.randint(0,100,size=(100, 4)) - creates an output array of size (100,4) with random integer elements between [0,100) .


Demo -

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

which produces:

     A   B   C   D
0   45  88  44  92
1   62  34   2  86
2   85  65  11  31
3   74  43  42  56
4   90  38  34  93
5    0  94  45  10
6   58  23  23  60
..  ..  ..  ..  ..

IsNull function in DB2 SQL?

I'm not familiar with DB2, but have you tried COALESCE?

ie:


SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product

Summing elements in a list

You can sum numbers in a list simply with the sum() built-in:

sum(your_list)

It will sum as many number items as you have. Example:

my_list = range(10, 17)
my_list
[10, 11, 12, 13, 14, 15, 16]

sum(my_list)
91

For your specific case:

For your data convert the numbers into int first and then sum the numbers:

data = ['5', '4', '9']

sum(int(i) for i in data)
18

This will work for undefined number of elements in your list (as long as they are "numbers")

Thanks for @senderle's comment re conversion in case the data is in string format.

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

I got this error too even I ran cmd as an Administrator.

The root cause is: The file is from VCS(subversion, perforce, etc.), and when I checked the properties of this file, its' Attributes is Read-only.

So the solution is:

  • (1) disable the 'Read-only' Attribute;
  • (2) check out from VCS, let the file under the status of read&write.

How do I configure Maven for offline development?

Sadly dependency:go-offline hasn't worked for me as it didn't cached everything, ie. POMs files and other implicitly mention dependencies.

The workaround has been to specify a local repository location, either within settings.xml file with <localRepository>...</localRepository> or by running mvn with -Dmaven.repo.local=... parameter. After initial project build, all necessary artifacts should be cached, and then you can reference repository location the same ways, while running Maven build in offline mode (mvn -o ...).

Why can't I set text to an Android TextView?

In your java class, set the "EditText" Type to "TextView". Because you have declared a TextView in the layout.xml file

Javascript Confirm popup Yes, No button instead of OK and Cancel

Have a look at http://bootboxjs.com/

Very easy to use:

 bootbox.confirm("Are you sure?", function(result) {
  Example.show("Confirm result: "+result);
});

Range with step of type float

You could use numpy.arange.

EDIT: The docs prefer numpy.linspace. Thanks @Droogans for noticing =)

Javascript Array inside Array - how can I call the child array name?

You've made an array of arrays (multidimensional), so options[0] in this case is the size array. you need to reference the first element of the child, which for you is: options[0][0].

If you wanted to loop through all entries you can use the for .. in ... syntax which is described here.

var a = [1,2,4,5,120,12];
for (var val in t) {
    console.log(t[val]);
}

var b = ['S','M','L'];
var both = [a,b];

for (var val in both) {
     for(val2 in both[val]){console.log(both[val][val2])}
}

Android: Pass data(extras) to a fragment

I prefer Serializable = no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable does not matter.

I would also always provide a helper method for a Fragment or Activity, this way you always know, what data has to be passed. Here an example for your ListMusicFragment:

private static final String EXTRA_MUSIC_LIST = "music_list";

public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_MUSIC_LIST, music);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public View onCreateView(...) { 
    ...
    Bundle bundle = intent.getArguments();
    List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
    ...
}

How to get the number of columns from a JDBC ResultSet?

This will print the data in columns and comes to new line once last column is reached.

ResultSetMetaData resultSetMetaData = res.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
for(int i =1; i<=columnCount; i++){
                if(!(i==columnCount)){

                    System.out.print(res.getString(i)+"\t");
                }
                else{
                    System.out.println(res.getString(i));
                }

            }

Can you hide the controls of a YouTube embed without enabling autoplay?

To continue using the iframe YouTube, you should only have to change ?autoplay=1 to ?autoplay=0.

Another way to accomplish this would be by using the YouTube JavaScript Player API. (https://developers.google.com/youtube/js_api_reference)

Edit: the YouTube JavaScript Player API is no longer supported.

<div id="howToVideo"></div>

<script type="application/javascript">

    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = false;
    ga.src = 'http://www.youtube.com/player_api';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);

    var done = false;
    var player;

    function onYouTubePlayerAPIReady() {
        player = new YT.Player('howToVideo', {
            height: '390',
            width: '640',
            videoId: 'qUJYqhKZrwA',
        playerVars: {
            controls: 0,
            disablekb: 1
        },
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
    }
    function onPlayerReady(evt) {
        console.log('onPlayerReady', evt);
    }
    function onPlayerStateChange(evt) {
        console.log('onPlayerStateChange', evt);
        if (evt.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }

    function stopVideo() {
        console.log('stopVideo');
        player.stopVideo();
    }

</script>

Here is a jsfiddle for the example: http://jsfiddle.net/fgkrj/

Note that player controls are disabled in the "playerVars" part of the player. The one sacrifice you make is that users are still able to pause the video by clicking on it. I would suggest writing a simple javascript function that subscribes to a stop event and calls player.playVideo().

What are the differences between Pandas and NumPy+SciPy in Python?

pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.

How to flip background image using CSS?

You can flip it horizontally with CSS...

a:visited {
    -moz-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    transform: scaleX(-1);
    filter: FlipH;
    -ms-filter: "FlipH";
}

jsFiddle.

If you want to flip vertically instead...

a:visited {
    -moz-transform: scaleY(-1);
    -o-transform: scaleY(-1);
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
    filter: FlipV;
    -ms-filter: "FlipV";
}

Source.

Text not wrapping in p tag

add float: left property to the image.

#rb-menu-com li .submenu div img {
    border:1px solid #fff;
    float:left;
}

Return multiple values in JavaScript?

You can also do:

function a(){
  var d=2;
  var c=3;
  var f=4;
  return {d:d,c:c,f:f}
}

const {d,c,f} = a()

Convert date to YYYYMM format

SELECT LEFT(CONVERT(varchar, GetDate(),112),6)

MySQL does not start when upgrading OSX to Yosemite or El Capitan

Solved by installing the latest mySQL release, following the instructions here http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/

EDIT
As Yosemite gets more popular, more people are stumbling on this question. The answer above has to do with upgrading MySQL, so that it runs. The answer linked by @doc in the comments has to do with getting MySQL to start automatically. These are 2 separate issues.

ASP.NET MVC on IIS 7.5

ASP.NET 4 was not registered in IIS. Had to run the following command in the command line/run

32bit (x86) Windows

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

64bit (x64) Windows

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

Note from David Murdoch's comment:

That the .net version has changed since this Answer was posted. Check which version of the framework is in the %windir%\Microsoft.NET\Framework64 directory and change the command accordingly before running (it is currently v4.0.30319)

Detect if user is scrolling

this works:

window.onscroll = function (e) {  
// called when the window is scrolled.  
} 

edit:

you said this is a function in a TimeInterval..
Try doing it like so:

userHasScrolled = false;
window.onscroll = function (e)
{
    userHasScrolled = true;
}

then inside your Interval insert this:

if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}

php execute a background process

Assuming this is running on a Linux machine, I've always handled it like this:

exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));

This launches the command $cmd, redirects the command output to $outputfile, and writes the process id to $pidfile.

That lets you easily monitor what the process is doing and if it's still running.

function isRunning($pid){
    try{
        $result = shell_exec(sprintf("ps %d", $pid));
        if( count(preg_split("/\n/", $result)) > 2){
            return true;
        }
    }catch(Exception $e){}

    return false;
}

How to have a default option in Angular.js select box

I needed the default “Please Select” to be unselectable. I also needed to be able to conditionally set a default selected option.

I achieved this the following simplistic way: JS code: // Flip these 2 to test selected default or no default with default “Please Select” text //$scope.defaultOption = 0; $scope.defaultOption = { key: '3', value: 'Option 3' };

$scope.options = [
   { key: '1', value: 'Option 1' },
   { key: '2', value: 'Option 2' },
   { key: '3', value: 'Option 3' },
   { key: '4', value: 'Option 4' }
];

getOptions();

function getOptions(){
    if ($scope.defaultOption != 0)
    { $scope.options.selectedOption = $scope.defaultOption; }
}

HTML:

<select name="OptionSelect" id="OptionSelect" ng-model="options.selectedOption" ng-options="item.value for item in options track by item.key">
<option value="" disabled selected style="display: none;"> -- Please Select -- </option>
</select>
<h1>You selected: {{options.selectedOption.key}}</h1>         

I hope this helps someone else that has similar requirements.

The "Please Select" was accomplished through Joffrey Outtier's answer here.

Change tab bar item selected color in a storyboard

You can also set selected image bar tint color by key path:

enter image description here

Hope this will help you!! Thanks

What is the difference/usage of homebrew, macports or other package installation tools?

MacPorts is the way to go.

  1. Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.

  2. MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.

  3. MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.

  4. If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.

  5. MacPorts support groups.

    foo@macpro:~/ port select --summary
    
    Name        Selected      Options
    ====        ========      =======
    db          none          db46 none
    gcc         none          gcc42 llvm-gcc42 mp-gcc48 none
    llvm        none          mp-llvm-3.3 none
    mysql       mysql56       mysql56 none
    php         php55         php55 php56 none
    postgresql  postgresql94  postgresql93 postgresql94 none
    python      none          python24 python25-apple python26-apple python27 python27-apple none
    

    If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.

  6. Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.

Regular expression for floating point numbers

^[+]?([0-9]{1,2})*[.,]([0-9]{1,1})?$

This will match:

  1. 1.2
  2. 12.3
  3. 1,2
  4. 12,3

JPA CascadeType.ALL does not delete orphans

For the records, in OpenJPA before JPA2 it was @ElementDependant.

How to create a shared library with cmake?

Always specify the minimum required version of cmake

cmake_minimum_required(VERSION 3.9)

You should declare a project. cmake says it is mandatory and it will define convenient variables PROJECT_NAME, PROJECT_VERSION and PROJECT_DESCRIPTION (this latter variable necessitate cmake 3.9):

project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")

Declare a new library target. Please avoid the use of file(GLOB ...). This feature does not provide attended mastery of the compilation process. If you are lazy, copy-paste output of ls -1 sources/*.cpp :

add_library(mylib SHARED
    sources/animation.cpp
    sources/buffers.cpp
    [...]
)

Set VERSION property (optional but it is a good practice):

set_target_properties(mylib PROPERTIES VERSION ${PROJECT_VERSION})

You can also set SOVERSION to a major number of VERSION. So libmylib.so.1 will be a symlink to libmylib.so.1.0.0.

set_target_properties(mylib PROPERTIES SOVERSION 1)

Declare public API of your library. This API will be installed for the third-party application. It is a good practice to isolate it in your project tree (like placing it include/ directory). Notice that, private headers should not be installed and I strongly suggest to place them with the source files.

set_target_properties(mylib PROPERTIES PUBLIC_HEADER include/mylib.h)

If you work with subdirectories, it is not very convenient to include relative paths like "../include/mylib.h". So, pass a top directory in included directories:

target_include_directories(mylib PRIVATE .)

or

target_include_directories(mylib PRIVATE include)
target_include_directories(mylib PRIVATE src)

Create an install rule for your library. I suggest to use variables CMAKE_INSTALL_*DIR defined in GNUInstallDirs:

include(GNUInstallDirs)

And declare files to install:

install(TARGETS mylib
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})

You may also export a pkg-config file. This file allows a third-party application to easily import your library:

Create a template file named mylib.pc.in (see pc(5) manpage for more information):

prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=@CMAKE_INSTALL_PREFIX@
libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@

Name: @PROJECT_NAME@
Description: @PROJECT_DESCRIPTION@
Version: @PROJECT_VERSION@

Requires:
Libs: -L${libdir} -lmylib
Cflags: -I${includedir}

In your CMakeLists.txt, add a rule to expand @ macros (@ONLY ask to cmake to not expand variables of the form ${VAR}):

configure_file(mylib.pc.in mylib.pc @ONLY)

And finally, install generated file:

install(FILES ${CMAKE_BINARY_DIR}/mylib.pc DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)

You may also use cmake EXPORT feature. However, this feature is only compatible with cmake and I find it difficult to use.

Finally the entire CMakeLists.txt should looks like:

cmake_minimum_required(VERSION 3.9)
project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")
include(GNUInstallDirs)
add_library(mylib SHARED src/mylib.c)
set_target_properties(mylib PROPERTIES
    VERSION ${PROJECT_VERSION}
    SOVERSION 1
    PUBLIC_HEADER api/mylib.h)
configure_file(mylib.pc.in mylib.pc @ONLY)
target_include_directories(mylib PRIVATE .)
install(TARGETS mylib
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES ${CMAKE_BINARY_DIR}/mylib.pc
    DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)

JPA eager fetch does not join

JPA doesn't provide any specification on mapping annotations to select fetch strategy. In general, related entities can be fetched in any one of the ways given below

  • SELECT => one query for root entities + one query for related mapped entity/collection of each root entity = (n+1) queries
  • SUBSELECT => one query for root entities + second query for related mapped entity/collection of all root entities retrieved in first query = 2 queries
  • JOIN => one query to fetch both root entities and all of their mapped entity/collection = 1 query

So SELECT and JOIN are two extremes and SUBSELECT falls in between. One can choose suitable strategy based on her/his domain model.

By default SELECT is used by both JPA/EclipseLink and Hibernate. This can be overridden by using:

@Fetch(FetchMode.JOIN) 
@Fetch(FetchMode.SUBSELECT)

in Hibernate. It also allows to set SELECT mode explicitly using @Fetch(FetchMode.SELECT) which can be tuned by using batch size e.g. @BatchSize(size=10).

Corresponding annotations in EclipseLink are:

@JoinFetch
@BatchFetch

How to annotate MYSQL autoincrement field with JPA annotations

As you have define the id in int type at the database creation, you have to use the same data type in the model class too. And as you have defined the id to auto increment in the database, you have to mention it in the model class by passing value 'GenerationType.AUTO' into the attribute 'strategy' within the annotation @GeneratedValue. Then the code becomes as below.

@Entity
public class Operator{

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;

  private String username;

  private String password;

  private Integer active;

  //Getters and setters...
}

Default value to a parameter while passing by reference in C++

It has been said in one of the direct comments to your answer already, but just to state it officially. What you want to use is an overload:

virtual const ULONG Write(ULONG &State, bool sequence);
inline const ULONG Write()
{
  ULONG state;
  bool sequence = true;
  Write (state, sequence);
}

Using function overloads also have additional benefits. Firstly you can default any argument you wish:

class A {}; 
class B {}; 
class C {};

void foo (A const &, B const &, C const &);
void foo (B const &, C const &); // A defaulted
void foo (A const &, C const &); // B defaulted
void foo (C const &); // A & B defaulted etc...

It is also possible to redefine default arguments to virtual functions in derived class, which overloading avoids:

class Base {
public:
  virtual void f1 (int i = 0);  // default '0'

  virtual void f2 (int);
  inline void f2 () {
    f2(0);                      // equivalent to default of '0'
  }
};

class Derived : public Base{
public:
  virtual void f1 (int i = 10);  // default '10'

  using Base::f2;
  virtual void f2 (int);
};

void bar ()
{
  Derived d;
  Base & b (d);
  d.f1 ();   // '10' used
  b.f1 ();   // '0' used

  d.f2 ();   // f1(int) called with '0' 
  b.f2 ();   // f1(int) called with '0
}

There is only one situation where a default really needs to be used, and that is on a constructor. It is not possible to call one constructor from another, and so this technique does not work in that case.

Limit results in jQuery UI Autocomplete

I could solve this problem by adding the following content to my CSS file:

.ui-autocomplete {
    max-height: 200px;
    overflow-y: auto;
    overflow-x: hidden;
}

Issue pushing new code in Github

If this is your first push, then you might not care about the history on the remote. You could then do a "force push" to skip checks that git does to prevent you from overwriting any existing, or differing, work on remote. Use with extreme care!

just change the

git push **-u** origin master

change it like this!

git push -f origin master

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

Is there a Newline constant defined in Java like Environment.Newline in C#?

Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").

When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.

Understanding the map function

The map() function is there to apply the same procedure to every item in an iterable data structure, like lists, generators, strings, and other stuff.

Let's look at an example: map() can iterate over every item in a list and apply a function to each item, than it will return (give you back) the new list.

Imagine you have a function that takes a number, adds 1 to that number and returns it:

def add_one(num):
  new_num = num + 1
  return new_num

You also have a list of numbers:

my_list = [1, 3, 6, 7, 8, 10]

if you want to increment every number in the list, you can do the following:

>>> map(add_one, my_list)
[2, 4, 7, 8, 9, 11]

Note: At minimum map() needs two arguments. First a function name and second something like a list.

Let's see some other cool things map() can do. map() can take multiple iterables (lists, strings, etc.) and pass an element from each iterable to a function as an argument.

We have three lists:

list_one = [1, 2, 3, 4, 5]
list_two = [11, 12, 13, 14, 15]
list_three = [21, 22, 23, 24, 25]

map() can make you a new list that holds the addition of elements at a specific index.

Now remember map(), needs a function. This time we'll use the builtin sum() function. Running map() gives the following result:

>>> map(sum, list_one, list_two, list_three)
[33, 36, 39, 42, 45]

REMEMBER:
In Python 2 map(), will iterate (go through the elements of the lists) according to the longest list, and pass None to the function for the shorter lists, so your function should look for None and handle them, otherwise you will get errors. In Python 3 map() will stop after finishing with the shortest list. Also, in Python 3, map() returns an iterator, not a list.

Count unique values using pandas groupby

I think you can use SeriesGroupBy.nunique:

print (df.groupby('param')['group'].nunique())
param
a    2
b    1
Name: group, dtype: int64

Another solution with unique, then create new df by DataFrame.from_records, reshape to Series by stack and last value_counts:

a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a    2
b    1
dtype: int64

How to extract text from an existing docx file using python-docx

There are two "generations" of python-docx. The initial generation ended with the 0.2.x versions and the "new" generation started at v0.3.0. The new generation is a ground-up, object-oriented rewrite of the legacy version. It has a distinct repository located here.

The opendocx() function is part of the legacy API. The documentation is for the new version. The legacy version has no documentation to speak of.

Neither reading nor writing hyperlinks are supported in the current version. That capability is on the roadmap, and the project is under active development. It turns out to be quite a broad API because Word has so much functionality. So we'll get to it, but probably not in the next month unless someone decides to focus on that aspect and contribute it. UPDATE Hyperlink support was added subsequent to this answer.

EditorFor() and html properties

I also had issue with setting the width of TextBox in MVC3, while setting the Clsss attribute worked for TextArea control but not for TextBoxFor control or EditorFor control:

I tried following & that worked for me:

@Html.TextBoxFor(model => model.Title, new { Class = "textBox", style = "width:90%;" })

also in this case Validations are working perfectly.

This project references NuGet package(s) that are missing on this computer

I had the same error but in my case it was not related to nuget packages at all. My solution had project that had reference to other projects that were not a part of my solution and were not built. After building them with some other solution (or I could include them into my solution as well), AND re-opening my solution in visual studio the issue was resolved.

Base table or view not found: 1146 Table Laravel 5

When you are passing the custom request in the controller method, and your request file doesn't follow the proper syntax or table name is changed, then laravel through this type of exception. I'll show you in Example.

My Request code.
     public function rules()
        {
            return [
                'name' => 'required|unique:posts|max:50',
                'description' => 'required',
            ];
        }

But my table name is todos not posts so that's why it through "Base table or view not found: 1146 Table Laravel 7


    I forgot to change the table name in first index.
     public function rules()
        {
            return [
                'name' => 'required|unique:todos|max:50',
                'description' => 'required',
            ];
        }

How do I count the number of occurrences of a char in a String?

My 'idiomatic one-liner' for this is:

int count = StringUtils.countMatches("a.b.c.d", ".");

Why write it yourself when it's already in commons lang?

Spring Framework's oneliner for this is:

int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");

PHP - remove all non-numeric characters from a string

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

Where are static methods and static variables stored in Java?

Class variables(Static variables) are stored as part of the Class object associated with that class. This Class object can only be created by JVM and is stored in permanent generation.

Also some have answered that it is stored in non heap area which is called Method Area. Even this answer is not wrong. It is just a debatable topic whether Permgen Area is a part of heap or not. Obviously perceptions differ from person to person. In my opinion we provide heap space and permgen space differently in JVM arguments. So it is a good assumption to treat them differently.

Another way to see it

Memory pools are created by JVM memory managers during runtime. Memory pool may belong to either heap or non-heap memory.A run time constant pool is a per-class or per-interface run time representation of the constant_pool table in a class file. Each runtime constant pool is allocated from the Java virtual machine’s method area and Static Variables are stored in this Method Area. Also this non-heap is nothing but perm gen area.Actually Method area is part of perm gen.(Reference)

enter image description here

What is the simplest SQL Query to find the second largest value?

select * from emp e where 3>=(select count(distinct salary)
    from emp where s.salary<=salary)

This query selects the maximum three salaries. If two emp get the same salary this does not affect the query.

matplotlib: Group boxplots

Here is my version. It stores data based on categories.

import matplotlib.pyplot as plt
import numpy as np

data_a = [[1,2,5], [5,7,2,2,5], [7,2,5]]
data_b = [[6,4,2], [1,2,5,3,2], [2,3,5,1]]

ticks = ['A', 'B', 'C']

def set_box_color(bp, color):
    plt.setp(bp['boxes'], color=color)
    plt.setp(bp['whiskers'], color=color)
    plt.setp(bp['caps'], color=color)
    plt.setp(bp['medians'], color=color)

plt.figure()

bpl = plt.boxplot(data_a, positions=np.array(xrange(len(data_a)))*2.0-0.4, sym='', widths=0.6)
bpr = plt.boxplot(data_b, positions=np.array(xrange(len(data_b)))*2.0+0.4, sym='', widths=0.6)
set_box_color(bpl, '#D7191C') # colors are from http://colorbrewer2.org/
set_box_color(bpr, '#2C7BB6')

# draw temporary red and blue lines and use them to create a legend
plt.plot([], c='#D7191C', label='Apples')
plt.plot([], c='#2C7BB6', label='Oranges')
plt.legend()

plt.xticks(xrange(0, len(ticks) * 2, 2), ticks)
plt.xlim(-2, len(ticks)*2)
plt.ylim(0, 8)
plt.tight_layout()
plt.savefig('boxcompare.png')

I am short of reputation so I cannot post an image to here. You can run it and see the result. Basically it's very similar to what Molly did.

Note that, depending on the version of python you are using, you may need to replace xrange with range

Result of this code

How to install Hibernate Tools in Eclipse?

uncompress the zip HibernateTools-3.2.4.Beta1-R20081031133 later in eclipse --> menu Help -> Update Sofwate -> add site -> local add, and select de folder uncompress an install automatic

What is boilerplate code?

On the etymology the term boilerplate: from http://www.takeourword.com/Issue009.html...

Interestingly, the term arose from the newspaper business. Columns and other pieces that were syndicated were sent out to subscribing newspapers in the form of a mat (i.e. a matrix). Once received, boiling lead was poured into this mat to create the plate used to print the piece, hence the name boilerplate. As the article printed on a boilerplate could not be altered, the term came to be used by attorneys to refer to the portions of a contract which did not change through repeated uses in different applications, and finally to language in general which did not change in any document that was used repeatedly for different occasions.

What constitutes boilerplate in programming? As may others have pointed out, it is just a chunk of code that is copied over and over again with little or no changes made to it in the process.

How do I add records to a DataGridView in VB.Net?

When I try to cast data source from datagridview that used bindingsource it error accor cannot casting:

----------Solution------------

'I changed casting from bindingsource that bind with datagridview

'Code here

Dim dtdata As New DataTable()

dtdata = CType(bndsData.DataSource, DataTable)

What is the intended use-case for git stash?

Stash is just a convenience method. Since branches are so cheap and easy to manage in git, I personally almost always prefer creating a new temporary branch than stashing, but it's a matter of taste mostly.

The one place I do like stashing is if I discover I forgot something in my last commit and have already started working on the next one in the same branch:

# Assume the latest commit was already done
# start working on the next patch, and discovered I was missing something

# stash away the current mess I made
git stash save

# some changes in the working dir

# and now add them to the last commit:
git add -u
git commit --amend

# back to work!
git stash pop

npm notice created a lockfile as package-lock.json. You should commit this file

I had same issue and the solution was to rename name field in package.json (remove white spaces) enter image description here

Horizontal line using HTML/CSS

you could also do it this way, in my case i use it before and after an h1 (brute force it ehehehe)

.titleImage::before {
content: "--------";
letter-spacing: -3px;
}

.titreImage::after {
content: "--------";
letter-spacing: -3px;
}

If the letter spacing makes it so the line get in the text just use a margin to push it away!

C# function to return array

You're trying to return variable Labels of type ArtworkData instead of array, therefore this needs to be in the method signature as its return type. You need to modify your code as such:

public static ArtworkData[] GetDataRecords(int UsersID)
{
    ArtworkData[] Labels;
    Labels = new ArtworkData[3];

    return Labels;
}

Array[] is actually an array of Array, if that makes sense.

Recommended date format for REST GET API

RFC6690 - Constrained RESTful Environments (CoRE) Link Format Does not explicitly state what Date format should be however in section 2. Link Format it points to RFC 3986. This implies that recommendation for date type in RFC 3986 should be used.

Basically RFC 3339 Date and Time on the Internet is the document to look at that says:

date and time format for use in Internet protocols that is a profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar.

what this boils down to : YYYY-MM-ddTHH:mm:ss.ss±hh:mm

(e.g 1937-01-01T12:00:27.87+00:20)

Is the safest bet.

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

How to validate array in Laravel?

You have to loop over the input array and add rules for each input as described here: Loop Over Rules

Here is a some code for ya:

$input = Request::all();
$rules = [];

foreach($input['name'] as $key => $val)
{
    $rules['name.'.$key] = 'required|distinct|min:3';
}

$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';

$validator = Validator::make($input, $rules);

//Now check validation:
if ($validator->fails()) 
{ 
  /* do something */ 
}

Pandas DataFrame concat vs append

Pandas concat vs append vs join vs merge

  • Concat gives the flexibility to join based on the axis( all rows or all columns)

  • Append is the specific case(axis=0, join='outer') of concat

  • Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']

  • Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'

How to fix '.' is not an internal or external command error

Just leave out the "dot-slash" ./:

D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"

Though, if you wanted to, you could use .\ and it would work.

D:\Gesture Recognition\Gesture Recognition\Debug>.\"Gesture Recognition.exe"

Converting a number with comma as decimal point to float

This function is compatible for numbers with dots or commas as decimals

function floatvalue($val){
            $val = str_replace(",",".",$val);
            $val = preg_replace('/\.(?=.*\.)/', '', $val);
            return floatval($val);
}

This works for all kind of inputs (American or european style)

echo floatvalue('1.325.125,54'); // The output is 1325125.54
echo floatvalue('1,325,125.54'); // The output is 1325125.54
echo floatvalue('59,95');        // The output is 59.95
echo floatvalue('12.000,30');    // The output is 12000.30
echo floatvalue('12,000.30');    // The output is 12000.30

How to embed HTML into IPython output?

to do this in a loop, you can do:

display(HTML("".join([f"<a href='{url}'>{url}</a></br>" for url in urls])))

This essentially creates the html text in a loop, and then uses the display(HTML()) construct to display the whole string as HTML

Resolve absolute path from relative path and/or file name

Small improvement to BrainSlugs83's excellent solution. Generalized to allow naming the output environment variable in the call.

@echo off
setlocal EnableDelayedExpansion

rem Example input value.
set RelativePath=doc\build

rem Resolve path.
call :ResolvePath AbsolutePath %RelativePath%

rem Output result.
echo %AbsolutePath%

rem End.
exit /b

rem === Functions ===

rem Resolve path to absolute.
rem Param 1: Name of output variable.
rem Param 2: Path to resolve.
rem Return: Resolved absolute path.
:ResolvePath
    set %1=%~dpfn2
    exit /b

If run from C:\project output is:

C:\project\doc\build

Select top 2 rows in Hive

Yes, here you can use LIMIT.

You can try it by the below query:

SELECT * FROM employee_list SORT BY salary DESC LIMIT 2

How to create threads in nodejs

I needed real multithreading in Node.js and what worked for me was the threads package. It spawns another process having it's own Node.js message loop, so they don't block each other. The setup is easy and the documentation get's you up and running fast. Your main program and the workers can communicate in both ways and worker "threads" can be killed if needed.

Since multithreading and Node.js is a complicated and widely discussed topic it was quite difficult to find a package that works for my specific requirement. For the record these did not work for me:

  • tiny-worker allowed spawning workers, but they seemed to share the same message loop (but it might be I did something wrong - threads had more documentation giving me confidence it really used multiple processes, so I kept going until it worked)
  • webworker-threads didn't allow require-ing modules in workers which I needed

And for those asking why I needed real multi-threading: For an application involving the Raspberry Pi and interrupts. One thread is handling those interrupts and another takes care of storing the data (and more).

Radio buttons not checked in jQuery

This works too. It seems shortest working notation: !$('#selector:checked')

Cannot stop or restart a docker container

Check if there is any zombie process using "top" command.

docker ps | grep <<container name>> 

Get the container id.

ps -ef | grep <<container id>>

ps -ef|grep defunct | grep java

And kill the container by Parent PID .

How to add extra whitespace in PHP?

PHP is an easy language with multiple solutions. A Quick Solution would be using Double Quotes " ". Example Below.

$var1 = "Hello";
$var2 = "World";
$var3 = "How";
$var4 = "are";
$var5 = "you";
$var6 = "?";
$var7 = ",";

echo "$var1 $var2$var7 $var3 $var4 $var5$var6";

//Output: Hello World, How are you?

batch script - run command on each file in directory

I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.

set codedirectory=C:\Users\code
for /r  %codedirectory% %%i in (*.c) do 
( some GCC commands )

Parse an URL in JavaScript

If your string is called s then

var id = s.match(/img_id=([^&]+)/)[1]

will give it to you.

R numbers from 1 to 100

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100))

gives

 -5 100

Instead, look at the : operator to give sequences (with a step size of one):

1:100

or you can use the seq function to have a bit more control. For example,

##Step size of 2
seq(1, 100, by=2)

or

##length.out: desired length of the sequence
seq(1, 100, length.out=5)

Enums in Javascript with ES6

I prefer @tonethar's approach, with a little bit of enhancements and digging for the benefit of understanding better the underlyings of the ES6/Node.js ecosystem. With a background in the server side of the fence, I prefer the approach of functional style around platform's primitives, this minimizes the code bloat, the slippery slope into the state's management valley of the shadow of death due to the introduction of new types and increases the readability - makes more clear the intent of the solution and the algorithm.

Solution with TDD, ES6, Node.js, Lodash, Jest, Babel, ESLint

// ./utils.js
import _ from 'lodash';

const enumOf = (...args) =>
  Object.freeze( Array.from( Object.assign(args) )
    .filter( (item) => _.isString(item))
    .map((item) => Object.freeze(Symbol.for(item))));

const sum = (a, b) => a + b;

export {enumOf, sum};
// ./utils.js

// ./kittens.js
import {enumOf} from "./utils";

const kittens = (()=> {
  const Kittens = enumOf(null, undefined, 'max', 'joe', 13, -13, 'tabby', new 
    Date(), 'tom');
  return () => Kittens;
})();

export default kittens();
// ./kittens.js 

// ./utils.test.js
import _ from 'lodash';
import kittens from './kittens';

test('enum works as expected', () => {
  kittens.forEach((kitten) => {
    // in a typed world, do your type checks...
    expect(_.isSymbol(kitten));

    // no extraction of the wrapped string here ...
    // toString is bound to the receiver's type
    expect(kitten.toString().startsWith('Symbol(')).not.toBe(false);
    expect(String(kitten).startsWith('Symbol(')).not.toBe(false);
    expect(_.isFunction(Object.valueOf(kitten))).not.toBe(false);

    const petGift = 0 === Math.random() % 2 ? kitten.description : 
      Symbol.keyFor(kitten);
    expect(petGift.startsWith('Symbol(')).not.toBe(true);
    console.log(`Unwrapped Christmas kitten pet gift '${petGift}', yeee :) 
    !!!`);
    expect(()=> {kitten.description = 'fff';}).toThrow();
  });
});
// ./utils.test.js

Adding values to Arraylist

Actually, a third is preferred:

ArrayList<Object> array = new ArrayList<Object>();
array.add(Integer.valueOf(3));
array.add("ss");

This avoids autoboxing (Integer.valueOf(3) versus 3) and doesn't create an unnecessary String object.

Eclipse complains when you don't use type arguments with a generic type like ArrayList, because you are using something called a raw type, which is discouraged. If a class is generic (that is, it has type parameters), then you should always use type arguments with that class.

Autoboxing, on the other hand, is a personal preference. Some people are okay with it, and some not. I don't like it, and I turn on the warning for autoboxing/autounboxing.

How to make this Header/Content/Footer layout using CSS?

Here is how to to that:

The header and footer are 30px height.

The footer is stuck to the bottom of the page.

HTML:

<div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>

CSS:

#header {
    height: 30px;
}
#footer {
    height: 30px;
    position: absolute;
    bottom: 0;
}
body {
    height: 100%;
    margin-bottom: 30px;
}

Try it on jsfiddle: http://jsfiddle.net/Usbuw/

Install msi with msiexec in a Specific Directory

This one worked for me too

msiexec /i "msi path" INSTALLDIR="D:\myfolder" /q

I had tried two other iterations and both installed in the default C:\Program Files

INSTALLDIR="D:\myfolder" /q got it installed on the other drive.

$lookup on ObjectId's in an array

2017 update

$lookup can now directly use an array as the local field. $unwind is no longer needed.

Old answer

The $lookup aggregation pipeline stage will not work directly with an array. The main intent of the design is for a "left join" as a "one to many" type of join ( or really a "lookup" ) on the possible related data. But the value is intended to be singular and not an array.

Therefore you must "de-normalise" the content first prior to performing the $lookup operation in order for this to work. And that means using $unwind:

db.orders.aggregate([
    // Unwind the source
    { "$unwind": "$products" },
    // Do the lookup matching
    { "$lookup": {
       "from": "products",
       "localField": "products",
       "foreignField": "_id",
       "as": "productObjects"
    }},
    // Unwind the result arrays ( likely one or none )
    { "$unwind": "$productObjects" },
    // Group back to arrays
    { "$group": {
        "_id": "$_id",
        "products": { "$push": "$products" },
        "productObjects": { "$push": "$productObjects" }
    }}
])

After $lookup matches each array member the result is an array itself, so you $unwind again and $group to $push new arrays for the final result.

Note that any "left join" matches that are not found will create an empty array for the "productObjects" on the given product and thus negate the document for the "product" element when the second $unwind is called.

Though a direct application to an array would be nice, it's just how this currently works by matching a singular value to a possible many.

As $lookup is basically very new, it currently works as would be familiar to those who are familiar with mongoose as a "poor mans version" of the .populate() method offered there. The difference being that $lookup offers "server side" processing of the "join" as opposed to on the client and that some of the "maturity" in $lookup is currently lacking from what .populate() offers ( such as interpolating the lookup directly on an array ).

This is actually an assigned issue for improvement SERVER-22881, so with some luck this would hit the next release or one soon after.

As a design principle, your current structure is neither good or bad, but just subject to overheads when creating any "join". As such, the basic standing principle of MongoDB in inception applies, where if you "can" live with the data "pre-joined" in the one collection, then it is best to do so.

The one other thing that can be said of $lookup as a general principle, is that the intent of the "join" here is to work the other way around than shown here. So rather than keeping the "related ids" of the other documents within the "parent" document, the general principle that works best is where the "related documents" contain a reference to the "parent".

So $lookup can be said to "work best" with a "relation design" that is the reverse of how something like mongoose .populate() performs it's client side joins. By idendifying the "one" within each "many" instead, then you just pull in the related items without needing to $unwind the array first.

What's the difference between Visual Studio Community and other, paid versions?

Check the following: https://www.visualstudio.com/vs/compare/ Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!

tooltips for Button

both <button> tag and <input type="button"> accept a title attribute..