Programs & Examples On #Sigterm

SIGTERM is one of the POSIX mandated signals; it indicates that the process should terminate, which is also the default action for SIGTERM.

Apache server keeps crashing, "caught SIGTERM, shutting down"

SIGTERM is used to restart Apache (provided that it's setup in init to auto-restart): http://httpd.apache.org/docs/2.2/stopping.html

The entries you see in the logs are almost certainly there because your provider used SIGTERM for that purpose. If it's truly crashing, not even serving static content, then that sounds like some sort of a thread/connection exhaustion issue. Perhaps a DoS that holds connections open?

Should definitely be something for your provider to investigate.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.

I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.

https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go

You can do this in a 'defer' fashion.

example for shutting down a server gracefully :

srv := &http.Server{}

go_shutdown_hook.ADD(func() {
    log.Println("shutting down server")
    srv.Shutdown(nil)
    log.Println("shutting down server-done")
})

l, err := net.Listen("tcp", ":3090")

log.Println(srv.Serve(l))

go_shutdown_hook.Wait()

How to process SIGTERM signal gracefully?

First, I'm not certain that you need a second thread to set the shutdown_flag.
Why not set it directly in the SIGTERM handler?

An alternative is to raise an exception from the SIGTERM handler, which will be propagated up the stack. Assuming you've got proper exception handling (e.g. with with/contextmanager and try: ... finally: blocks) this should be a fairly graceful shutdown, similar to if you were to Ctrl+C your program.

Example program signals-test.py:

#!/usr/bin/python

from time import sleep
import signal
import sys


def sigterm_handler(_signo, _stack_frame):
    # Raises SystemExit(0):
    sys.exit(0)

if sys.argv[1] == "handle_signal":
    signal.signal(signal.SIGTERM, sigterm_handler)

try:
    print "Hello"
    i = 0
    while True:
        i += 1
        print "Iteration #%i" % i
        sleep(1)
finally:
    print "Goodbye"

Now see the Ctrl+C behaviour:

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
^CGoodbye
Traceback (most recent call last):
  File "./signals-test.py", line 21, in <module>
    sleep(1)
KeyboardInterrupt
$ echo $?
1

This time I send it SIGTERM after 4 iterations with kill $(ps aux | grep signals-test | awk '/python/ {print $2}'):

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Terminated
$ echo $?
143

This time I enable my custom SIGTERM handler and send it SIGTERM:

$ ./signals-test.py handle_signal
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Goodbye
$ echo $?
0

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

long start = System.currentTimeMillis();
counter.countPrimes(1000000);
long end = System.currentTimeMillis();

System.out.println("Took : " + ((end - start) / 1000));

UPDATE

An even more accurate solution would be:

final long start = System.nanoTime();
counter.countPrimes(1000000);
final long end = System.nanoTime();

System.out.println("Took: " + ((end - start) / 1000000) + "ms");
System.out.println("Took: " + (end - start)/ 1000000000 + " seconds");

Equivalent of Oracle's RowID in SQL Server

ROWID is a hidden column on Oracle tables, so, for SQL Server, build your own. Add a column called ROWID with a default value of NEWID().

How to do that: Add column, with default value, to existing table in SQL Server

Preventing twitter bootstrap carousel from auto sliding on page load

For Bootstrap 4 simply remove the 'data-ride="carousel"' from the carousel div. This removes auto play at load time.

To enable the auto play again you would still have to use the "play" call in javascript.

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).

You can make a session the default as follows:

t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.get_default_session()
    assert t.eval() == sess.run(t)

The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

You state in the comments that the returned JSON is this:

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

You're telling Gson that you have an array of Post objects:

List<Post> postsList = Arrays.asList(gson.fromJson(reader,
                    Post[].class));

You don't. The JSON represents exactly one Post object, and Gson is telling you that.

Change your code to be:

Post post = gson.fromJson(reader, Post.class);

SVG gradient using CSS

Here is how to set a linearGradient on a target element:

<style type="text/css">
    path{fill:url('#MyGradient')}
</style>
<defs>
    <linearGradient id="MyGradient">
        <stop offset="0%" stop-color="#e4e4e3" ></stop>
        <stop offset="80%" stop-color="#fff" ></stop>
    </linearGradient>
</defs>

How to pick element inside iframe using document.getElementById

You need to make sure the frame is fully loaded the best way to do it is to use onload:

<iframe id="nesgt" src="" onload="custom()"></iframe>

function custom(){
    document.getElementById("nesgt").contentWindow.document;
    }

this function will run automatically when the iframe is fully loaded.

it could be done with setTimeout but we can't get the exact time of the frame load.

hope this helps someone.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

This is what then SQL2003 standard (§6.1 Data Types) says about the two:

 <exact numeric type> ::=
    NUMERIC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DECIMAL [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DEC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | SMALLINT
  | INTEGER
  | INT
  | BIGINT

 ...

21) NUMERIC specifies the data type
    exact numeric, with the decimal
    precision and scale specified by the
    <precision> and <scale>.

22) DECIMAL specifies the data type
    exact numeric, with the decimal scale
    specified by the <scale> and the
    implementation-defined decimal
    precision equal to or greater than the
    value of the specified <precision>.

Play/pause HTML 5 video using JQuery

I use FancyBox and jQuery to embedd a video. Give it an ID.

Perhaps not the BEST solution could toggle play/pause differently - but easy for me and IT WORKS! :)

In the

`

<input type="hidden" id="current_video_playing">

<input type="hidden" id="current_video_status" value="playing">

<video id="video-1523" autobuffer="false" src="movie.mp4"></video>

<script>

// Play Pause with spacebar

$(document).keypress(function(e) { 

    theVideo = document.getElementById('current_video_playing').value

    if (e.which == 32) {

        if (document.getElementById('current_video_status').value == 'playing') {

            document.getElementById(theVideo).pause();

            document.getElementById('current_video_status').value = 'paused'

        } else {

            document.getElementById('current_video_status').value = 'playing'

            document.getElementById(theVideo).play();

        }

    }

});

</script>`

Empty set literal?

Yes. The same notation that works for non-empty dict/set works for empty ones.

Notice the difference between non-empty dict and set literals:

{1: 'a', 2: 'b', 3: 'c'} -- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'} -- a tuple of values inside makes a set

So:

{} == zero number of key-value pairs == empty dict
{*()} == empty tuple of values == empty set

However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:

a = set()

Performance:

The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):

>>> %timeit ({*()} & {*()}) | {*()}
214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

>>> %timeit (set() & set()) | set()
252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

... and for completeness, Renato Garcia's frozenset proposal on the above expression is some 60% faster!

>>> ? = frozenset()

>>> %timeit (? & ?) | ?
100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

NB: As ctrueden noticed in comments, {()} is not an empty set. It's a set with 1 element: empty tuple.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.

Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know

If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.

In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:

How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections

Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.

How can I convert an integer to a hexadecimal string in C?

Interesting that these answers utilize printf like it is a given. printf converts the integer to a Hexadecimal string value.

//*************************************************************
// void prntnum(unsigned long n, int base, char sign, char *outbuf)
// unsigned long num = number to be printed
// int base        = number base for conversion;  decimal=10,hex=16
// char sign       = signed or unsigned output
// char *outbuf   = buffer to hold the output number
//*************************************************************

void prntnum(unsigned long n, int base, char sign, char *outbuf)
{

    int i = 12;
    int j = 0;

    do{
        outbuf[i] = "0123456789ABCDEF"[num % base];
        i--;
        n = num/base;
    }while( num > 0);

    if(sign != ' '){
        outbuf[0] = sign;
        ++j;
    }

    while( ++i < 13){
       outbuf[j++] = outbuf[i];
    }

    outbuf[j] = 0;

}

#1292 - Incorrect date value: '0000-00-00'

You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.

Oracle Differences between NVL and Coalesce

Another proof that coalesce() does not stop evaluation with the first non-null value:

SELECT COALESCE(1, my_sequence.nextval) AS answer FROM dual;

Run this, then check my_sequence.currval;

How to build PDF file from binary string returned from a web-service using javascript

I work in PHP and use a function to decode the binary data sent back from the server. I extract the information an input to a simple file.php and view the file through my server and all browser display the pdf artefact.

<?php
   $data = 'dfjhdfjhdfjhdfjhjhdfjhdfjhdfjhdfdfjhdf==blah...blah...blah..'

   $data = base64_decode($data);
    header("Content-type: application/pdf");
    header("Content-Length:" . strlen($data ));
    header("Content-Disposition: inline; filename=label.pdf");
    print $data;
    exit(1);

?>

Run PowerShell command from command prompt (no ps1 script)

Run it on a single command line like so:

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile 
  -WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath> 
  -Recurse -FileType <type>"

Difference between JSON.stringify and JSON.parse

JSON.parse() takes a JSON string and transforms it into a JavaScript object.

JSON.stringify() takes a JavaScript object and transforms it into a JSON string.

const myObj = {
      name: 'bipon',
      age: 25,
      favoriteFood: 'fish curry'
};

 const myObjStr = JSON.stringify(myObj);

console.log(myObjStr);
// "{"name":"bipon","age":26,"favoriteFood":"fish curry"}"

console.log(JSON.parse(myObjStr));
 // Object {name:"bipon",age:26,favoriteFood:"fish curry"}
And although the methods are usually used on objects, they can also be used on arrays:
const myArr = ['simon', 'gomez', 'john'];

const myArrStr = JSON.stringify(myArr);

console.log(myArrStr);
// "["simon","gomez","john"]"

console.log(JSON.parse(myArrStr));
// ["simon","gomez","john"]

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

It means that servlet jar is missing .

check the libraries for your project. Configure your buildpath download **

servlet-api.jar

** and import it in your project.

Attaching click event to a JQuery object not yet added to the DOM

On event

$('#my-button').on('click', function () {
    console.log("yeahhhh!!! but this doesn't work for me :(");
});

Or add the event after append

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

This was the best solution for me, just follow this path C:\Users\yourusername.gradle\wrapper\dists then delete all the files inside this folder. Close your android studio and restart it and it will automatically download the updated gradle files.

Bootstrap modal appearing under background

Check your css to see if you have any blurs and filters. I removed this code from my css and the modal worked normally again

.modal-open .main-wrapper {
    -webkit-filter: blur(1px);
    -moz-filter: blur(1px);
    -o-filter: blur(1px);
    -ms-filter: blur(1px);
    filter: blur(1px);
}

C Programming: How to read the whole file contents into a buffer

Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

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

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.

Changing the sign of a number in PHP?

using alberT and Dan Tao solution:

negative to positive and viceversa

$num = $num <= 0 ? abs($num) : -$num ;

How to check what user php is running as?

You can try using backticks like this:

echo `whoami`;

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

How do I generate a stream from a string?

public Stream GenerateStreamFromString(string s)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(s));
}

How to get pip to work behind a proxy server

At least for pip 1.3.1, it honors the http_proxy and https_proxy environment variables. Make sure you define both, as it will access the PYPI index using https.

export https_proxy="http://<proxy.server>:<port>"
pip install TwitterApi

Changing variable names with Python for loops

Definitely should use a dict using the "group" + str(i) key as described in the accepted solution but I wanted to share a solution using exec. Its a way to parse strings into commands & execute them dynamically. It would allow to create these scalar variable names as per your requirement instead of using a dict. This might help in regards what not to do, and just because you can doesn't mean you should. Its a good solution only if using scalar variables is a hard requirement:

l = locals()
for i in xrange(3):
    exec("group" + str(i) + "= self.getGroup(selected, header + i)")

Another example where this could work using a Django model example. The exec alternative solution is commented out and the better way of handling such a case using the dict attribute makes more sense:

Class A(models.Model):

    ....

    def __getitem__(self, item):  # a.__getitem__('id')
        #exec("attrb = self." + item)
        #return attrb
        return self.__dict__[item]

It might make more sense to extend from a dictionary in the first place to get setattr and getattr functions.

A situation which involves parsing, for example generating & executing python commands dynamically, exec is what you want :) More on exec here.

How to remove all listeners in an element?

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);

If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

forEach is not a function error with JavaScript array

A more naive version, at least you're sure that it'll work on all devices, without conversion and ES6 :

const children = parent.children;
for (var i = 0; i < children.length; i++){
    console.log(children[i]);
}

https://jsfiddle.net/swb12kqn/5/

C++ cout hex values?

I understand this isn't what OP asked for, but I still think it is worth to point out how to do it with printf. I almost always prefer using it over std::cout (even with no previous C background).

printf("%.2X", a);

'2' defines the precision, 'X' or 'x' defines case.

Does Java have something like C#'s ref and out keywords?

Like many others, I needed to convert a C# project to Java. I did not find a complete solution on the web regarding out and ref modifiers. But, I was able to take the information I found, and expand upon it to create my own classes to fulfill the requirements. I wanted to make a distinction between ref and out parameters for code clarity. With the below classes, it is possible. May this information save others time and effort.

An example is included in the code below.

//*******************************************************************************************
//XOUT CLASS
//*******************************************************************************************
public class XOUT<T>
{
    public XOBJ<T> Obj = null;

    public XOUT(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XOUT()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(this);
    }

    public XREF<T> Ref()
    {
        return(Obj.Ref());
    }
};

//*******************************************************************************************
//XREF CLASS
//*******************************************************************************************

public class XREF<T>
{
    public XOBJ<T> Obj = null;

    public XREF(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XREF()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(Obj.Out());
    }

    public XREF<T> Ref()
    {
        return(this);
    }
};

//*******************************************************************************************
//XOBJ CLASS
//*******************************************************************************************
/**
 *
 * @author jsimms
 */
/*
    XOBJ is the base object that houses the value. XREF and XOUT are classes that
    internally use XOBJ. The classes XOBJ, XREF, and XOUT have methods that allow
    the object to be used as XREF or XOUT parameter; This is important, because
    objects of these types are interchangeable.

    See Method:
       XXX.Ref()
       XXX.Out()

    The below example shows how to use XOBJ, XREF, and XOUT;
    //
    // Reference parameter example
    //
    void AddToTotal(int a, XREF<Integer> Total)
    {
       Total.Obj.Value += a;
    }

    //
    // out parameter example
    //
    void Add(int a, int b, XOUT<Integer> ParmOut)
    {
       ParmOut.Obj.Value = a+b;
    }

    //
    // XOBJ example
    //
    int XObjTest()
    {
       XOBJ<Integer> Total = new XOBJ<>(0);
       Add(1, 2, Total.Out());    // Example of using out parameter
       AddToTotal(1,Total.Ref()); // Example of using ref parameter
       return(Total.Value);
    }
*/


public class XOBJ<T> {

    public T Value;

    public  XOBJ() {

    }

    public XOBJ(T value) {
        this.Value = value;
    }

    //
    // Method: Ref()
    // Purpose: returns a Reference Parameter object using the XOBJ value
    //
    public XREF<T> Ref()
    {
        XREF<T> ref = new XREF<T>();
        ref.Obj = this;
        return(ref);
    }

    //
    // Method: Out()
    // Purpose: returns an Out Parameter Object using the XOBJ value
    //
    public XOUT<T> Out()
    {
        XOUT<T> out = new XOUT<T>();
        out.Obj = this;
        return(out);
    }

    //
    // Method get()
    // Purpose: returns the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public T get() {
        return Value;
    }

    //
    // Method get()
    // Purpose: sets the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public void set(T anotherValue) {
        Value = anotherValue;
    }

    @Override
    public String toString() {
        return Value.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return Value.equals(obj);
    }

    @Override
    public int hashCode() {
        return Value.hashCode();
    }
}

How to count occurrences of a column value efficiently in SQL?

select s.id, s.age, c.count
from students s
inner join (
    select age, count(*) as count
    from students
    group by age
) c on s.age = c.age
order by id

Getting today's date in YYYY-MM-DD in Python?

You can use,

>>> from datetime import date
>>> date.today().__str__()
'2019-10-05'

ngrok command not found

Windows:

  1. Extract.
  2. Open folder
  3. Right click Windows Powershell.
  4. ngrock http 5000 {your post number instead of 5000}
  5. Make sure local server is running on another cmd too.

//Do not worry about auth step

How to get a list of all files that changed between two Git commits?

If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type

git status -- it will show the files with changes

then if you want to know what changes are to be made it can be checked in ways ,

git diff -- will show all the changes in all files

it is good only when only one file is modified

and if you want to check particular file then use

git diff

How do I make a Docker container start automatically on system boot?

More "gentle" mode from the documentation:

docker run -dit --restart unless-stopped <image_name>

Putty: Getting Server refused our key Error

In the case of mine it was a wrong user:group attribution. I solved setting the right user and group:

sudo chown [user]:[group] -R /home/[user]

jQuery get content between <div> tags

Use the below where x is the variable which holds the markup in question.

$(x).find("div").html();

PuTTY scripting to log onto host

For me it works this way:

putty -ssh [email protected] 22 -pw password

putty, protocol, user name @ ip address port and password. To connect in less than a second.

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

How can I see an the output of my C programs using Dev-C++?

Use #include conio.h

Then add getch(); before return 0;

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

To answer your question

In Sql Server joins syntax OUTER is optional

It is mentioned in msdn article : https://msdn.microsoft.com/en-us/library/ms177634(v=sql.130).aspx

So following list shows join equivalent syntaxes with and without OUTER

LEFT OUTER JOIN => LEFT JOIN
RIGHT OUTER JOIN => RIGHT JOIN
FULL OUTER JOIN => FULL JOIN

Other equivalent syntaxes

INNER JOIN => JOIN
CROSS JOIN => ,

Strongly Recommend Dotnet Mob Artice : Joins in Sql Server enter image description here

key_load_public: invalid format

There is a simple solution if you can install and use puttygen tool. Below are the steps. You should have the passphrase of the private key.

step 1: Download latest puttygen and open puttygen

step 2: Load your existing private key file, see below image

Load an existing private key

step 3: Enter passphrase for key if asked and hit ok

enter paasphrase

step 4: as shown in the below image select "conversion" menu tab and select "Export OpenSSH key"

save OpenSSH file

Save new private key file at preferred location and use accordingly.

Java ArrayList of Doubles

Try this:

 List<Double> l1= new ArrayList<Double>();
 l1.add(1.38);
 l1.add(2.56);
 l1.add(4.3);

Remove all occurrences of char from string

package com.acn.demo.action;

public class RemoveCharFromString {

    static String input = "";
    public static void main(String[] args) {
        input = "abadbbeb34erterb";
        char token = 'b';
        removeChar(token);
    }

    private static void removeChar(char token) {
        // TODO Auto-generated method stub
        System.out.println(input);
        for (int i=0;i<input.length();i++) {
            if (input.charAt(i) == token) {
            input = input.replace(input.charAt(i), ' ');
                System.out.println("MATCH FOUND");
            }
            input = input.replaceAll(" ", "");
            System.out.println(input);
        }
    }
}

Simple way to count character occurrences in a string

Functional style (Java 8, just for fun):

str.chars().filter(num -> num == '$').count()

How do I pass the this context to a function?

Javascripts .call() and .apply() methods allow you to set the context for a function.

var myfunc = function(){
    alert(this.name);
};

var obj_a = {
    name:  "FOO"
};

var obj_b = {
    name:  "BAR!!"
};

Now you can call:

myfunc.call(obj_a);

Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);

Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

var _css = $.fn.css;
$.fn.css = function(){
   alert('hooked!');
   _css.apply(this, arguments);
};

Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

if your node_modules got installed in say /home/UserName/ like in my case, your package-lock.json file will also be there. just delete this file, go back to your app folder and run npm init and then npm install <pkgname> (e.g express) and a new node_modules folder will be created for your.

Installing a plain plugin jar in Eclipse 3.5

Since the advent of p2, you should be using the dropins directory instead.

To be completely clear create "plugins" under "/dropins" and make sure to restart eclipse with the "-clean" option.

Granting Rights on Stored Procedure to another user of Oracle

On your DBA account, give USERB the right to create a procedure using grant grant create any procedure to USERB

The procedure will look

CREATE OR REPLACE PROCEDURE USERB.USERB_PROCEDURE
--Must add the line below
AUTHID CURRENT_USER AS
  BEGIN
  --DO SOMETHING HERE
  END
END

GRANT EXECUTE ON USERB.USERB_PROCEDURE TO USERA

I know this is a very old question but I am hoping I could chip it a bit.

jquery - Click event not working for dynamically created button

My guess is that the buttons you created are not yet on the page by the time you bind the button. Either bind each button in the $.getJSON function, or use a dynamic binding method like:

$('body').on('click', 'button', function() {
    ...
});

Note you probably don't want to do this on the 'body' tag, but instead wrap the buttons in another div or something and call on on it.

jQuery On Method

Toggle button using two image on different state

Do this:

<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   <!--check.xml-->
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

create check.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>

Should I use "camel case" or underscores in python?

for everything related to Python's style guide: i'd recommend you read PEP8.

To answer your question:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Start script missing error when running npm start

It looks like you might not have defined a start script in your package.json file or your project does not contain a server.js file.

If there is a server.js file in the root of your package, then npm will default the start command to node server.js.

https://docs.npmjs.com/misc/scripts#default-values

You could either change the name of your application script to server.js or add the following to your package.json

"scripts": {
    "start": "node your-script.js"
}

Or ... you could just run node your-script.js directly

JavaScript hard refresh of current page

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

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

I faced this issue when I tried to checkout using specific tag but the tag value was incorrect. Here's an example how easy it can be:

[email protected]:user/reponame?ref=1.0.0

this was incorrect and below is the correct one (note v before the version name):

[email protected]:user/reponame?ref=v1.0.0

If you're not familiar with all those tiny details it's really easy to omit them.

Node/Express file upload

I find this, simple and efficient:

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

// default options
app.use(fileUpload());

app.post('/upload', function(req, res) {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }

  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
  let sampleFile = req.files.sampleFile;

  // Use the mv() method to place the file somewhere on your server
  sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});

express-fileupload

MomentJS getting JavaScript Date in UTC

Or simply:

Date.now

From MDN documentation:

The Date.now() method returns the number of milliseconds elapsed since January 1, 1970

Available since ECMAScript 5.1

It's the same as was mentioned above (new Date().getTime()), but more shortcutted version.

Dynamic instantiation from string name of a class in dynamically imported module?

tl;dr

Import the root module with importlib.import_module and load the class by its name using getattr function:

# Standard import
import importlib
# Load "module.submodule.MyClass"
MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
# Instantiate the class (pass arguments to the constructor, if needed)
instance = MyClass()

explanations

You probably don't want to use __import__ to dynamically import a module by name, as it does not allow you to import submodules:

>>> mod = __import__("os.path")
>>> mod.join
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'join'

Here is what the python doc says about __import__:

Note: This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().

Instead, use the standard importlib module to dynamically import a module by name. With getattr you can then instantiate a class by its name:

import importlib
my_module = importlib.import_module("module.submodule")
MyClass = getattr(my_module, "MyClass")
instance = MyClass()

You could also write:

import importlib
module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
MyClass = getattr(importlib.import_module(module_name), class_name)
instance = MyClass()

This code is valid in python = 2.7 (including python 3).

Git credential helper - update password

If you are a Windows user, you may either remove or update your credentials in Credential Manager.

In Windows 10, go to the below path:

Control PanelAll Control Panel ItemsCredential Manager

Or search for "credential manager" in your "Search Windows" section in the Start menu.

Then from the Credential Manager, select "Windows Credentials".

Credential Manager will show many items including your outlook and GitHub repository under "Generic credentials"

You click on the drop down arrow on the right side of your Git: and it will show options to edit and remove. If you remove, the credential popup will come next time when you fetch or pull. Or you can directly edit the credentials there.

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

Checking if float is an integer

stdlib float modf (float x, float *ipart) splits into two parts, check if return value (fractional part) == 0.

Comparing two dataframes and getting the differences

# given
df1=pd.DataFrame({'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24'],
    'Fruit':['Banana','Orange','Apple','Celery'],
    'Num':[22.1,8.6,7.6,10.2],
    'Color':['Yellow','Orange','Green','Green']})
df2=pd.DataFrame({'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24','2013-11-25','2013-11-25'],
    'Fruit':['Banana','Orange','Apple','Celery','Apple','Orange'],
    'Num':[22.1,8.6,7.6,1000,22.1,8.6],
    'Color':['Yellow','Orange','Green','Green','Red','Orange']})

# find which rows are in df2 that aren't in df1 by Date and Fruit
df_2notin1 = df2[~(df2['Date'].isin(df1['Date']) & df2['Fruit'].isin(df1['Fruit']) )].dropna().reset_index(drop=True)

# output
print('df_2notin1\n', df_2notin1)
#      Color        Date   Fruit   Num
# 0     Red  2013-11-25   Apple  22.1
# 1  Orange  2013-11-25  Orange   8.6

Compute row average in pandas

If you are looking to average column wise. Try this,

df.drop('Region', axis=1).apply(lambda x: x.mean())

# it drops the Region column
df.drop('Region', axis=1,inplace=True)

How to stop flask application without using ctrl-c

For Windows, it is quite easy to stop/kill flask server -

  1. Goto Task Manager
  2. Find flask.exe
  3. Select and End process

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

C# int to byte[]

BitConverter.GetBytes(int) almost does what you want, except the endianness is wrong.

You can use the IPAddress.HostToNetwork method to swap the bytes within the the integer value before using BitConverter.GetBytes or use Jon Skeet's EndianBitConverter class. Both methods do the right thing(tm) regarding portability.

int value;
byte[] bytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value));

How to verify if a file exists in a batch file?

You can use IF EXIST to check for a file:

IF EXIST "filename" (
  REM Do one thing
) ELSE (
  REM Do another thing
)

If you do not need an "else", you can do something like this:

set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=

Here's a working example of searching for a file or a folder:

REM setup

echo "some text" > filename
mkdir "foldername"

REM finds file    

IF EXIST "filename" (
  ECHO file filename exists
) ELSE (
  ECHO file filename does not exist
)

REM does not find file

IF EXIST "filename2.txt" (
  ECHO file filename2.txt exists
) ELSE (
  ECHO file filename2.txt does not exist
)

REM folders must have a trailing backslash    

REM finds folder

IF EXIST "foldername\" (
  ECHO folder foldername exists
) ELSE (
  ECHO folder foldername does not exist
)

REM does not find folder

IF EXIST "filename\" (
  ECHO folder filename exists
) ELSE (
  ECHO folder filename does not exist
)

Testing pointers for validity (C/C++)

Setting the pointer to NULL before and after using is a good technique. This is easy to do in C++ if you manage pointers within a class for example (a string):

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();

    void SetText( const char *text);
    char *GetText() const { return MyText; }
    void Clear();

private:
    char * MyText;
};


SomeClass::SomeClass()
{
    MyText = NULL;
}


SomeClass::~SomeClass()
{
    Clear();
}

void SomeClass::Clear()
{
    if (MyText)
        free( MyText);

    MyText = NULL;
}



void SomeClass::Settext( const char *text)
{
    Clear();

    MyText = malloc( strlen(text));

    if (MyText)
        strcpy( MyText, text);
}

html form - make inputs appear on the same line

Try just putting a div around the first and last name inputs/labels like this:

<div class="name">
        <label for="First_Name">First Name:</label>
        <input name="first_name" id="First_Name" type="text" />

        <label for="Name">Last Name:</label>
        <input name="last_name" id="Last_Name" type="text" /> 
</div>

Look at the fiddle here: http://jsfiddle.net/XAkXg/

Can we pass parameters to a view in SQL?

Here is an option I have not seen so far:

Just add the column you want to restrict on to the view:

create view emp_v as (
select emp_name, emp_id from emp;
)

select emp_v.emp_name from emp_v
where emp_v.emp_id = (id to restrict by)

C# : 'is' keyword and checking for Not

While the IS operator is normally the best way, there is an alternative that you can use in some cirumstances. You can use the as operator and test for null.

MyClass mc = foo as MyClass;
if ( mc == null ) { }
else {}

One time page refresh after first page load

use window.localStorage... like this

var refresh = $window.localStorage.getItem('refresh');
console.log(refresh);
if (refresh===null){
    window.location.reload();
    $window.localStorage.setItem('refresh', "1");
}

It's work for me

Downgrade npm to an older version

Just need to add version of which you want

upgrade or downgrade

npm install -g npm@version

Example if you want to downgrade from npm 5.6.0 to 4.6.1 then,

npm install -g [email protected]

It is tested on linux

How to get ID of clicked element with jQuery

Your id will be passed through as #1, #2 etc. However, # is not valid as an ID (CSS selectors prefix IDs with #).

Mean of a column in a data frame, given the column's name

Use summarise in the dplyr package:

library(dplyr)
summarise(df, Average = mean(col_name, na.rm = T))

note: dplyr supports both summarise and summarize.

Extract the last substring from a cell

Right(A1, Len(A1)-Find("(asterisk)",Substitute(A1, "(space)","(asterisk)",Len(A1)-Len(Substitute(A1,"(space)", "(no space)")))))

Try this. Hope it works.

How to reduce the image size without losing quality in PHP

If you are looking to reduce the size using coding itself, you can follow this code in php.

<?php 
function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);

    return $destination;
}

$source_img = 'source.jpg';
$destination_img = 'destination .jpg';

$d = compress($source_img, $destination_img, 90);
?>

$d = compress($source_img, $destination_img, 90);

This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source);

The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.

Fix columns in horizontal scrolling

SOLVED

http://jsfiddle.net/DJqPf/7/

.table-wrapper { 
    overflow-x:scroll;
    overflow-y:visible;
    width:250px;
    margin-left: 120px;
}
td, th {
    padding: 5px 20px;
    width: 100px;
}
th:first-child {
    position: fixed;
    left: 5px
}

UPDATE

_x000D_
_x000D_
$(function () {  _x000D_
  $('.table-wrapper tr').each(function () {_x000D_
    var tr = $(this),_x000D_
        h = 0;_x000D_
    tr.children().each(function () {_x000D_
      var td = $(this),_x000D_
          tdh = td.height();_x000D_
      if (tdh > h) h = tdh;_x000D_
    });_x000D_
    tr.css({height: h + 'px'});_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
    position: relative;_x000D_
}_x000D_
.table-wrapper { _x000D_
    overflow-x:scroll;_x000D_
    overflow-y:visible;_x000D_
    width:200px;_x000D_
    margin-left: 120px;_x000D_
}_x000D_
_x000D_
_x000D_
td, th {_x000D_
    padding: 5px 20px;_x000D_
    width: 100px;_x000D_
}_x000D_
tbody tr {_x000D_
  _x000D_
}_x000D_
th:first-child {_x000D_
    position: absolute;_x000D_
    left: 5px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
    <h1>SOME RANDOM TEXT</h1>_x000D_
</div>_x000D_
<div class="table-wrapper">_x000D_
    <table id="consumption-data" class="data">_x000D_
        <thead class="header">_x000D_
            <tr>_x000D_
                <th>Month</th>_x000D_
                <th>Item 1</th>_x000D_
                <th>Item 2</th>_x000D_
                <th>Item 3</th>_x000D_
                <th>Item 4</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody class="results">_x000D_
            <tr>_x000D_
                <th>Jan is an awesome month</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Feb</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Mar</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Apr</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>  _x000D_
            </tr>_x000D_
            <tr>    _x000D_
                <th>May</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Jun</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
_x000D_
            <tr>_x000D_
                <th>...</th>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

1. Open project level build.gradle

Update com.google.gms:google-services version to latest. Track latest release. At the time of answer latest is 4.1.0.

2. Open app level build.gradle

Update below dependency if you use any. Note that firebase has individual versions for every dependency now.

Use latest Firebase Libraries. At the time of answer latest versions are below.

Firebase Core                com.google.firebase:firebase-core:16.0.3
Ads                          com.google.firebase:firebase-ads:15.0.1
Analytics                    com.google.firebase:firebase-analytics:16.0.3
App Indexing                 com.google.firebase:firebase-appindexing:16.0.1
Authentication               com.google.firebase:firebase-auth:16.0.3
Cloud Firestore              com.google.firebase:firebase-firestore:17.1.0
Cloud Functions              com.google.firebase:firebase-functions:16.1.0
Cloud Messaging              com.google.firebase:firebase-messaging:17.3.2
Cloud Storage   c            om.google.firebase:firebase-storage:16.0.2
Crash Reporting              com.google.firebase:firebase-crash:16.2.0
Crashlytics                  com.crashlytics.sdk.android:crashlytics:2.9.5
Dynamic Links                com.google.firebase:firebase-dynamic-links:16.1.1
Invites                      com.google.firebase:firebase-invites:16.0.3
In-App Messaging             com.google.firebase:firebase-inappmessaging:17.0.1
In-App Messaging Display     com.google.firebase:firebase-inappmessaging-display:17.0.1
ML Kit: Model Interpreter    com.google.firebase:firebase-ml-model-interpreter:16.2.0
ML Kit: Vision               com.google.firebase:firebase-ml-vision:17.0.0
ML Kit: Image Labeling       com.google.firebase:firebase-ml-vision-image-label-model:15.0.0
Performance Monitoring       com.google.firebase:firebase-perf:16.1.0
Realtime Database            com.google.firebase:firebase-database:16.0.2
Remote Config                com.google.firebase:firebase-config:16.0.0

Sync and Build...

Node.js + Nginx - What now?

I proxy independent Node Express applications through Nginx.

Thus new applications can be easily mounted and I can also run other stuff on the same server at different locations.

Here are more details on my setup with Nginx configuration example:

Deploy multiple Node applications on one web server in subfolders with Nginx

Things get tricky with Node when you need to move your application from from localhost to the internet.

There is no common approach for Node deployment.

Google can find tons of articles on this topic, but I was struggling to find the proper solution for the setup I need.

Basically, I have a web server and I want Node applications to be mounted to subfolders (i.e. http://myhost/demo/pet-project/) without introducing any configuration dependency to the application code.

At the same time I want other stuff like blog to run on the same web server.

Sounds simple huh? Apparently not.

In many examples on the web Node applications either run on port 80 or proxied by Nginx to the root.

Even though both approaches are valid for certain use cases, they do not meet my simple yet a little bit exotic criteria.

That is why I created my own Nginx configuration and here is an extract:

upstream pet_project {
  server localhost:3000;
}

server {
  listen 80;
  listen [::]:80;
  server_name frontend;

  location /demo/pet-project {
    alias /opt/demo/pet-project/public/;
    try_files $uri $uri/ @pet-project;
  }

  location @pet-project {
    rewrite /demo/pet-project(.*) $1 break;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $proxy_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://pet_project;
    proxy_redirect http://pet_project/ /demo/pet-project/;
  }
}

From this example you can notice that I mount my Pet Project Node application running on port 3000 to http://myhost/demo/pet-project.

First Nginx checks if whether the requested resource is a static file available at /opt/demo/pet-project/public/ and if so it serves it as is that is highly efficient, so we do not need to have a redundant layer like Connect static middleware.

Then all other requests are overwritten and proxied to Pet Project Node application, so the Node application does not need to know where it is actually mounted and thus can be moved anywhere purely by configuration.

proxy_redirect is a must to handle Location header properly. This is extremely important if you use res.redirect() in your Node application.

You can easily replicate this setup for multiple Node applications running on different ports and add more location handlers for other purposes.

From: http://skovalyov.blogspot.dk/2012/07/deploy-multiple-node-applications-on.html

Is there an equivalent for var_dump (PHP) in Javascript?

console.log(OBJECT|ARRAY|STRING|...);
console.info(OBJECT|ARRAY|STRING|...);
console.debug(OBJECT|ARRAY|STRING|...);
console.warn(OBJECT|ARRAY|STRING|...);
console.assert(Condition, 'Message if false');

These Should work correctly On Google Chrome and Mozilla Firefox (if you are running with old version of firefox, so you have to install Firebug plugin)
On Internet Explorer 8 or higher you must do as follow:

  • Launch "Developer Tools, by clicking on F12 Button
  • On the Tab List, click on "Script" Tab"
  • Click on "Console" Button in the right side

For more informations you can visit this URL: https://developer.chrome.com/devtools/docs/console-api

How do I count occurrence of duplicate items in array

Count duplicate element of an array in PHP without using in-built function

$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
        for($i=0;$i<$arrlength-1;$i++)
        {
          $key=$arraychars[$i];
          if($arrCount[$key]>=1)
            {
              $arrCount[$key]++;
            } else{
              $arrCount[$key]=1;
        }
        echo $arraychars[$i]."<br>";
     }
        echo "<pre>";
        print_r($arrCount);

How can I recover a lost commit in Git?

Before answering, let's add some background, explaining what this HEAD is.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time (excluding git worktree).

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history it's called detached HEAD.

Enter image description here

On the command line, it will look like this - SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch:

Enter image description here

Enter image description here


A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# Create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

Enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7) you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there, reset && checkout modify the HEAD.

Enter image description here

using wildcards in LDAP search filters/queries

Your best bet would be to anticipate prefixes, so:

"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"

Clunky, but I'm doing a similar thing within my organization.

How can I convert NSDictionary to NSData and vice versa?

Use NSJSONSerialization:

NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
                                                             options:NSJSONReadingAllowFragments
                                                               error:&error];

The latest returns id, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).

Single line if statement with 2 actions

userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

This problem is generally caused by the website/intranet URL being placed in one of:

  • Compatibility Mode List
  • Internet Explorer Intranet Zone
    (with Display intranet sites in Compatibility View setting enabled)
  • Enterprise Mode List

On corporate networks, these compatibility view settings are often controlled centrally via group policy. In your case, Enterprise Mode appears to be the culprit.

IE 11 Enterprise Mode

Unfortunately setting META X-UA-Compatible will not override this.

For End-Users

Sometimes the only way for end-users to override this is to press F12 and change the Document Mode under the Emulation Tab. However this setting is not permanent and may revert once Developer Tools is closed.

You can also try to exclude your site from the Intranet zone. But the list of domains which belong to the Intranet zone is usually also controlled by the group policy, so the chance of this working is slim.

To see the list of domains that belong to the Intranet zone, go to:

Tools -> Internet Options -> Security -> Sites -> Advanced

If the list contains your subdomain and is greyed out, then you will not be able to override compatibility view until your network admin allows it.

You really need to contact your network administrator to allow changing the compatibility view settings in the group policy.

For Network Admins

Loading the website with Developer Tools open (F12) will often report the reason that IE is switching to an older mode.

All 3 settings mentioned above are generally controlled via Group Policy, although can sometimes be overridden on user machines.

If Enterprise Mode is the issue (as appears to be the case for the original poster), the following two articles might be helpful:

Remote debugging Tomcat with Eclipse

First of all, if you open catalina.bat with text editor, you see that: "Do not set the variables in this script....." So never change it in that script, instead you can do below steps:

  1. It advices you to create a new bat file with name "setenv.bat".
  2. Then set 2 variables in that bat file such as:

    set CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

    set JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

  3. Lastly run that at cmd that: "catalina.bat jpda start"

  4. In IDE, create remote debug configuration and set host to related server ip and port to 8000.

Set default heap size in Windows

Setup JAVA_OPTS as a system variable with the following content:

JAVA_OPTS="-Xms256m -Xmx512m"

After that in a command prompt run the following commands:

SET JAVA_OPTS="-Xms256m -Xmx512m"

This can be explained as follows:

  • allocate at minimum 256MBs of heap
  • allocate at maximum 512MBs of heap

These values should be changed according to application requirements.

EDIT:

You can also try adding it through the Environment Properties menu which can be found at:

  1. From the Desktop, right-click My Computer and click Properties.
  2. Click Advanced System Settings link in the left column.
  3. In the System Properties window click the Environment Variables button.
  4. Click New to add a new variable name and value.
  5. For variable name enter JAVA_OPTS for variable value enter -Xms256m -Xmx512m
  6. Click ok and close the System Properties Tab.
  7. Restart any java applications.

EDIT 2:

JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.

To setup a system variable you have to complete the steps listed above from 1 to 4.

Access HTTP response as string in Go

bs := string(body) should be enough to give you a string.

From there, you can use it as a regular string.

A bit as in this thread:

var client http.Client
resp, err := client.Get(url)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusOK {
    bodyBytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    bodyString := string(bodyBytes)
    log.Info(bodyString)
}

See also GoByExample.

As commented below (and in zzn's answer), this is a conversion (see spec).
See "How expensive is []byte(string)?" (reverse problem, but the same conclusion apply) where zzzz mentioned:

Some conversions are the same as a cast, like uint(myIntvar), which just reinterprets the bits in place.

Sonia adds:

Making a string out of a byte slice, definitely involves allocating the string on the heap. The immutability property forces this.
Sometimes you can optimize by doing as much work as possible with []byte and then creating a string at the end. The bytes.Buffer type is often useful.

What is `related_name` used for in Django?

To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material

@with_author 
class BOM(models.Model): 
    name = models.CharField(max_length=200,null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tomaterial =  models.ForeignKey(Material, related_name = 'tomaterial')
    frommaterial =  models.ForeignKey(Material, related_name = 'frommaterial')
    creation_time = models.DateTimeField(auto_now_add=True, blank=True)
    quantity = models.DecimalField(max_digits=19, decimal_places=10)

So when you will have to access this data you only can use related name

 bom = material.tomaterial.all().order_by('-creation_time')

It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)

How can I draw vertical text with CSS cross-browser?

I adapted this from http://snook.ca/archives/html_and_css/css-text-rotation :

<style>
    .Rotate-90
    {
        display: block;
        position: absolute;
        right: -5px;
        top: 15px;
        -webkit-transform: rotate(-90deg);
        -moz-transform: rotate(-90deg);
    }
</style>
<!--[if IE]>
    <style>
        .Rotate-90 {
            filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
            right:-15px; top:5px;
        }
    </style>
    <![endif]-->

How to maintain a Unique List in Java?

Use new HashSet<String> An example:

import java.util.HashSet;
import java.util.Set;

public class MainClass {
  public static void main(String args[]) {
    String[] name1 = { "Amy", "Jose", "Jeremy", "Alice", "Patrick" };

    String[] name2 = { "Alan", "Amy", "Jeremy", "Helen", "Alexi" };

    String[] name3 = { "Adel", "Aaron", "Amy", "James", "Alice" };

    Set<String> letter = new HashSet<String>();

    for (int i = 0; i < name1.length; i++)
      letter.add(name1[i]);

    for (int j = 0; j < name2.length; j++)
      letter.add(name2[j]);

    for (int k = 0; k < name3.length; k++)
      letter.add(name3[k]);

    System.out.println(letter.size() + " letters must be sent to: " + letter);

  }
}

Android AlertDialog Single Button

Alert Dialog

alert dialog with a single button.

alert dialog with an icon.

alert dialog with three-button.

alert dialog with a choice option, radio button.

alert dialog with the multi-choice option, checkbox button.

<resources>
    <string name="app_name">Alert Dialog</string>

    <string name="info_dialog">Info Dialog</string>
    <string name="icon_dialog">Icon Dialog</string>
    <string name="rate_dialog">Rate Dialog</string>
    <string name="singleOption_dialog">Single Options Dialog</string>
    <string name="multiOption_dialog">Multi Options Dialog</string>

    <string-array name="fruit_name">
        <item>Apple</item>
        <item>Banana</item>
        <item>Orange</item>
        <item>Grapes</item>
        <item>Watermelon</item>
        <item>Nothing</item>
    </string-array>
</resources>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/info_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/info_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />

    <Button
        android:id="@+id/icon_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/icon_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />

    <Button
        android:id="@+id/rate_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/rate_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />

    <Button
        android:id="@+id/single_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/singleOption_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />

    <Button
        android:id="@+id/multi_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/multiOption_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />
</LinearLayout>

public class MainActivity extends AppCompatActivity {

    String select;
    String[] fruitNames;
    Button infoDialog, iconDialog, rateDialog, singleOptionDialog, multiOptionDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        infoDialog = findViewById(R.id.info_dialog);
        rateDialog = findViewById(R.id.rate_dialog);
        iconDialog = findViewById(R.id.icon_dialog);
        singleOptionDialog = findViewById(R.id.single_dialog);
        multiOptionDialog = findViewById(R.id.multi_dialog);
        infoDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                infoDialog();
            }
        });
        rateDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ratingDialog();
            }
        });
        iconDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iconDialog();
            }
        });
        singleOptionDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SingleSelectionDialog();
            }
        });
        multiOptionDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MultipleSelectionDialog();
            }
        });
    }

    /*Display information dialog*/
    private void infoDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Info");
        dialogBuilder.setMessage("Some informative message for the user to do that.");
        dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    /*Display rating dialog*/
    private void ratingDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Rate Us");
        dialogBuilder.setMessage("If you liked it, please rate it. It will help us grow.");
        dialogBuilder.setPositiveButton("Rate", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.setNegativeButton("Leave it", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.setNeutralButton("May be, later", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    /*Dialog with icons*/
    private void iconDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Info");
        dialogBuilder.setIcon(R.mipmap.ic_launcher_round);
        dialogBuilder.setMessage("You know, you could have provided some valuable message here!");
        dialogBuilder.setPositiveButton("Got it", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    /*Dialog to select single option*/
    private void SingleSelectionDialog() {
        fruitNames = getResources().getStringArray(R.array.fruit_name);
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
        dialogBuilder.setTitle("Which fruit you want to eat?");
        dialogBuilder.setSingleChoiceItems(fruitNames, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //Toast.makeText(MainActivity.this, checkedItem, Toast.LENGTH_SHORT).show();
                select = fruitNames[i];
            }
        });
        dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Item selected: " + select, Toast.LENGTH_SHORT).show();
            }
        });
        dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Cancel", Toast.LENGTH_SHORT).show();
            }
        });
        dialogBuilder.create().show();
    }

    /*Dialog to select multiple options*/
    public void MultipleSelectionDialog() {
        final String[] items = {"Apple", "Banana", "Orange", "Grapes", "Watermelon"};
        final ArrayList<Integer> selectedList = new ArrayList<>();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choice multi item fruit list");
        builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                if (isChecked) {
                    selectedList.add(which);
                } else if (selectedList.contains(which)) {
                    selectedList.remove(which);
                }
            }
        });
        builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ArrayList<String> selectedStrings = new ArrayList<>();
                for (int j = 0; j < selectedList.size(); j++) {
                    selectedStrings.add(items[selectedList.get(j)]);
                }
                Toast.makeText(getApplicationContext(), "Items selected: " + Arrays.toString(selectedStrings.toArray()), Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
    }
}

enter image description here

What does "restore purchases" in In-App purchases mean?

You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.

for other type of products it will automatically restore it.

Please read following text which will clear your concept about this :

Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.

Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.

If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:

iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

so that the entry is UNchecked then the software keyboard will be displayed once again.

how do I get eclipse to use a different compiler version for Java?

Eclipse uses it's own internal compiler that can compile to several Java versions.

From Eclipse Help > Java development user guide > Concepts > Java Builder

The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.

For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.

When you configure a project:

[project-name] > Properties > Java Compiler > Compiler compliance level

This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.

Host environment variables, eg JAVA_HOME etc, are not used.

The Oracle/Sun JDK compiler is not used.

How to toggle font awesome icon on click?

Simply call jQuery's toggleClass() on the i element contained within your a element(s) to toggle either the plus and minus icons:

...click(function() {
    $(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});

Note that this assumes that a class of fa-plus-circle is added to your i element by default.

JSFiddle demo.

How to center canvas in html5

Using grid?

_x000D_
_x000D_
const canvas = document.querySelector('canvas'); 
const ctx = canvas.getContext('2d'); 
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
_x000D_
body, html {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
    background-color: black;
}

body {
    display: grid;
    grid-template-rows: auto;
    justify-items: center;
    align-items: center;
}

canvas {
  height: 80vh; 
  width: 80vw; 
  display: block;
}
_x000D_
<html>
  <body>
        <canvas></canvas>
  </body>
</html>
_x000D_
_x000D_
_x000D_

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Maybe it is simple, try this if you have a DataFrame. then make sure that both matrices or vectros that you're trying to combine have the same rows_name/index

I had the same issue. I changed the name indices of the rows to make them match each other here is an example for a matrix (principal component) and a vector(target) have the same row indicies (I circled them in the blue in the leftside of the pic)

Before, "when it was not working", I had the matrix with normal row indicies (0,1,2,3) while I had the vector with row indices (ID0, ID1, ID2, ID3) then I changed the vector's row indices to (0,1,2,3) and it worked for me.

enter image description here

Get value from a string after a special character

Here's a way:

<html>
    <head>
        <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                var value = $('input[type="hidden"]')[0].value;
                alert(value.split(/\?/)[1]);
            });
        </script>
    </head>
    <body>
        <input type="hidden" value="/TEST/Name?3" />
    </body>
</html>

How to create our own Listener interface in android?

I have created a Generic AsyncTask Listener which get result from AsycTask seperate class and give it to CallingActivity using Interface Callback.

new GenericAsyncTask(context,new AsyncTaskCompleteListener()
        {
             public void onTaskComplete(String response) 
             {
                 // do your work. 
             }
        }).execute();

Interface

interface AsyncTaskCompleteListener<T> {
   public void onTaskComplete(T result);
}

GenericAsyncTask

class GenericAsyncTask extends AsyncTask<String, Void, String> 
{
    private AsyncTaskCompleteListener<String> callback;

    public A(Context context, AsyncTaskCompleteListener<String> cb) {
        this.context = context;
        this.callback = cb;
    }

    protected void onPostExecute(String result) {
       finalResult = result;
       callback.onTaskComplete(result);
   }  
}

Have a look at this , this question for more details.

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

Defining lists as global variables in Python

No, you can specify the list as a keyword argument to your function.

alist = []
def fn(alist=alist):
    alist.append(1)
fn()
print alist    # [1]

I'd say it's bad practice though. Kind of too hackish. If you really need to use a globally available singleton-like data structure, I'd use the module level variable approach, i.e. put 'alist' in a module and then in your other modules import that variable:

In file foomodule.py:

alist = []

In file barmodule.py:

import foomodule
def fn():
    foomodule.alist.append(1)
print foomodule.alist    # [1]

Mockito matcher and array of primitives

I agree with Mutanos and Alecio. Further, one can check as many identical method calls as possible (verifying the subsequent calls in the production code, the order of the verify's does not matter). Here is the code:

import static org.mockito.AdditionalMatchers.*;

    verify(mockObject).myMethod(aryEq(new byte[] { 0 }));
    verify(mockObject).myMethod(aryEq(new byte[] { 1, 2 }));

CSS content property: is it possible to insert HTML instead of Text?

Unfortunately, this is not possible. Per the spec:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.

As an example, using the given CSS with the following HTML:

<h1 class="header">Title</h1>

... will result in the following output:

<a href="#top">Back</a>Title

CSS to set A4 paper size

CSS

body {
  background: rgb(204,204,204); 
}
page[size="A4"] {
  background: white;
  width: 21cm;
  height: 29.7cm;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
@media print {
  body, page[size="A4"] {
    margin: 0;
    box-shadow: 0;
  }
}

HTML

<page size="A4"></page>
<page size="A4"></page>
<page size="A4"></page>

DEMO

Custom Adapter for List View

public class ListAdapter extends ArrayAdapter<Item> {

    private int resourceLayout;
    private Context mContext;

    public ListAdapter(Context context, int resource, List<Item> items) {
        super(context, resource, items);
        this.resourceLayout = resource;
        this.mContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(mContext);
            v = vi.inflate(resourceLayout, null);
        }

        Item p = getItem(position);

        if (p != null) {
            TextView tt1 = (TextView) v.findViewById(R.id.id);
            TextView tt2 = (TextView) v.findViewById(R.id.categoryId);
            TextView tt3 = (TextView) v.findViewById(R.id.description);

            if (tt1 != null) {
                tt1.setText(p.getId());
            }

            if (tt2 != null) {
                tt2.setText(p.getCategory().getId());
            }

            if (tt3 != null) {
                tt3.setText(p.getDescription());
            }
        }

        return v;
    }

}

This is a class I had used for my project. You need to have a collection of your items which you want to display, in my case it's <Item>. You need to override View getView(int position, View convertView, ViewGroup parent) method.

R.layout.itemlistrow defines the row of the ListView.

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content" android:orientation="vertical"
    android:layout_width="fill_parent">

    <TableRow android:layout_width="fill_parent"
              android:id="@+id/TableRow01"
              android:layout_height="wrap_content">

        <TextView android:textColor="#FFFFFF"
                  android:id="@+id/id"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:text="id" android:textStyle="bold" 
                  android:gravity="left"
                  android:layout_weight="1" 
                  android:typeface="monospace"
                  android:height="40sp" />
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView android:textColor="#FFFFFF" 
                  android:id="@+id/categoryId"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:text="categoryId" 
                  android:layout_weight="1" 
                  android:height="20sp" />

        <TextView android:layout_height="wrap_content"
                  android:layout_width="fill_parent" 
                  android:layout_weight="1"
                  android:textColor="#FFFFFF"
                  android:gravity="right"
                  android:id="@+id/description"
                  android:text="description" 
                  android:height="20sp" />
    </TableRow>

</TableLayout>

In the MainActivity define ListViewlike this,

ListView yourListView = (ListView) findViewById(R.id.itemListView);

// get data from the table by the ListAdapter
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, List<yourItem>);

yourListView .setAdapter(customAdapter);

How to update parent's state in React?

It seems that we can only pass data from parent to child as react promotes Unidirectional Data Flow, but to make parent update itself when something happens in its "child component", we generally use what is called a "callback function".

We pass the function defined in the parent to the child as "props" and call that function from the child triggering it in the parent component.


class Parent extends React.Component {
  handler = (Value_Passed_From_SubChild) => {
    console.log("Parent got triggered when a grandchild button was clicked");
    console.log("Parent->Child->SubChild");
    console.log(Value_Passed_From_SubChild);
  }
  render() {
    return <Child handler = {this.handler} />
  }
}
class Child extends React.Component {
  render() {
    return <SubChild handler = {this.props.handler}/ >
  }
}
class SubChild extends React.Component { 
  constructor(props){
   super(props);
   this.state = {
      somethingImp : [1,2,3,4]
   }
  }
  render() {
     return <button onClick = {this.props.handler(this.state.somethingImp)}>Clickme<button/>
  }
}
React.render(<Parent />,document.getElementById('app'));

 HTML
 ----
 <div id="app"></div>

In this example we can make data pass from SubChild -> Child -> Parent by passing function to its direct Child.

How to iterate for loop in reverse order in swift?

You can use reversed() method for easily reverse values.

var i:Int
for i in 1..10.reversed() {
    print(i)
}

The reversed() method reverse the values.

How can I send an email through the UNIX mailx command?

mailx -s "subjec_of_mail" [email protected] < file_name

through mailx utility we can send a file from unix to mail server. here in above code we can see first parameter is -s "subject of mail" the second parameter is mail ID and the last parameter is name of file which we want to attach

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

Video file formats supported in iPhone

Short answer: H.264 MPEG (MP4)

Long answer from Apple.com:

Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,

Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats

http://www.apple.com/iphone/specs.html

Can regular JavaScript be mixed with jQuery?

Yes, they're both JavaScript, you can use whichever functions are appropriate for the situation.

In this case you can just put the code in a document.ready handler, like this:

$(function() {
  var canvas = document.getElementById("canvas");
  if (canvas.getContext) {
    var ctx = canvas.getContext("2d");

    ctx.fillStyle = "rgb(200,0,0)";
    ctx.fillRect (10, 10, 55, 50);

    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect (30, 30, 55, 50);
  }
});

Remove Backslashes from Json Data in JavaScript

tl;dr: You don't have to remove the slashes, you have nested JSON, and hence have to decode the JSON twice: DEMO (note I used double slashes in the example, because the JSON is inside a JS string literal).


I assume that your actual JSON looks like

{"data":"{\n \"taskNames\" : [\n \"01 Jan\",\n \"02 Jan\",\n \"03 Jan\",\n \"04 Jan\",\n \"05 Jan\",\n \"06 Jan\",\n \"07 Jan\",\n \"08 Jan\",\n \"09 Jan\",\n \"10 Jan\",\n \"11 Jan\",\n \"12 Jan\",\n \"13 Jan\",\n \"14 Jan\",\n \"15 Jan\",\n \"16 Jan\",\n \"17 Jan\",\n \"18 Jan\",\n \"19 Jan\",\n \"20 Jan\",\n \"21 Jan\",\n \"22 Jan\",\n \"23 Jan\",\n \"24 Jan\",\n \"25 Jan\",\n \"26 Jan\",\n \"27 Jan\"]}"}

I.e. you have a top level object with one key, data. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. This lets the parser know that " is to be treated literally and doesn't terminate the string.

So you can either fix the server side code, so that you don't double encode the data, or you have to decode the JSON twice, e.g.

var data = JSON.parse(JSON.parse(json).data));

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

Four fewer characters, but 2 more ms

%%timeit
df.isna().T.any()
# 52.4 ms ± 352 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
df.isna().any(axis=1)
# 50 ms ± 423 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

I'd probably use axis=1

Interface or an Abstract Class: which one to use?

Why to use abstract classes? The following is a simple example. Lets say we have the following code:

<?php 

class Fruit {
    private $color;

    public function eat() {
        // chew
    }

    public function setColor($c) {
        $this->color = $c;
    }
}

class Apple extends Fruit {
    public function eat() {
        // chew until core
    }
}

class Orange extends Fruit {
    public function eat() {
        // peeling
        // chew
    }
}

Now I give you an apple and you eat it. What does it taste like? It tastes like an apple.

<?php 
$apple = new Apple();
$apple->eat();

// Now I give you a fruit.
$fruit = new Fruit();
$fruit->eat();

What does that taste like? Well, it doesn't make much sense, so you shouldn't be able to do that. This is accomplished by making the Fruit class abstract as well as the eat method inside of it.

<?php 
abstract class Fruit {
    private $color;

    abstract public function eat(){}

    public function setColor($c) {
        $this->color = $c;
    }
}
?>

An abstract class is just like an interface, but you can define methods in an abstract class whereas in an interface they are all abstract. Abstract classes can have both empty and working/concrete methods. In interfaces, functions defined there cannot have a body. In abstract classes, they can.

A real world example:

<?php 
abstract class person {

    public $LastName;
    public $FirstName;
    public $BirthDate;

    abstract protected function write_info();
}

final class employee extends person{

    public $EmployeeNumber;
    public $DateHired;

    public function write_info(){
        //sql codes here
        echo "Writing ". $this->LastName . "'s info to emloyee dbase table <br>";   
    }
}

final class student extends person{

    public $StudentNumber;
    public $CourseName;

    public function write_info(){
        //sql codes here
        echo "Writing ". $this->LastName . "'s info to student dbase table <br>";
    }
}

///----------
$personA = new employee;
$personB = new student;

$personA->FirstName="Joe";
$personA->LastName="Sbody";

$personB->FirstName="Ben";
$personB->LastName="Dover";

$personA->write_info();
// Writing Sbody's info to emloyee dbase table
$personB->write_info();
// Writing Dover's info to student dbase table 

How can I Remove .DS_Store files from a Git repository?

I had to change git-rm to git rm in the above to get it to work:

find . -depth -name '.DS_Store' -exec git rm --cached '{}' \; -print

Angularjs: input[text] ngChange fires while the value is changing

I had exactly the same problem and this worked for me. Add ng-model-update and ng-keyup and you're good to go! Here is the docs

 <input type="text" name="userName"
         ng-model="user.name"
         ng-change="update()"
         ng-model-options="{ updateOn: 'blur' }"
         ng-keyup="cancel($event)" />

Pandas - Compute z-score for all columns

The almost one-liner solution:

df2 = (df.ix[:,1:] - df.ix[:,1:].mean()) / df.ix[:,1:].std()
df2['ID'] = df['ID']

Find object by its property in array of objects with AngularJS way

you can use angular's filter https://docs.angularjs.org/api/ng/filter/filter

in your controller:

$filter('filter')(myArray, {'id':73}) 

or in your HTML

{{ myArray | filter : {'id':73} }}

Select all where [first letter starts with B]

You can use:

WHERE LEFT (name_field, 1) = 'B';

Better way to remove specific characters from a Perl string

With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write

$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi

or, using the more efficient tr

$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd

tr docs

What is App.config in C#.NET? How to use it?

App.Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.

See this MSDN article on how to do that.

List of macOS text editors and code editors

I like Aptana Studio and Redcar for rails programming.

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

This trick worked for me in Eclipse Luna (4.4.2): For a jar file I am using (htsjdk), I packed the source in a separate jar file (named htsjdk-2.0.1-src.jar; I could do this since htsjdk is open source) and stored it in the lib-src folder of my project. In my own Java source I selected an element I was using from the jar and hit F3 (Open declaration). Eclipse opened the class file and showed the button "Attach source". I clicked the button and pointed to the src jar file I had just put into the lib-src folder. Now I get the Javadoc when hovering over anything I’m using from the jar.

How to get a parent element to appear above child

Some of these answers do work, but setting position: absolute; and z-index: 10; seemed pretty strong just to achieve the required effect. I found the following was all that was required, though unfortunately, I've not been able to reduce it any further.

HTML:

<div class="wrapper">
    <div class="parent">
        <div class="child">
            ...
        </div>
    </div>
</div>

CSS:

.wrapper {
    position: relative;
    z-index: 0;
}

.child {
    position: relative;
    z-index: -1;
}

I used this technique to achieve a bordered hover effect for image links. There's a bit more code here but it uses the concept above to show the border over the top of the image.

http://jsfiddle.net/g7nP5/

smtp configuration for php mail

But now it is not working and I contacted our hosting team then they told me to use smtp

Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.

Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.

Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).

C.

How do I install Python 3 on an AWS EC2 instance?

As of Amazon Linux version 2017.09 python 3.6 is now available:

sudo yum install python36 python36-virtualenv python36-pip

See the Release Notes for more info and other packages

Kill a postgresql session/connection

For me worked the following:

sudo gitlab-ctl stop
sudo gitlab-ctl start gitaly
sudo gitlab-rake gitlab:setup [type yes and let it finish]
sudo gitlab-ctl start

I am using:
gitlab_edition: "gitlab-ce"
gitlab_version: '12.4.0-ce.0.el7'

What is the difference between "::" "." and "->" in c++

-> is for pointers to a class instance

. is for class instances

:: is for classnames - for example when using a static member

HTML embed autoplay="false", but still plays automatically

<embed ... autostart="0">

Replace false with 0

Detect if Android device has Internet connection

A nice solution to check if the active network have internet connection:

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        Network network = connectivityManager.getActiveNetwork();
        NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
        return networkCapabilities != null && networkCapabilities
                .hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    }
    return false;
}

Loop through an array in JavaScript

var x = [4, 5, 6];
for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
    console.log(i,j);
}

A lot cleaner...

Openssl is not recognized as an internal or external command

This works for me:

C:\Users\example>keytool -exportcert -alias androiddebugkey -keystore 
"C:\Users\example\.android" | "C:\openssl\bin\openssl.exe" sha1 -binary 
| "C:\openssl\bin\oenssl.exe" base64

Leverage browser caching, how on apache or .htaccess?

I took my chance to provide full .htaccess code to pass on Google PageSpeed Insight:

  1. Enable compression
  2. Leverage browser caching
# Enable Compression
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
</IfModule>
<IfModule mod_gzip.c>
  mod_gzip_on Yes
  mod_gzip_dechunk Yes
  mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
  mod_gzip_item_include handler ^cgi-script$
  mod_gzip_item_include mime ^text/.*
  mod_gzip_item_include mime ^application/x-javascript.*
  mod_gzip_item_exclude mime ^image/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

# Leverage Browser Caching
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpg "access 1 year"
  ExpiresByType image/jpeg "access 1 year"
  ExpiresByType image/gif "access 1 year"
  ExpiresByType image/png "access 1 year"
  ExpiresByType text/css "access 1 month"
  ExpiresByType text/html "access 1 month"
  ExpiresByType application/pdf "access 1 month"
  ExpiresByType text/x-javascript "access 1 month"
  ExpiresByType application/x-shockwave-flash "access 1 month"
  ExpiresByType image/x-icon "access 1 year"
  ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</IfModule>

There is also some configurations for various web servers see here.
Hope this would help to get the 100/100 score.

optimized page score

Bootstrap tab activation with JQuery

Add an id attribute to a html tag

<ul class="nav nav-tabs">
    <li><a href="#aaa" data-toggle="tab" id="tab_aaa">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab" id="tab_bbb">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab" id="tab_ccc">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>

Then using JQuery

$("#tab_aaa").tab('show');

Use Device Login on Smart TV / Console

i've been researching for that too but unfortunately the facebook device auth is still on experimental and they didn't give new keys (partner) to use the device auth.

You can find the working example here: http://oauth-device-demo.appspot.com/ Just look at the website source and you can have the appID that works with it.

The other one is twitter PIN oauth it's working and publicly available (i'm using it) https://dev.twitter.com/docs/auth/pin-based-authorization

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

I have a better way to solve the 'February 31st' problem:

def add_months(start_date, months):
    import calendar

    year = start_date.year + (months / 12)
    month = start_date.month + (months % 12)
    day = start_date.day

    if month > 12:
        month = month % 12
        year = year + 1

    days_next = calendar.monthrange(year, month)[1]
    if day > days_next:
        day = days_next

    return start_date.replace(year, month, day)

I think that it also works with negative numbers (to subtract months), but I haven't tested this very much.

How do I remove background-image in css?

div#a {
  background-image: url('../images/spacer.png');
  background-image: none !important;
}

I use a transparent spacer image in addition to the rule to remove the background image because IE6 seems to ignore the background-image: none even though it is marked !important.

Underscore prefix for property and method names in JavaScript

"Only conventions? Or is there more behind the underscore prefix?"

Apart from privacy conventions, I also wanted to help bring awareness that the underscore prefix is also used for arguments that are dependent on independent arguments, specifically in URI anchor maps. Dependent keys always point to a map.

Example ( from https://github.com/mmikowski/urianchor ) :

$.uriAnchor.setAnchor({
  page   : 'profile',
  _page  : {
    uname   : 'wendy',
    online  : 'today'
  }
});

The URI anchor on the browser search field is changed to:

\#!page=profile:uname,wendy|online,today

This is a convention used to drive an application state based on hash changes.

Vector of Vectors to create matrix

Assume we have the following class:

#include <vector>

class Matrix {
 private:
  std::vector<std::vector<int>> data;
};

First of all I would like suggest you to implement a default constructor:

#include <vector>

class Matrix {
 public:
  Matrix(): data({}) {}

 private:
  std::vector<std::vector<int>> data;
};

At this time we can create Matrix instance as follows:

Matrix one;

The next strategic step is to implement a Reset method, which takes two integer parameters that specify the new number of rows and columns of the matrix, respectively:

#include <vector>

class Matrix {
 public:
  Matrix(): data({}) {}

  Matrix(const int &rows, const int &cols) {
    Reset(rows, cols);
  }

  void Reset(const int &rows, const int &cols) {
    if (rows == 0 || cols == 0) {
      data.assign(0, std::vector<int>(0));
    } else {
      data.assign(rows, std::vector<int>(cols));
    }
  }

 private:
  std::vector<std::vector<int>> data;
};

At this time the Reset method changes the dimensions of the 2D-matrix to the given ones and resets all its elements. Let me show you a bit later why we may need this.

Well, we can create and initialize our matrix:

Matrix two(3, 5);

Lets add info methods for our matrix:

#include <vector>

class Matrix {
 public:
  Matrix(): data({}) {}

  Matrix(const int &rows, const int &cols) {
    Reset(rows, cols);
  }

  void Reset(const int &rows, const int &cols) {
    data.resize(rows);
    for (int i = 0; i < rows; ++i) {
      data.at(i).resize(cols);
    }
  }

  int GetNumRows() const {
    return data.size();
  }

  int GetNumColumns() const {
    if (GetNumRows() > 0) {
      return data[0].size();
    }

    return 0;
  }

 private:
  std::vector<std::vector<int>> data;
};

At this time we can get some trivial matrix debug info:

#include <iostream>

void MatrixInfo(const Matrix& m) {
  std::cout << "{ \"rows\": " << m.GetNumRows()
            << ", \"cols\": " << m.GetNumColumns() << " }" << std::endl;
}

int main() {
  Matrix three(3, 4);
  MatrixInfo(three);
}

The second class method we need at this time is At. A sort of getter for our private data:

#include <vector>

class Matrix {
 public:
  Matrix(): data({}) {}

  Matrix(const int &rows, const int &cols) {
    Reset(rows, cols);
  }

  void Reset(const int &rows, const int &cols) {
    data.resize(rows);
    for (int i = 0; i < rows; ++i) {
      data.at(i).resize(cols);
    }
  }

  int At(const int &row, const int &col) const {
    return data.at(row).at(col);
  }

  int& At(const int &row, const int &col) {
    return data.at(row).at(col);
  }

  int GetNumRows() const {
    return data.size();
  }

  int GetNumColumns() const {
    if (GetNumRows() > 0) {
      return data[0].size();
    }

    return 0;
  }

 private:
  std::vector<std::vector<int>> data;
};

The constant At method takes the row number and column number and returns the value in the corresponding matrix cell:

#include <iostream>

int main() {
  Matrix three(3, 4);
  std::cout << three.At(1, 2); // 0 at this time
}

The second, non-constant At method with the same parameters returns a reference to the value in the corresponding matrix cell:

#include <iostream>

int main() {
  Matrix three(3, 4);
  three.At(1, 2) = 8;
  std::cout << three.At(1, 2); // 8
}

Finally lets implement >> operator:

#include <iostream>

std::istream& operator>>(std::istream& stream, Matrix &matrix) {
  int row = 0, col = 0;

  stream >> row >> col;
  matrix.Reset(row, col);

  for (int r = 0; r < row; ++r) {
    for (int c = 0; c < col; ++c) {
      stream >> matrix.At(r, c);
    }
  }

  return stream;
}

And test it:

#include <iostream>

int main() {
  Matrix four; // An empty matrix

  MatrixInfo(four);
  // Example output:
  //
  // { "rows": 0, "cols": 0 }

  std::cin >> four;
  // Example input
  //
  // 2 3
  // 4 -1 10
  // 8 7 13

  MatrixInfo(four);
  // Example output:
  //
  // { "rows": 2, "cols": 3 }
}

Feel free to add out of range check. I hope this example helps you :)

char initial value in Java

As you will see in linked discussion there is no need for initializing char with special character as it's done for us and is represented by '\u0000' character code.

So if we want simply to check if specified char was initialized just write:

if(charVariable != '\u0000'){
 actionsOnInitializedCharacter();
}

Link to question: what's the default value of char?

Git: force user and password prompt

With git config -l, I now see I have a credential.helper=osxkeychain option

That means the credential helper (initially introduced in 1.7.10) is now in effect, and will cache automatically the password for accessing a remote repository over HTTP.
(as in "GIT: Any way to set default login credentials?")

You can disable that option entirely, or only for a single repo.

Regular Expression for password validation

Update to Justin answer above. if you want to use it using Data Annotation in MVC you can do as follow

[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$", ErrorMessage = "Password must be between 6 and 20 characters and contain one uppercase letter, one lowercase letter, one digit and one special character.")]

Angular 2: How to write a for loop, not a foreach loop

Depending on the length of the wanted loop, maybe even a more "template-driven" solution:

<ul>
  <li *ngFor="let index of [0,1,2,3,4,5]">
    {{ index }}
  </li>
</ul>

How do I install TensorFlow's tensorboard?

I have a local install of tensorflow 1.15.0 (with tensorboard obviously included) on MacOS.

For me, the path to the relevant file within my user directory is Library/Python/3.7/lib/python/site-packages/tensorboard/main.py. So, which does not work for me, but you have to look for the file named main.py, which is weird since it apparently is named something else for other users.

adb doesn't show nexus 5 device

For those who are still frustrated, if you are using the experimental ART runtime, try switching back to dalvik (in developer options on device)

Why isn't textarea an input[type="textarea"]?

Maybe this is going a bit too far back but…

Also, I’d like to suggest that multiline text fields have a different type (e.g. “textarea") than single-line fields ("text"), as they really are different types of things, and imply different issues (semantics) for client-side handling.

Marc Andreessen, 11 October 1993

Using a PagedList with a ViewModel ASP.Net MVC

The fact that you're using a view model has no bearing. The standard way of using PagedList is to store "one page of items" as a ViewBag variable. All you have to determine is what collection constitutes what you'll be paging over. You can't logically page multiple collections at the same time, so assuming you chose Instructors:

ViewBag.OnePageOfItems = myViewModelInstance.Instructors.ToPagedList(pageNumber, 10);

Then, the rest of the standard code works as it always has.

How to check whether an object has certain method/property?

To avoid AmbiguousMatchException, I would rather say

objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0

How to know function return type and argument types?

Docstrings (and documentation in general). Python 3 introduces (optional) function annotations, as described in PEP 3107 (but don't leave out docstrings)

Launch Minecraft from command line - username and password as prefix

To run Minecraft with Forge (change C:\Users\nov11\AppData\Roaming/.minecraft/to your MineCraft path :) [Just for people who are a bit too lazy to search on Google...] Special thanks to ammarx for his TagAPI_3 (Github) which was used to create this command. Arguments are separated line by line to make it easier to find useful ones.

java
-Xms1024M
-Xmx1024M
-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump
-Djava.library.path=C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/natives
-cp
C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraftforge/forge/1.12.2-14.23.5.2775/forge-1.12.2-14.23.5.2775.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/ow2/asm/asm-all/5.2/asm-all-5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/jline/jline/3.5.1/jline-3.5.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/akka/akka-actor_2.11/2.3.3/akka-actor_2.11-2.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/config/1.2.1/config-1.2.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-actors-migration_2.11/1.1.0/scala-actors-migration_2.11-1.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-compiler/2.11.1/scala-compiler-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-library_2.11/1.0.2/scala-continuations-library_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-plugin_2.11.1/1.0.2/scala-continuations-plugin_2.11.1-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-parser-combinators_2.11/1.0.1/scala-parser-combinators_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-reflect/2.11.1/scala-reflect-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-swing_2.11/1.0.1/scala-swing_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-xml_2.11/1.0.2/scala-xml_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/java3d/vecmath/1.5.2/vecmath-1.5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/trove4j/trove4j/3.0.3/trove4j-3.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/maven/maven-artifact/3.5.3/maven-artifact-3.5.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/patchy/1.1/patchy-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/oshi-project/oshi-core/1.1/oshi-core-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/platform/3.4.0/platform-3.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/ibm/icu/icu4j-core-mojang/51.2/icu4j-core-mojang-51.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecjorbis/20101023/codecjorbis-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecwav/20101023/codecwav-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/libraryjavasound/20101123/libraryjavasound-20101123.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/librarylwjglopenal/20100824/librarylwjglopenal-20100824.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/soundsystem/20120107/soundsystem-20120107.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/io/netty/netty-all/4.1.9.Final/netty-all-4.1.9.Final.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/guava/guava/21.0/guava-21.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-lang3/3.5/commons-lang3-3.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-io/commons-io/2.5/commons-io-2.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-codec/commons-codec/1.10/commons-codec-1.10.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jinput/jinput/2.0.5/jinput-2.0.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jutils/jutils/1.0.0/jutils-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/authlib/1.5.25/authlib-1.5.25.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/realms/1.10.22/realms-1.10.22.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-compress/1.8.1/commons-compress-1.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpclient/4.3.3/httpclient-4.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpcore/4.3.2/httpcore-4.3.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/it/unimi/dsi/fastutil/7.1.0/fastutil-7.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-api/2.8.1/log4j-api-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-core/2.8.1/log4j-core-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.4-nightly-20150209/lwjgl_util-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.2-nightly-20140822/lwjgl-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.2-nightly-20140822/lwjgl_util-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/1.12.2.jar
net.minecraft.launchwrapper.Launch
--width
854
--height
480
--username
Ishikawa
--version
1.12.2-forge1.12.2-14.23.5.2775
--gameDir
C:\Users\nov11\AppData\Roaming/.minecraft
--assetsDir
C:\Users\nov11\AppData\Roaming/.minecraft/assets
--assetIndex
1.12
--uuid
N/A
--accessToken
aeef7bc935f9420eb6314dea7ad7e1e5
--userType
mojang
--tweakClass
net.minecraftforge.fml.common.launcher.FMLTweaker
--versionType
Forge

Just when other solutions don't work. accessToken and uuid can be acquired from Mojang Servers, check other anwsers for details.

Edit (26.11.2018): I've also created Launcher Framework in C# (.NET Framework 3.5), which you can also check to see how launcher should work Available Here

Team Build Error: The Path ... is already mapped to workspace

I had a similar problem with Visual Studio 2010 complaining about an already-mapped-workspace, but instead of deleting the entire workspace, I used the following from the Visual Studio Command Prompt: "tf workspace PROBLEM_WORKSPACE_NAME". This brought up an "Edit Workspace" dialog. From there I was able to remove the path in question from the "Working Folders" list, which got rid of the error.

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

Convert xlsx to csv in Linux with command line

If .xlsx file has many sheets, -s flag can be used to get the sheet you want. For example:

xlsx2csv "my_file.xlsx" -s 2 second_sheet.csv

second_sheet.csv would contain data of 2nd sheet in my_file.xlsx.

Filter by Dates in SQL

If your dates column does not contain time information, you could get away with:

WHERE dates BETWEEN '20121211' and '20121213'

However, given your dates column is actually datetime, you want this

WHERE dates >= '20121211'
  AND dates < '20121214'  -- i.e. 00:00 of the next day

Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:

WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'

Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.

Sorting a Dictionary in place with respect to keys

Take a look at SortedDictionary, there's even a constructor overload so you can pass in your own IComparable for the comparisons.

Cannot use object of type stdClass as array?

When you try to access it as $result['context'], you treating it as an array, the error it's telling you that you are actually dealing with an object, then you should access it as $result->context

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

double doubleVal = 1.745;
double doubleVal1 = 0.745;
System.out.println(new BigDecimal(doubleVal));
System.out.println(new BigDecimal(doubleVal1));

outputs:

1.74500000000000010658141036401502788066864013671875
0.74499999999999999555910790149937383830547332763671875

Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).

More about double precision:

NoClassDefFoundError in Java: com/google/common/base/Function

After you extract your "selenium-java-.zip" file you need to configure your build path from your IDE. Import all the jar files under "lib" folder and both selenium standalone server & Selenium java version jar files.

Jquery function BEFORE form submission

You can use some div or span instead of button and then on click call some function which submits form at he end.

<form id="my_form">
   <span onclick="submit()">submit</span>
</form>

<script>
   function submit()
   {   
       //do something
       $("#my_form").submit();
   }
</script>

jquery ajax get responsetext from http url

The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).

And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)

Recommendations of Python REST (web services) framework?

Seems all kinds of python web frameworks can implement RESTful interfaces now.

For Django, besides tastypie and piston, django-rest-framework is a promising one worth to mention. I've already migrated one of my project on it smoothly.

Django REST framework is a lightweight REST framework for Django, that aims to make it easy to build well-connected, self-describing RESTful Web APIs.

Quick example:

from django.conf.urls.defaults import patterns, url
from djangorestframework.resources import ModelResource
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
from myapp.models import MyModel

class MyResource(ModelResource):
    model = MyModel

urlpatterns = patterns('',
    url(r'^$', ListOrCreateModelView.as_view(resource=MyResource)),
    url(r'^(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=MyResource)),
)

Take the example from official site, all above codes provide api, self explained document(like soap based webservice) and even sandbox to test a bit. Very convenience.

Links: http://django-rest-framework.org/

Delimiter must not be alphanumeric or backslash and preg_match

You can also use T-Regx library which has automatic delimiters for you:

$matches = pattern("My name is '(.*)' and im fine")->match($string1)->all();

                 // ? No delimiters needed 

How to escape special characters of a string with single backslashes

This is one way to do it (in Python 3.x):

escaped = a_string.translate(str.maketrans({"-":  r"\-",
                                          "]":  r"\]",
                                          "\\": r"\\",
                                          "^":  r"\^",
                                          "$":  r"\$",
                                          "*":  r"\*",
                                          ".":  r"\."}))

For reference, for escaping strings to use in regex:

import re
escaped = re.escape(a_string)

Get startup type of Windows service using PowerShell

WMI is the way to do this.

Get-WmiObject -Query "Select StartMode From Win32_Service Where Name='winmgmt'"

Or

Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='Winmgmt'"

How to make a .jar out from an Android Studio project

In the Android Studio IDE, access the "Run Anything bar" by:

CTRL+CTRL +gradle CreateFullJarRelease+ENTER

After that you'll find your artefact in this folder in your project
Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar


OR


Gradle has already a Task for that, in the gradle side-menu, under the other folder.

gradle toolbar

Then scroll down to createFullJarRelease and click it.

Gradle Tasks

After that you'll find your artefact in this folder in your project

Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar

Writing a new line to file in PHP (line feed)

Use PHP_EOL which outputs \r\n or \n depending on the OS.

How to make lists contain only distinct element in Python?

one-liner and preserve order

list(OrderedDict.fromkeys([2,1,1,3]))

although you'll need

from collections import OrderedDict

jQuery UI DatePicker to show year only

I had the same problem and, after a day of research, I came up with this solution: http://jsfiddle.net/konstantc/4jkef3a1/

_x000D_
_x000D_
// *** (month and year only) ***_x000D_
$(function() { _x000D_
  $('#datepicker1').datepicker( {_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: true,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: true,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('MM yy (M y) (mm/y)', new Date(year, month, 1)));_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only) ***_x000D_
$(function() { _x000D_
  $('#datepicker2').datepicker( {_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: false,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: true,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-month").hide();_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $(".ui-datepicker-prev").hide();_x000D_
    $(".ui-datepicker-next").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only, no controls) ***_x000D_
$(function() { _x000D_
  $('#datepicker3').datepicker( {_x000D_
    dateFormat: "yy",_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: false,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: false,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
    },_x000D_
    onChangeMonthYear : function () {_x000D_
      $(this).datepicker( "hide" );_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-month").hide();_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $(".ui-datepicker-prev").hide();_x000D_
    $(".ui-datepicker-next").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
  <h2 class="font-weight-light text-lg-left mt-4 mb-0"><b>jQuery UI Datepicker</b> custom select</h2>_x000D_
_x000D_
  <hr class="mt-2 mb-3">_x000D_
  <div class="row text-lg-left">_x000D_
    <div class="col-12">_x000D_
_x000D_
      <form>_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker1">(month and year only : <code>id="datepicker1"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker1" _x000D_
                 placeholder="(month and year only)" />_x000D_
        </div>_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker2">(year only : <code>input id="datepicker2"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker2" _x000D_
                 placeholder="(year only)" />_x000D_
        </div>_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker3">(year only, no controls : <code>input id="datepicker3"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker3" _x000D_
                 placeholder="(year only, no controls)" />_x000D_
        </div>_x000D_
_x000D_
      </form>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

I know this question is pretty old but I thought that my solution can be of use to others that encounter this problem. Hope it helps.

How to create an XML document using XmlDocument?

What about:

#region Using Statements
using System;
using System.Xml;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XmlDocument doc = new XmlDocument( );

        //(1) the xml declaration is recommended, but not mandatory
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore( xmlDeclaration, root );

        //(2) string.Empty makes cleaner code
        XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
        doc.AppendChild( element1 );

        XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
        element1.AppendChild( element2 );

        XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text1 = doc.CreateTextNode( "text" );
        element3.AppendChild( text1 );
        element2.AppendChild( element3 );

        XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text2 = doc.CreateTextNode( "other text" );
        element4.AppendChild( text2 );
        element2.AppendChild( element4 );

        doc.Save( "D:\\document.xml" );
    }
}

(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?


The result is:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

But I recommend you to use LINQ to XML which is simpler and more readable like here:

#region Using Statements
using System;
using System.Xml.Linq;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XDocument doc = new XDocument( new XElement( "body", 
                                           new XElement( "level1", 
                                               new XElement( "level2", "text" ), 
                                               new XElement( "level2", "other text" ) ) ) );
        doc.Save( "D:\\document.xml" );
    }
}

How to remove illegal characters from path and filenames?

For starters, Trim only removes characters from the beginning or end of the string. Secondly, you should evaluate if you really want to remove the offensive characters, or fail fast and let the user know their filename is invalid. My choice is the latter, but my answer should at least show you how to do things the right AND wrong way:

StackOverflow question showing how to check if a given string is a valid file name. Note you can use the regex from this question to remove characters with a regular expression replacement (if you really need to do this).

Binding Listbox to List<object> in WinForms

ListBox1.DataSource = CreateDataSource();
ListBox1.DataTextField = "FieldProperty";
ListBox1.DataValueField = "ValueProperty";

Please refer to this article for detailed examples.

Change column type in pandas

When I've only needed to specify specific columns, and I want to be explicit, I've used (per DOCS LOCATION):

dataframe = dataframe.astype({'col_name_1':'int','col_name_2':'float64', etc. ...})

So, using the original question, but providing column names to it ...

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col_name_1', 'col_name_2', 'col_name_3'])
df = df.astype({'col_name_2':'float64', 'col_name_3':'float64'})

How to capitalize the first letter of text in a TextView in an Android Application

Please create a custom TextView and use it :

public class CustomTextView extends TextView {

    public CapitalizedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        if (text.length() > 0) {
            text = String.valueOf(text.charAt(0)).toUpperCase() + text.subSequence(1, text.length());
        }
        super.setText(text, type);
    }
}

Zip folder in C#

using DotNetZip (available as nuget package):

public void Zip(string source, string destination)
{
    using (ZipFile zip = new ZipFile
    {
        CompressionLevel = CompressionLevel.BestCompression
    })
    {
        var files = Directory.GetFiles(source, "*",
            SearchOption.AllDirectories).
            Where(f => Path.GetExtension(f).
                ToLowerInvariant() != ".zip").ToArray();

        foreach (var f in files)
        {
            zip.AddFile(f, GetCleanFolderName(source, f));
        }

        var destinationFilename = destination;

        if (Directory.Exists(destination) && !destination.EndsWith(".zip"))
        {
            destinationFilename += $"\\{new DirectoryInfo(source).Name}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-ffffff}.zip";
        }

        zip.Save(destinationFilename);
    }
}

private string GetCleanFolderName(string source, string filepath)
{
    if (string.IsNullOrWhiteSpace(filepath))
    {
        return string.Empty;
    }

    var result = filepath.Substring(source.Length);

    if (result.StartsWith("\\"))
    {
        result = result.Substring(1);
    }

    result = result.Substring(0, result.Length - new FileInfo(filepath).Name.Length);

    return result;
}

Usage:

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest");

Or

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest\output.zip");

Calling startActivity() from outside of an Activity context

You can achieve it with addFlags instead of setFlags

myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

According to the documentation it does:

Add additional flags to the intent (or with existing flags value).


EDIT

Be aware if you are using flags that you change the history stack as Alex Volovoy's answer says:

...avoid setting flags as it will interfere with normal flow of event and history stack.

MySQL timestamp select date range

A compact, flexible method for timestamps without fractional seconds would be:

SELECT * FROM table_name 
WHERE field_name 
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')

If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >= and < operators as per Wouter's answer.

Here is an example of temporal fields defined with fractional second precision (maximum precision in use):

mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)

mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)

mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)

Check if a value is an object in JavaScript

Here's an answer with optional chaining, and perhaps the smallest isObj function for this question.

_x000D_
_x000D_
const isObj = o => o?.constructor === Object;_x000D_
_x000D_
// True for this_x000D_
console.log(isObj({}));        // object!_x000D_
_x000D_
// False for these_x000D_
console.log(isObj(0));         // number_x000D_
console.log(isObj([]));        // array_x000D_
console.log(isObj('lol'));     // string_x000D_
console.log(isObj(null));      // null_x000D_
console.log(isObj(undefined)); // undefined_x000D_
console.log(isObj(() => {}));  // function_x000D_
console.log(isObj(Object));    // class
_x000D_
_x000D_
_x000D_

Where are static methods and static variables stored in Java?

In real world or project we have requirement in advance and needs to create variable and methods inside the class , On the basis of requirement we needs to decide whether we needs to create

  1. Local ( create n access within block or method constructor)
  2. Static,
  3. Instance Variable( every object has its own copy of it),

=>2. Static Keyword we will used with variable which going to same for particular class throughout for all objects, e.g in selenium : we decalre webDriver as static=> so we do not need to create webdriver again and again for every test case= Static Webdriver driver(but parallel execution it will cause problem but thats another case); then, Real world scenario=>If India is class then, flag, money would be same every indian so we might take as static. Anatoher example: utility method we always declare as static b'cos it will be used in different test cases. Static stored in CMA( PreGen space)=PreGen (Fixed memory)changed to Metaspace after Java8 as now its growing dynamically

Bootstrap DatePicker, how to set the start date for tomorrow?

this.$('#datepicker').datepicker({minDate: 1});

minDate:0 - Enable dates in the calender from the current date. MinDate:1 enable dates in the calender currentDate+1

To Restrict date between from tomorrow and the same day next month u need to give something like

$( "#datepicker" ).datepicker({ minDate: 1, maxDate: "+1M" });

How to set time zone in codeigniter?

add it in your index.php file, and it will work on all over your site

if ( function_exists( 'date_default_timezone_set' ) ) {
    date_default_timezone_set('Asia/Kolkata');
}

Cannot find R.layout.activity_main

I had the same problem, fixed by replacing R with com.example.appname.R obviously put your package reference in there instead. Or just add this line to your file:

import com.your.package.R

Or even better, try removing this line from your code if exists:

import android.support.compat.R

Check if object exists in JavaScript

If that's a global object, you can use if (!window.maybeObject)

Remove CSS from a Div using JQuery

You could use the removeAttr method, if you want to delete all the inline style you added manually with javascript. It's better to use CSS classes but you never know.

$("#displayPanel div").removeAttr("style")

Linux: command to open URL in default browser

I think using xdg-open http://example.com is probably the best choice.

In case they don't have it installed I suppose they might have just kde-open or gnome-open (both of which take a single file/url) or some other workaround such as looping over common browser executable names until you find one which can be executed(using which). If you want a full list of workarounds/fallbacks I suggest reading xdg-open(it's a shell script which calls out to kde-open/gnome-open/etc. or some other fallback).

But since xdg-open and xdg-mime(used for one of the fallbacks,) are shell scripts I'd recommend including them in your application and if calling which xdg-open fails add them to temporary PATH variable in your subprograms environment and call out to them. If xdg-open fails, I'd recommend throwing an Exception with an error message from what it output on stderr and catching the exception and printing/displaying the error message.

I would ignore the java awt Desktop solution as the bug seems to indicate they don't plan on supporting non-gnome desktops anytime soon.

SyntaxError: Use of const in strict mode?

cd /
npm install -g nave
nave use 6.11.1
node app.js

TABLOCK vs TABLOCKX

Quite an old article on mssqlcity attempts to explain the types of locks:

Shared locks are used for operations that do not change or update data, such as a SELECT statement.

Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.

Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.

What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).


The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.

What does cmd /C mean?

/C Carries out the command specified by the string and then terminates.

You can get all the cmd command line switches by typing cmd /?.

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Check your Gradle plugin version. Try downgrading it if you have updated to a newer version just before this issue showed up. Go to File -> Project Structure. Change to the previous version.

Creating a URL in the controller .NET MVC

I had the same issue, and it appears Gidon's answer has one tiny flaw: it generates a relative URL, which cannot be sent by mail.

My solution looks like this:

string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });

This way, a full URL is generated, and it works even if the application is several levels deep on the hosting server, and uses a port other than 80.

EDIT: I found this useful as well.

How to copy data from one table to another new table in MySQL?

INSERT INTO Table1(Column1,Column2..) SELECT Column1,Column2.. FROM Table2 [WHERE <condition>]

C++: Print out enum value as text

There has been a discussion here which might help: Is there a simple way to convert C++ enum to string?

UPDATE: Here#s a script for Lua which creates an operator<< for each named enum it encounters. This might need some work to make it work for the less simple cases [1]:

function make_enum_printers(s)
    for n,body in string.gmatch(s,'enum%s+([%w_]+)%s*(%b{})') do
    print('ostream& operator<<(ostream &o,'..n..' n) { switch(n){') 
    for k in string.gmatch(body,"([%w_]+)[^,]*") do
    print('  case '..k..': return o<<"'..k..'";')
    end
    print('  default: return o<<"(invalid value)"; }}')
    end
end

local f=io.open(arg[1],"r")
local s=f:read('*a')
make_enum_printers(s)

Given this input:

enum Errors
{ErrorA=0, ErrorB, ErrorC};

enum Sec {
    X=1,Y=X,foo_bar=X+1,Z
};

It produces:

ostream& operator<<(ostream &o,Errors n) { switch(n){
  case ErrorA: return o<<"ErrorA";
  case ErrorB: return o<<"ErrorB";
  case ErrorC: return o<<"ErrorC";
  default: return o<<"(invalid value)"; }}
ostream& operator<<(ostream &o,Sec n) { switch(n){
  case X: return o<<"X";
  case Y: return o<<"Y";
  case foo_bar: return o<<"foo_bar";
  case Z: return o<<"Z";
  default: return o<<"(invalid value)"; }}

So that's probably a start for you.

[1] enums in different or non-namespace scopes, enums with initializer expressions which contain a komma, etc.