Programs & Examples On #Setdlldirectory

Adds a directory to the search path used to locate DLLs for the application.

Pass a password to ssh in pure bash

Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:

"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage

which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh "thought" that it is run in the regular terminal and since it may be accomplished by simple posix functions, it is beyond what simple bash offers.

Remove all whitespace from C# string with regex

No need for regex. This will also remove tabs, newlines etc

var newstr = String.Join("",str.Where(c=>!char.IsWhiteSpace(c)));

WhiteSpace chars : 0009 , 000a , 000b , 000c , 000d , 0020 , 0085 , 00a0 , 1680 , 180e , 2000 , 2001 , 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 200a , 2028 , 2029 , 202f , 205f , 3000.

MySQL select one column DISTINCT, with corresponding other columns

Keep in mind when using the group by and order by that MySQL is the ONLY database that allows for columns to be used in the group by and/or order by piece that are not part of the select statement.

So for example: select column1 from table group by column2 order by column3

That will not fly in other databases like Postgres, Oracle, MSSQL, etc. You would have to do the following in those databases

select column1, column2, column3 from table group by column2 order by column3

Just some info in case you ever migrate your current code to another database or start working in another database and try to reuse code.

Cannot read property 'addEventListener' of null

This is because the element hadn't been loaded at the time when the bundle js was being executed.

I'd move the <script src="sample.js" type="text/javascript"></script> to the very bottom of the index.html file. This way you can ensure script is executed after all the html elements have been parsed and rendered .

How do you get the file size in C#?

If you have already a file path as input, this is the code you need:

long length = new System.IO.FileInfo(path).Length;

How to determine the content size of a UIWebView?

This's weird!

I tested the solutions both sizeThatFits: and [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] are NOT working for me.

However, I found an interesting easy way to get the right height of webpage content. Currently, I used it in my delegate method scrollViewDidScroll:.

CGFloat contentHeight = scrollView.contentSize.height - CGRectGetHeight(scrollView.frame);

Verified in iOS 9.3 Simulator/Device, good luck!

EDIT:

Background: The html content is calculated by my string variable and HTTP content template, loaded by method loadHTMLString:baseURL:, no registered JS scripts there.

Can a for loop increment/decrement by more than one?

for (var i = 0; i < 10; i = i + 2) {
    // code here
}?

printf format specifiers for uint32_t and size_t

If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t or uintmax_t and use "%jd" or %ju, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t.

How to set environment variables in Python?

os.environ behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get and set operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.

Python 3

For python 3, dictionaries use the in keyword instead of has_key

>>> import os
>>> 'HOME' in os.environ  # Check an existing env. variable
True
...

Python 2

>>> import os
>>> os.environ.has_key('HOME')  # Check an existing env. variable
True
>>> os.environ.has_key('FOO')   # Check for a non existing variable
False
>>> os.environ['FOO'] = '1'     # Set a new env. variable (String value)
>>> os.environ.has_key('FOO')
True
>>> os.environ.get('FOO')       # Retrieve the value
'1'

There is one important thing to note about using os.environ:

Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ again will not reflect the latest values.

Excerpt from the docs:

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

os.environ.data which stores all the environment variables, is a dict object, which contains all the environment values:

>>> type(os.environ.data)  # changed to _data since v3.2 (refer comment below)
<type 'dict'>

Django Template Variables and Javascript

The {{variable}} is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.

Having said that, you can put this kind of substitution into your JavaScript.

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}";
</script>

This gives you "dynamic" javascript.

Getting each individual digit from a whole integer

Usually, this problem resolve with using the modulo of a number in a loop or convert a number to a string. For convert a number to a string, you may can use the function itoa, so considering the variant with the modulo of a number in a loop.


Content of a file get_digits.c

$ cat get_digits.c 

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


// return a length of integer
unsigned long int get_number_count_digits(long int number);

// get digits from an integer number into an array
int number_get_digits(long int number, int **digits, unsigned int *len);

// for demo features
void demo_number_get_digits(long int number);


int
main()
{
    demo_number_get_digits(-9999999999999);
    demo_number_get_digits(-10000000000);
    demo_number_get_digits(-1000);
    demo_number_get_digits(-9);
    demo_number_get_digits(0);
    demo_number_get_digits(9);
    demo_number_get_digits(1000);
    demo_number_get_digits(10000000000);
    demo_number_get_digits(9999999999999);
    return EXIT_SUCCESS;
}


unsigned long int
get_number_count_digits(long int number)
{
    if (number < 0)
        number = llabs(number);
    else if (number == 0)
        return 1;

    if (number < 999999999999997)
        return floor(log10(number)) + 1;

    unsigned long int count = 0;
    while (number > 0) {
        ++count;
        number /= 10;
    }
    return count;
}


int
number_get_digits(long int number, int **digits, unsigned int *len)
{
    number = labs(number);

    // termination count digits and size of a array as well as
    *len = get_number_count_digits(number);

    *digits = realloc(*digits, *len * sizeof(int));

    // fill up the array
    unsigned int index = 0;
    while (number > 0) {
        (*digits)[index] = (int)(number % 10);
        number /= 10;
        ++index;
    }

    // reverse the array
    unsigned long int i = 0, half_len = (*len / 2);
    int swap;
    while (i < half_len) {
        swap = (*digits)[i];
        (*digits)[i] = (*digits)[*len - i - 1];
        (*digits)[*len - i - 1] = swap;
         ++i;
    }

    return 0;
}


void
demo_number_get_digits(long int number)
{
    int *digits;
    unsigned int len;

    digits = malloc(sizeof(int));

    number_get_digits(number, &digits, &len);

    printf("%ld --> [", number);
    for (unsigned int i = 0; i < len; ++i) {
        if (i == len - 1)
            printf("%d", digits[i]);
        else
            printf("%d, ", digits[i]);
    }
    printf("]\n");

    free(digits);
}

Demo with the GNU GCC

$~/Downloads/temp$ cc -Wall -Wextra -std=c11 -o run get_digits.c -lm
$~/Downloads/temp$ ./run
-9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
-10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-1000 --> [1, 0, 0, 0]
-9 --> [9]
0 --> [0]
9 --> [9]
1000 --> [1, 0, 0, 0]
10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

Demo with the LLVM/Clang

$~/Downloads/temp$ rm run
$~/Downloads/temp$ clang -std=c11 -Wall -Wextra get_digits.c -o run -lm
setivolkylany$~/Downloads/temp$ ./run
-9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
-10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-1000 --> [1, 0, 0, 0]
-9 --> [9]
0 --> [0]
9 --> [9]
1000 --> [1, 0, 0, 0]
10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

Testing environment

$~/Downloads/temp$ cc --version | head -n 1
cc (Debian 4.9.2-10) 4.9.2
$~/Downloads/temp$ clang --version
Debian clang version 3.5.0-10 (tags/RELEASE_350/final) (based on LLVM 3.5.0)
Target: x86_64-pc-linux-gnu
Thread model: posix

AngularJS: factory $http.get JSON file

I have approximately these problem. I need debug AngularJs application from Visual Studio 2013.

By default IIS Express restricted access to local files (like json).

But, first: JSON have JavaScript syntax.

Second: javascript files is allowed.

So:

  1. rename JSON to JS (data.json->data.js).

  2. correct load command ($http.get('App/data.js').success(function (data) {...

  3. load script data.js to page (<script src="App/data.js"></script>)

Next use loaded data an usual manner. It is just workaround, of course.

Detect & Record Audio in Python

As a follow up to Nick Fortescue's answer, here's a more complete example of how to record from the microphone and process the resulting data:

from sys import byteorder
from array import array
from struct import pack

import pyaudio
import wave

THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100

def is_silent(snd_data):
    "Returns 'True' if below the 'silent' threshold"
    return max(snd_data) < THRESHOLD

def normalize(snd_data):
    "Average the volume out"
    MAXIMUM = 16384
    times = float(MAXIMUM)/max(abs(i) for i in snd_data)

    r = array('h')
    for i in snd_data:
        r.append(int(i*times))
    return r

def trim(snd_data):
    "Trim the blank spots at the start and end"
    def _trim(snd_data):
        snd_started = False
        r = array('h')

        for i in snd_data:
            if not snd_started and abs(i)>THRESHOLD:
                snd_started = True
                r.append(i)

            elif snd_started:
                r.append(i)
        return r

    # Trim to the left
    snd_data = _trim(snd_data)

    # Trim to the right
    snd_data.reverse()
    snd_data = _trim(snd_data)
    snd_data.reverse()
    return snd_data

def add_silence(snd_data, seconds):
    "Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
    silence = [0] * int(seconds * RATE)
    r = array('h', silence)
    r.extend(snd_data)
    r.extend(silence)
    return r

def record():
    """
    Record a word or words from the microphone and 
    return the data as an array of signed shorts.

    Normalizes the audio, trims silence from the 
    start and end, and pads with 0.5 seconds of 
    blank sound to make sure VLC et al can play 
    it without getting chopped off.
    """
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=1, rate=RATE,
        input=True, output=True,
        frames_per_buffer=CHUNK_SIZE)

    num_silent = 0
    snd_started = False

    r = array('h')

    while 1:
        # little endian, signed short
        snd_data = array('h', stream.read(CHUNK_SIZE))
        if byteorder == 'big':
            snd_data.byteswap()
        r.extend(snd_data)

        silent = is_silent(snd_data)

        if silent and snd_started:
            num_silent += 1
        elif not silent and not snd_started:
            snd_started = True

        if snd_started and num_silent > 30:
            break

    sample_width = p.get_sample_size(FORMAT)
    stream.stop_stream()
    stream.close()
    p.terminate()

    r = normalize(r)
    r = trim(r)
    r = add_silence(r, 0.5)
    return sample_width, r

def record_to_file(path):
    "Records from the microphone and outputs the resulting data to 'path'"
    sample_width, data = record()
    data = pack('<' + ('h'*len(data)), *data)

    wf = wave.open(path, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(sample_width)
    wf.setframerate(RATE)
    wf.writeframes(data)
    wf.close()

if __name__ == '__main__':
    print("please speak a word into the microphone")
    record_to_file('demo.wav')
    print("done - result written to demo.wav")

Phonegap + jQuery Mobile, real world sample or tutorial

you may check this website: Phonegap RSS feeds, Javascript, this is an example about rss reader which uses the phonegap and jquery-mobile techniques

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Proper way to wait for one function to finish before continuing?

Your main fun will call firstFun then on complete of it your next fun will call.

async firstFunction() {
            const promise = new Promise((resolve, reject) => {
                for (let i = 0; i < 5; i++) {
                    // do something
                    console.log(i);
                    if (i == 4) {
                        resolve(i);
                    }
                }
            });
            const result = await promise;
        }

        second() {
            this.firstFunction().then( res => {
                // third function call do something
                console.log('Gajender here');
            });
        }

How to find list of possible words from a letter matrix [Boggle Solver]

I suggest making a tree of letters based on words. The tree would be composed of a letter structs, like this:

letter: char
isWord: boolean

Then you build up the tree, with each depth adding a new letter. In other words, on the first level there'd be the alphabet; then from each of those trees, there'd be another another 26 entries, and so on, until you've spelled out all the words. Hang onto this parsed tree, and it'll make all possible answers faster to look up.

With this parsed tree, you can very quickly find solutions. Here's the pseudo-code:

BEGIN: 
    For each letter:
        if the struct representing it on the current depth has isWord == true, enter it as an answer.
        Cycle through all its neighbors; if there is a child of the current node corresponding to the letter, recursively call BEGIN on it.

This could be sped up with a bit of dynamic programming. For example, in your sample, the two 'A's are both next to an 'E' and a 'W', which (from the point they hit them on) would be identical. I don't have enough time to really spell out the code for this, but I think you can gather the idea.

Also, I'm sure you'll find other solutions if you Google for "Boggle solver".

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I am trying to avoid using VBA. But if has to be, then it has to be:)

There is quite simple UDF for you:

Function myCountIf(rng As Range, criteria) As Long
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
    Next ws
End Function

and call it like this: =myCountIf(I:I,A13)


P.S. if you'd like to exclude some sheets, you can add If statement:

Function myCountIf(rng As Range, criteria) As Long
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.name <> "Sheet1" And ws.name <> "Sheet2" Then
            myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
        End If
    Next ws
End Function

UPD:

I have four "reference" sheets that I need to exclude from being scanned/searched. They are currently the last four in the workbook

Function myCountIf(rng As Range, criteria) As Long
    Dim i As Integer

    For i = 1 To ThisWorkbook.Worksheets.Count - 4
        myCountIf = myCountIf + WorksheetFunction.CountIf(ThisWorkbook.Worksheets(i).Range(rng.Address), criteria)
    Next i
End Function

JSON to pandas DataFrame

billmanH's solution helped me but didn't work until i switched from:

n = data.loc[row,'json_column']

to:

n = data.iloc[[row]]['json_column']

here's the rest of it, converting to a dictionary is helpful for working with json data.

import json

for row in range(len(data)):
    n = data.iloc[[row]]['json_column'].item()
    jsonDict = json.loads(n)
    if ('mykey' in jsonDict):
        display(jsonDict['mykey'])

Android ImageButton with a selected state?

ToggleImageButton which implements Checkable interface and supports OnCheckedChangeListener and android:checked xml attribute:

public class ToggleImageButton extends ImageButton implements Checkable {
    private OnCheckedChangeListener onCheckedChangeListener;

    public ToggleImageButton(Context context) {
        super(context);
    }

    public ToggleImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        setChecked(attrs);
    }

    public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setChecked(attrs);
    }

    private void setChecked(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
        setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
        a.recycle();
    }

    @Override
    public boolean isChecked() {
        return isSelected();
    }

    @Override
    public void setChecked(boolean checked) {
        setSelected(checked);

        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(this, checked);
        }
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
    }

    @Override
    public boolean performClick() {
        toggle();
        return super.performClick();
    }

    public OnCheckedChangeListener getOnCheckedChangeListener() {
        return onCheckedChangeListener;
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    public static interface OnCheckedChangeListener {
        public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
    }
}

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ToggleImageButton">
        <attr name="android:checked" />
    </declare-styleable>
</resources>

Angular ui-grid dynamically calculate height of the grid

.ui-grid, .ui-grid-viewport,.ui-grid-contents-wrapper, .ui-grid-canvas { height: auto !important; }

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

It happened with me when I changed the instance type of my AWS server.

#2002 Cannot log in to the MySQL server can also occur when the mysqld service is not started.

So first of all you need to execute :

$ sudo service mysqld restart

This will give you :

$ sudo service mysqld restart
Stopping mysqld:                                           [  OK  ]
Starting mysqld:                                           [  OK  ]

After that the error will not come.

P.S. On EC2 instances, one should also change the host from localhost to 127.0.0.1 as mentioned in the top answer.

How to store images in mysql database using php

if(isset($_POST['form1']))
{
    try
    {


        $user=$_POST['username'];

        $pass=$_POST['password'];
        $email=$_POST['email'];
        $roll=$_POST['roll'];
        $class=$_POST['class'];



        if(empty($user)) throw new Exception("Name can not empty");
        if(empty($pass)) throw new Exception("Password can not empty");
        if(empty($email)) throw new Exception("Email can not empty");
        if(empty($roll)) throw new Exception("Roll can not empty");
        if(empty($class)) throw new Exception("Class can not empty");


        $statement=$db->prepare("show table status like 'tbl_std_info'");
        $statement->execute();
        $result=$statement->fetchAll();
        foreach($result as $row)
        $new_id=$row[10];


        $up_file=$_FILES["image"]["name"];

        $file_basename=substr($up_file, 0 , strripos($up_file, "."));
        $file_ext=substr($up_file, strripos($up_file, ".")); 
        $f1="$new_id".$file_ext;

        if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
        {
            throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
        }
        move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);


        $statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");

        $statement->execute(array($user,$f1,$pass,$email,$roll,$class));


        $success="Registration Successfully Completed";

        echo $success;
    }
    catch(Exception $e)
    {
        $msg=$e->getMessage();
    }
}

How to resize a custom view programmatically?

With Kotlin and using dp unit:

myView.updateLayoutParams {
    val pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200f, context.resources.displayMetrics)
    height = pixels.toInt()
}

Installing Java on OS X 10.9 (Mavericks)

I downloaded manually to here: Java for OS X 2014-001.

After that open your terminal and check the installation with java -version.

EDIT (January, 2015): Also see HT202912, About Java for OS X 2014-001:

enter image description here

How to use Bash to create a folder if it doesn't already exist?

Cleaner way, exploit shortcut evaluation of shell logical operators. Right side of the operator is executed only if left side is true.

[ ! -d /home/mlzboy/b2c2/shared/db ] && mkdir -p /home/mlzboy/b2c2/shared/db

Find objects between two dates MongoDB

Using with Moment.js and Comparison Query Operators

  var today = moment().startOf('day');
  // "2018-12-05T00:00:00.00
  var tomorrow = moment(today).endOf('day');
  // ("2018-12-05T23:59:59.999

  Example.find(
  {
    // find in today
    created: { '$gte': today, '$lte': tomorrow }
    // Or greater than 5 days
    // created: { $lt: moment().add(-5, 'days') },
  }), function (err, docs) { ... });

Show spinner GIF during an $http request in AngularJS?

If you're wrapping your api calls within a service/factory, then you can track the loading counter there (per answer and excellent simultaneous suggestion by @JMaylin), and reference the loading counter via a directive. Or any combination thereof.

API WRAPPER

yourModule
    .factory('yourApi', ['$http', function ($http) {
        var api = {}

        //#region ------------ spinner -------------

        // ajax loading counter
        api._loading = 0;

        /**
         * Toggle check
         */
        api.isOn = function () { return api._loading > 0; }

        /**
         * Based on a configuration setting to ignore the loading spinner, update the loading counter
         * (for multiple ajax calls at one time)
         */
        api.spinner = function(delta, config) {
            // if we haven't been told to ignore the spinner, change the loading counter
            // so we can show/hide the spinner

            if (NG.isUndefined(config.spin) || config.spin) api._loading += delta;

            // don't let runaway triggers break stuff...
            if (api._loading < 0) api._loading = 0;

            console.log('spinner:', api._loading, delta);
        }
        /**
         * Track an ajax load begin, if not specifically disallowed by request configuration
         */
        api.loadBegin = function(config) {
            api.spinner(1, config);
        }
        /**
         * Track an ajax load end, if not specifically disallowed by request configuration
         */
        api.loadEnd = function (config) {
            api.spinner(-1, config);
        }

        //#endregion ------------ spinner -------------

        var baseConfig = {
            method: 'post'
            // don't need to declare `spin` here
        }

        /**
         * $http wrapper to standardize all api calls
         * @param args stuff sent to request
         * @param config $http configuration, such as url, methods, etc
         */
        var callWrapper = function(args, config) {
            var p = angular.extend(baseConfig, config); // override defaults

            // fix for 'get' vs 'post' param attachment
            if (!angular.isUndefined(args)) p[p.method == 'get' ? 'params' : 'data'] = args;

            // trigger the spinner
            api.loadBegin(p);

            // make the call, and turn of the spinner on completion
            // note: may want to use `then`/`catch` instead since `finally` has delayed completion if down-chain returns more promises
            return $http(p)['finally'](function(response) {
                api.loadEnd(response.config);
                return response;
            });
        }

        api.DoSomething = function(args) {
            // yes spinner
            return callWrapper(args, { cache: true });
        }
        api.DoSomethingInBackground = function(args) {
            // no spinner
            return callWrapper(args, { cache: true, spin: false });
        }

        // expose
        return api;
    });

SPINNER DIRECTIVE

(function (NG) {
    var loaderTemplate = '<div class="ui active dimmer" data-ng-show="hasSpinner()"><div class="ui large loader"></div></div>';

    /**
     * Show/Hide spinner with ajax
     */
    function spinnerDirective($compile, api) {
        return {
            restrict: 'EA',
            link: function (scope, element) {
                // listen for api trigger
                scope.hasSpinner = api.isOn;

                // attach spinner html
                var spin = NG.element(loaderTemplate);
                $compile(spin)(scope); // bind+parse
                element.append(spin);
            }
        }
    }

    NG.module('yourModule')
        .directive('yourApiSpinner', ['$compile', 'yourApi', spinnerDirective]);
})(angular);

USAGE

<div ng-controller="myCtrl" your-api-spinner> ... </div>

Difference between DataFrame, Dataset, and RDD in Spark

Most of answers are correct only want to add one point here

In Spark 2.0 the two APIs (DataFrame +DataSet) will be unified together into a single API.

"Unifying DataFrame and Dataset: In Scala and Java, DataFrame and Dataset have been unified, i.e. DataFrame is just a type alias for Dataset of Row. In Python and R, given the lack of type safety, DataFrame is the main programming interface."

Datasets are similar to RDDs, however, instead of using Java serialization or Kryo they use a specialized Encoder to serialize the objects for processing or transmitting over the network.

Spark SQL supports two different methods for converting existing RDDs into Datasets. The first method uses reflection to infer the schema of an RDD that contains specific types of objects. This reflection based approach leads to more concise code and works well when you already know the schema while writing your Spark application.

The second method for creating Datasets is through a programmatic interface that allows you to construct a schema and then apply it to an existing RDD. While this method is more verbose, it allows you to construct Datasets when the columns and their types are not known until runtime.

Here you can find RDD tof Data frame conversation answer

How to convert rdd object to dataframe in spark

Redeploy alternatives to JRebel

Take a look at DCEVM, it's a modification of the HotSpot VM that allows unlimited class redefinitions at runtime. You can add/remove fields and methods and change the super types of a class at runtime.

The binaries available on the original site are limited to Java 6u25 and to early versions of Java 7. The project has been forked on Github and supports recent versions of Java 7 and 8. The maintainer provides binaries for 32/64 bits VMs on Windows/Linux. Starting with Java 11 the project moved to a new GitHub repository and now also provides binaries for OS X.

DCEVM is packaged for Debian and Ubuntu, it's conveniently integrated with OpenJDK and can be invoked with java -dcevm. The name of the package depends on the version of the default JDK:

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

How to compare type of an object in Python?

You're very close! string is a module, not a type. You probably want to compare the type of obj against the type object for strings, namely str:

type(obj) == str  # this works because str is already a type

Alternatively:

type(obj) == type('')

Note, in Python 2, if obj is a unicode type, then neither of the above will work. Nor will isinstance(). See John's comments to this post for how to get around this... I've been trying to remember it for about 10 minutes now, but was having a memory block!

How to send an email using PHP?

using PHP built in function mail()

more info from : https://www.php.net/manual/en/function.mail.php

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

  • The ownership of the relation is determined by where you place the 'mappedBy' attribute to the annotation. The entity you put 'mappedBy' is the one which is NOT the owner. There's no chance for both sides to be owners. If you don't have a 'delete user' use-case you could simply move the ownership to the Group entity, as currently the User is the owner.
  • On the other hand, you haven't been asking about it, but one thing worth to know. The groups and users are not combined with each other. I mean, after deleting User1 instance from Group1.users, the User1.groups collections is not changed automatically (which is quite surprising for me),
  • All in all, I would suggest you decide who is the owner. Let say the User is the owner. Then when deleting a user the relation user-group will be updated automatically. But when deleting a group you have to take care of deleting the relation yourself like this:

entityManager.remove(group)
for (User user : group.users) {
     user.groups.remove(group);
}
...
// then merge() and flush()

VS 2012: Scroll Solution Explorer to current file

If you need one-off sync with the solution pane, then there is new command "Sync with Active Document" (default shortcut: Ctrl+[, S). Explained here: Visual Studio 2012 New Features: Solution Explorer

Elastic Search: how to see the indexed data

Kibana is also a good solution. It is a data visualization platform for Elastic.If installed it runs by default on port 5601.

Out of the many things it provides. It has "Dev Tools" where we can do your debugging.

For example you can check your available indexes here using the command

GET /_cat/indices

Use of var keyword in C#

I think you may be misunderstanding the usage of var in C#. It is still strong typing, unlike the VB varient type so there is no performance hit from using it or not.

Since there is no effect on the final compiled code it really is a stylist choice. Personally I don't use it since I find the code easier to read with the full types defined, but I can imagine a couple of years down the line that full type declaration will be looked at in the same way as Hungarian notation is now - extra typing for no real benefit over the information that intellisense gives us by default.

Is it possible to style html5 audio tag?

Yes: you can hide the built-in browser UI (by removing the controls attribute from audio) and instead build your own interface and control the playback using Javascript (source):

<audio id="player" src="vincent.mp3"></audio>
<div> 
  <button onclick="document.getElementById('player').play()">Play</button> 
  <button onclick="document.getElementById('player').pause()">Pause</button> 
  <button onclick="document.getElementById('player').volume += 0.1">Vol +</button> 
  <button onclick="document.getElementById('player').volume -= 0.1">Vol -</button> 
</div>

You can then style the elements however you wish using CSS.

MDN HTMLAudioElement API reference

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

What is the default value for enum variable?

It is whatever member of the enumeration represents the value 0. Specifically, from the documentation:

The default value of an enum E is the value produced by the expression (E)0.

As an example, take the following enum:

enum E
{
    Foo, Bar, Baz, Quux
}

Without overriding the default values, printing default(E) returns Foo since it's the first-occurring element.

However, it is not always the case that 0 of an enum is represented by the first member. For example, if you do this:

enum F
{
    // Give each element a custom value
    Foo = 1, Bar = 2, Baz = 3, Quux = 0
}

Printing default(F) will give you Quux, not Foo.

If none of the elements in an enum G correspond to 0:

enum G
{
    Foo = 1, Bar = 2, Baz = 3, Quux = 4
}

default(G) returns literally 0, although its type remains as G (as quoted by the docs above, a cast to the given enum type).

Video 100% width and height

Easiest & Responsive.

<video src="full.mp4" autoplay muted loop></video>

<style>
    video {
        height: 100vh;
        width: 100%;
        object-fit: fill; // use "cover" to avoid distortion
        position: absolute;
    }
</style>

jQuery - Detecting if a file has been selected in the file input

I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs

Generate a dummy-variable

Another way is to use mtabulate from qdapTools package, i.e.

df <- data.frame(var = sample(c("A", "B", "C"), 5, replace = TRUE))
  var
#1   C
#2   A
#3   C
#4   B
#5   B

library(qdapTools)
mtabulate(df$var)

which gives,

  A B C
1 0 0 1
2 1 0 0
3 0 0 1
4 0 1 0
5 0 1 0

Entity Framework Refresh context?

yourContext.Entry(yourEntity).Reload();

How to normalize a signal to zero mean and unit variance?

If you have the stats toolbox, then you can compute

Z = zscore(S);

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

"Could not find a valid gem in any repository" (rubygame and others)

are you behind any proxy?

check your browser for proxy that you might use:

execute the command: gem install xxx --http-proxy=http://user:password@server and you should be good to go.

Adding form action in html in laravel

You need to set a name to your Routes. Like this:


    Route::get('/','WelcomeController@home')->name('welcome.home');
    Route::post('/', array('as' => 'log_in', 'uses' => 'WelcomeController@log_in'))->name('welcome.log_in');
    Route::get('home', 'HomeController@index')->name('home.index');

I just put name on Routes that need this. In my case, to call from tag form at blade template. Like this:

<form action="{{ route('home.index') }}" >

Or, You can do this:

<form action="/" >

hibernate could not get next sequence value

The Database that we are using should be mentioned under search_path in Postgres SQL Configuration file. This can be done by editing Postgressql configuration file by setting search_path along with database name for example: TESTDB.

  1. Find postgressql.conf file under data folder of Postgres SQL datbase.
  2. Set search_path = "$user", public, TESTDB;
  3. Restart the Postgres SQL service to affect the change.

It worked for me after making the above change.

Numeric for loop in Django templates

Unfortunately, that's not supported in the Django template language. There are a couple of suggestions, but they seem a little complex. I would just put a variable in the context:

...
render_to_response('foo.html', {..., 'range': range(10), ...}, ...)
...

and in the template:

{% for i in range %}
     ...
{% endfor %}

How do I call a Django function on button click?

The following answer could be helpful for the first part of your question:

Django: How can I call a view function from template?

Aligning a float:left div to center?

try it like this:

  <div id="divContainer">
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <br class="clear" />
    </div>

    <style type="text/css">
    #divContainer { margin: 0 auto; width: 800px; }
    .divImageHolder { float:left; }
    .clear { clear:both; }
    </style>

jQuery check if it is clicked or not

Alright, before I go into the solution, lets be on the same line about this one fact: Javascript is Event Based. So you'll usually have to setup callbacks to be able to do procedures.

Based on your comment I assumed you have a trigger that will do the logic that launched the function depending if the element is clicked; for sake of demonstration I made it a "submit button"; but this can be a timer or something else.

var the_action = function(type) {
    switch(type) {
        case 'a':
            console.log('Case A');
            break;
         case 'b':
            console.log('Case B');
            break;
    }
};

$('.clickme').click(function() { 
    console.log('Clicked');
    $(this).data('clicked', true);
});

$('.submit').click(function() {
    // All your logic can go here if you want.
    if($('.clickme').data('clicked') == true) {
        the_action('a');
    } else {
        the_action('b');
    }
});

Live Example: http://jsfiddle.net/kuroir/6MCVJ/

What is the difference between printf() and puts() in C?

When comparing puts() and printf(), even though their memory consumption is almost the same, puts() takes more time compared to printf().

Format certain floating dataframe columns into percentage in pandas

As a similar approach to the accepted answer that might be considered a bit more readable, elegant, and general (YMMV), you can leverage the map method:

# OP example
df['var3'].map(lambda n: '{:,.2%}'.format(n))

# also works on a series
series_example.map(lambda n: '{:,.2%}'.format(n))

Performance-wise, this is pretty close (marginally slower) than the OP solution.

As an aside, if you do choose to go the pd.options.display.float_format route, consider using a context manager to handle state per this parallel numpy example.

How to use UIPanGestureRecognizer to move object? iPhone/iPad

-(IBAction)Method
{
      UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
      [panRecognizer setMinimumNumberOfTouches:1];
      [panRecognizer setMaximumNumberOfTouches:1];
      [ViewMain addGestureRecognizer:panRecognizer];
      [panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{

     CGPoint translation = [recognizer translationInView:self.view];
     recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
                                     recognizer.view.center.y + translation.y);
     [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

     if (recognizer.state == UIGestureRecognizerStateEnded) {

         CGPoint velocity = [recognizer velocityInView:self.view];
         CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
         CGFloat slideMult = magnitude / 200;
         NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

         float slideFactor = 0.1 * slideMult; // Increase for more of a slide
         CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor), 
                                     recognizer.view.center.y + (velocity.y * slideFactor));
         finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
         finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);

         [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
             recognizer.view.center = finalPoint;
         } completion:nil];

    }

}

How many bytes is unsigned long long?

Use the operator sizeof, it will give you the size of a type expressed in byte. One byte is eight bits. See the following program:

#include <iostream>

int main(int,char**)
{
 std::cout << "unsigned long long " << sizeof(unsigned long long) << "\n";
 std::cout << "unsigned long long int " << sizeof(unsigned long long int) << "\n";
 return 0;
}

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

How to close a GUI when I push a JButton?

You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.

The System.exit(0) will terminates the currently running Java Virtual Machine.

How to center links in HTML

Since you have a list of links, you should be marking them up as a list (and not as paragraphs).

Listamatic has a bunch of examples of how you can style lists of links, including a number that are vertical lists with each link being centred (which is what you appear to be after). It also has a tutorial which explains the principles.

That part of the styling essentially boils down to "Set text-align: center on an element that is displaying as a block which contains the link text" (that could be the anchor itself (if you make it display as a block) or the list item containing it.

Switch role after connecting to database

--create a user that you want to use the database as:

create role neil;

--create the user for the web server to connect as:

create role webgui noinherit login password 's3cr3t';

--let webgui set role to neil:

grant neil to webgui; --this looks backwards but is correct.

webgui is now in the neil group, so webgui can call set role neil . However, webgui did not inherit neil's permissions.

Later, login as webgui:

psql -d some_database -U webgui
(enter s3cr3t as password)

set role neil;

webgui does not need superuser permission for this.

You want to set role at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:

public class SetRoleJdbcInterceptor extends JdbcInterceptor {

    @Override
    public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(authentication != null) {
            try {

                /* 
                  use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.

                  Or use a whitelist-map approach
                */
                String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());

                Statement statement = pooledConnection.getConnection().createStatement();
                statement.execute("set role \"" + username + "\"");
                statement.close();
            } catch(SQLException exp){
                throw new RuntimeException(exp);
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("close".equals(method.getName())){
            Statement statement = ((Connection)proxy).createStatement();
            statement.execute("reset role");
            statement.close();
        }

        return super.invoke(proxy, method, args);
    }
}

ActiveXObject creation error " Automation server can't create object"

This is caused by Security settings for internet explorer. You can fix this,by changing internet explorer settings.Go To Settings->Internet Options->Security Tabs. You will see different zones:i)Internet ii)Local Intranet iii)Trusted Sites iv)Restricted Sites. Depending on your requirement select one zone. I am running my application in localhost so i selected Local intranet and then click Custom Level button. It opens security settings window. Please enable Initialize and script Activex controls not marked as safe for scripting option.It should work.

enter image description here

enter image description here

How to create a hex dump of file containing only the hex characters without spaces in bash?

It seems to depend on the details of the version of od. On OSX, use this:

od -t x1 -An file |tr -d '\n '

(That's print as type hex bytes, with no address. And whitespace deleted afterwards, of course.)

How to make a JFrame Modal in Swing java

You can create a class that is passed a reference to the parent JFrame and holds it in a JFrame variable. Then you can lock the frame that created your new frame.

parentFrame.disable();

//Some actions

parentFrame.enable();

<code> vs <pre> vs <samp> for inline and block code snippets

Consider Prism.js: https://prismjs.com/#examples

It makes <pre><code> work and is attractive.

Difference between PACKETS and FRAMES

Actually, there are five words commonly used when we talk about layers of reference models (or protocol stacks): data, segment, packet, frame and bit. And the term PDU (Protocol Data Unit) is used to refer to the packets in different layers of the OSI model. Thus PDU gives an abstract idea of the data packets. The PDU has a different meaning in different layers still we can use it as a common term.

When we come to your question, we can call all of them by using the general term PDU, but if you want to call them specifically at a given layer:

  • Data: PDU of Application, Presentation and Session Layers
  • Segment: PDU of Transport Layer
  • Packet: PDU of network Layer
  • Frame: PDU of data-link Layer
  • Bit: PDU of physical Layer

Here is a diagram, since a picture is worth a thousand words: a picture is worth a thousand words

String.Format for Hex

More generally.

byte[] buf = new byte[] { 123, 2, 233 };

string s = String.Concat(buf.Select(b => b.ToString("X2")));

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

Xcopy exit code 4 means "Initialization error occurred. There is not enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line."

It looks like Visual Studio is supplying invalid arguments to xcopy. Check your post-build event command via Project > Right Click > Properties > Build Events > Post Build Event.

Note that if the $(ProjectDir) or similar macro terms have spaces in the resulting paths when expanded, then they will need to be wrapped in double quotes. For example:

xcopy "$(ProjectDir)Library\dsoframer.ocx" "$(TargetDir)" /Y /E /D1

How to change Vagrant 'default' machine name?

Yes, for Virtualbox provider do something like this:

Vagrant.configure("2") do |config|
    # ...other options...
    config.vm.provider "virtualbox" do |p|
        p.name = "something-else"
    end
end

how to check for datatype in node js- specifically for integer

I just made some tests in node.js v4.2.4 (but this is true in any javascript implementation):

> typeof NaN
'number'
> isNaN(NaN)
true
> isNaN("hello")
true

the surprise is the first one as type of NaN is "number", but that is how it is defined in javascript.

So the next test brings up unexpected result

> typeof Number("hello")
"number"

because Number("hello") is NaN

The following function makes results as expected:

function isNumeric(n){
  return (typeof n == "number" && !isNaN(n));
}

Git merge errors

as suggested in git status,

Unmerged paths:                                                                                                                                
(use "git add <file>..." to mark resolution)                                                                                                 

    both modified:   a.jl                                  
    both modified:   b.jl

I used git add to finish the merging, then git checkout works fine.

What's the best way to get the current URL in Spring MVC?

Java's URI Class can help you out of this:

public static String getCurrentUrl(HttpServletRequest request){
    URL url = new URL(request.getRequestURL().toString());
    String host  = url.getHost();
    String userInfo = url.getUserInfo();
    String scheme = url.getProtocol();
    String port = url.getPort();
    String path = request.getAttribute("javax.servlet.forward.request_uri");
    String query = request.getAttribute("javax.servlet.forward.query_string");

    URI uri = new URI(scheme,userInfo,host,port,path,query,null)
    return uri.toString();
}

How to remove old and unused Docker images

If you wish to automatically/periodically clean up exited containers and remove images and volumes that aren't in use by a running container you can download the image meltwater/docker-cleanup.

Just run:

docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw  -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest

It runs every 30 minutes by default. You can however set the delay time by using this flag in seconds (DELAY_TIME=1800 option).

More details: https://github.com/meltwater/docker-cleanup/blob/master/README.md

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

See the docs for num.toStringAsFixed().

String toStringAsFixed(int fractionDigits)

Returns a decimal-point string-representation of this.

Converts this to a double before computing the string representation.

  • If the absolute value of this is greater or equal to 10^21 then this methods returns an exponential representation computed by this.toStringAsExponential().

Examples:

1000000000000000000000.toStringAsExponential(3); // 1.000e+21
  • Otherwise the result is the closest string representation with exactly fractionDigits digits after the decimal point. If fractionDigits equals 0 then the decimal point is omitted.

The parameter fractionDigits must be an integer satisfying: 0 <= fractionDigits <= 20.

Examples:

1.toStringAsFixed(3);  // 1.000
(4321.12345678).toStringAsFixed(3);  // 4321.123
(4321.12345678).toStringAsFixed(5);  // 4321.12346
123456789012345678901.toStringAsFixed(3);  // 123456789012345683968.000
1000000000000000000000.toStringAsFixed(3); // 1e+21
5.25.toStringAsFixed(0); // 5

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

Normalize data in pandas

You can use apply for this, and it's a bit neater:

import numpy as np
import pandas as pd

np.random.seed(1)

df = pd.DataFrame(np.random.randn(4,4)* 4 + 3)

          0         1         2         3
0  9.497381  0.552974  0.887313 -1.291874
1  6.461631 -6.206155  9.979247 -0.044828
2  4.276156  2.002518  8.848432 -5.240563
3  1.710331  1.463783  7.535078 -1.399565

df.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

          0         1         2         3
0  0.515087  0.133967 -0.651699  0.135175
1  0.125241 -0.689446  0.348301  0.375188
2 -0.155414  0.310554  0.223925 -0.624812
3 -0.484913  0.244924  0.079473  0.114448

Also, it works nicely with groupby, if you select the relevant columns:

df['grp'] = ['A', 'A', 'B', 'B']

          0         1         2         3 grp
0  9.497381  0.552974  0.887313 -1.291874   A
1  6.461631 -6.206155  9.979247 -0.044828   A
2  4.276156  2.002518  8.848432 -5.240563   B
3  1.710331  1.463783  7.535078 -1.399565   B


df.groupby(['grp'])[[0,1,2,3]].apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

     0    1    2    3
0  0.5  0.5 -0.5 -0.5
1 -0.5 -0.5  0.5  0.5
2  0.5  0.5  0.5 -0.5
3 -0.5 -0.5 -0.5  0.5

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Yes. Google Chrome has deprecated the feature in version 50. If you tried to use it in chrome the error is:

getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.

So, you have to add SSL certificate. Well, that's the only way.

And it's quite easy now using Let's Encrypt. Here's guide

And for testing purpose you could try this:

1.localhost is treated as a secure origin over HTTP, so if you're able to run your server from localhost, you should be able to test the feature on that server.

2.You can run chrome with the --unsafely-treat-insecure-origin-as-secure="http://example.com" flag (replacing "example.com" with the origin you actually want to test), which will treat that origin as secure for this session. Note that you also need to include the --user-data-dir=/test/only/profile/dir to create a fresh testing profile for the flag to work.

I think Firefox also restricted user from accessing GeoLocation API requests from http. Here's the webkit changelog: https://trac.webkit.org/changeset/200686

Select where count of one field is greater than one

One way

SELECT t1.* 
FROM db.table t1
WHERE exists 
      (SELECT *
      FROM db.table t2 
      where t1.pk != t2.pk 
      and t1.someField = t2.someField)

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Take a look: https://devanswers.co/problem-php-7-2-phpmyadmin-warning-in-librariessql-count/

Firstly, backup sql.lib.php before editing. Edit sql.lib.php in nano.

$ sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php

Press CTRL + W and search for (count($analyzed_sql_results['select_expr'] == 1)

Replace it with ((count($analyzed_sql_results['select_expr']) == 1)

Save file and exit. (Press CTRL + X, press Y and then press ENTER)

How to install and run Typescript locally in npm?

You need to tell npm that "tsc" exists as a local project package (via the "scripts" property in your package.json) and then run it via npm run tsc. To do that (at least on Mac) I had to add the path for the actual compiler within the package, like this

{
  "name": "foo"
  "scripts": {
    "tsc": "./node_modules/typescript/bin/tsc"
  },
  "dependencies": {
    "typescript": "^2.3.3",
    "typings": "^2.1.1"
  }
}

After that you can run any TypeScript command like npm run tsc -- --init (the arguments come after the first --).

Embed HTML5 YouTube video without iframe?

Yes. Youtube API is the best resource for this.

There are 3 way to embed a video:

  • IFrame embeds using <iframe> tags
  • IFrame embeds using the IFrame Player API
  • AS3 (and AS2*) object embeds DEPRECATED

I think you are looking for the second one of them:

IFrame embeds using the IFrame Player API

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

<div id="ytplayer"></div>

<script>
  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE'
    });
  }
</script>

Here are some instructions where you may take a look when starting using the API.


An embed example without using iframe is to use <object> tag:

<object width="640" height="360">
    <param name="movie" value="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3"/
    <param name="allowFullScreen" value="true"/>
    <param name="allowscriptaccess" value="always"/>
    <embed width="640" height="360" src="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>

(replace yt-video-id with your video id)

JSFIDDLE

Chrome desktop notification example

Notify.js is a wrapper around the new webkit notifications. It works pretty well.

http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To use aliases on eloquent models modify your code like this:

Item
    ::from( 'items as items_alias' )
    ->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
    ->select( DB::raw( 'items_alias.*' ) )
    ->get();

This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result. Adding DB::raw prevents laravel from adding table prefixes to aliases.

"Invalid form control" only in Google Chrome

I had this issue when I had class="hidden" on the input fields because I was using buttons instead of radio bullets - and changing the "active" state via JS..

I simply added an extra radio input field part of the same group where i wanted the msg to appear:

<input type="radio" id="thenorm" name="ppoption" value=""  required style="opacity:0"/>

the other 2 active bullets are invisible, this one isnt and this triggers the validation message and no console errors - bit of a hack but what isnt these days..

Finding blocking/locking queries in MS SQL (mssql)

You may find this query useful:

SELECT * 
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName' 
AND blocking_session_id <> 0

How to get the size of a varchar[n] field in one SQL statement?

I was looking for the TOTAL size of the column and hit this article, my solution is based off of MarcE's.

SELECT sum(DATALENGTH(your_field)) AS FIELDSIZE FROM your_table

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

Simple and easy :

_x000D_
_x000D_
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
  <input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Using margin / padding to space <span> from the rest of the <p>

Add this style to your span:

position:relative; 
top: 10px;

Demo: http://jsfiddle.net/BqTUS/3/

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

Yes the example by nixlike works very well.

Inventory:

[docker-host]
myhost1 user=barbara
myhost2 user=heather

playbook:

---

- hosts: localhost
  connection: local         

     tasks:    
        - name: loop debug inventory hostnames
          debug: 
            msg: "the docker host is {{ item }}"
          with_inventory_hostnames: docker-host
        - name: loop debug items
          debug: 
            msg: "the docker host is {{ hostvars[item]['user'] }}"
          with_items: "{{ groups['docker-host'] }}"

output:

ansible-playbook ansible/tests/vars-test-local.yml

PLAY [localhost]


TASK [setup] ******************************************************************* ok: [localhost]

TASK [loop debug inventory hostnames] ****************************************** ok: [localhost] => (item=myhost2) => { "item": "myhost2", "msg": "the docker host is myhost2" } ok: [localhost] => (item=myhost1) => { "item": "myhost1", "msg": "the docker host is myhost1" }

TASK [loop debug items] ******************************************************** ok: [localhost] => (item=myhost1) => { "item": "myhost1", "msg": "the docker host is barbara" } ok: [localhost] => (item=myhost2) => { "item": "myhost2", "msg": "the docker host is heather" }

PLAY RECAP ********************************************************************* localhost : ok=3 changed=0 unreachable=0
failed=0

thanks!

Error Message : Cannot find or open the PDB file

I'm also a newbie to CUDA/Visual studio and encountered the same problem with a couple of the samples. If you run DEBUG-> Start Debugging, then repeatedly step over (F10) you'll see the output window appear and get populated. Normal execution returns nomal completion status 0x0 (as you observed) and the output window is closed.

Android Studio - Failed to apply plugin [id 'com.android.application']

First of all, before trying the most complicated things you should make the step easier, in my case this bug just happened on my way until the project contained 'spaces' for example:

Replace:

C://Users/Silva Neto/OneDrive/Work space/project

With:

C://Users/SilvaNeto/OneDrive/Workspace/project

Notice that we replaced spaces with camelCase but you can choose any naming scheme you like, and hopefully this could solve your issue.

I hope this will help.

Advantages of SQL Server 2008 over SQL Server 2005?

There are new features added. But, you will have to see if it is worth the upgrade. Some good improvements in Management Studio 2008 though, especially the intellisense for the Query Editor.

WSDL validator?

If you're using Eclipse, just have your WSDL in a .wsdl file, eclipse will validate it automatically.

From the Doc

The WSDL validator handles validation according to the 4 step process defined above. Steps 1 and 2 are both delegated to Apache Xerces (and XML parser). Step 3 is handled by the WSDL validator and any extension namespace validators (more on extensions below). Step 4 is handled by any declared custom validators (more on this below as well). Each step must pass in order for the next step to run.

Insert picture/table in R Markdown

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

String commaSeparatedNames = namesList.toString().replaceAll( "[\\[|\\]| ]", "" );  // replace [ or ] or blank

The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space).

AbstractCollection javadoc

How to get child process from parent process

The shell process is $$ since it is a special parameter

On Linux, the proc(5) filesystem gives a lot of information about processes. Perhaps pgrep(1) (which accesses /proc) might help too.

So try cat /proc/$$/status to get the status of the shell process.

Hence, its parent process id could be retrieved with e.g.

  parpid=$(awk '/PPid:/{print $2}' /proc/$$/status)

Then use $parpid in your script to refer to the parent process pid (the parent of the shell).

But I don't think you need it!

Read some Bash Guide (or with caution advanced bash scripting guide, which has mistakes) and advanced linux programming.

Notice that some server daemon processes (wich usually need to be unique) are explicitly writing their pid into /var/run, e.g. the  sshd server daemon is writing its pid into the textual file /var/run/sshd.pid). You may want to add such a feature into your own server-like programs (coded in C, C++, Ocaml, Go, Rust or some other compiled language).

Get variable from PHP to JavaScript

You can pass PHP Variables to your JavaScript by generating it with PHP:

<?php
$someVar = 1;
?>

<script type="text/javascript">
    var javaScriptVar = "<?php echo $someVar; ?>";
</script>

Center the content inside a column in Bootstrap 4

_x000D_
_x000D_
.row>.col, .row>[class^=col-] {_x000D_
    padding-top: .75rem;_x000D_
    padding-bottom: .75rem;_x000D_
    background-color: rgba(86,61,124,.15);_x000D_
    border: 1px solid rgba(86,61,124,.2);_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
  <div class="row justify-content-md-center">_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col col-lg-2">_x000D_
      1 of 2_x000D_
    </div>_x000D_
    <div class="col col-lg-2">_x000D_
      3 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP Pass variable to next page

**page 1**
<form action="exapmple.php?variable_name=$value" method="POST"> 
    <button>
        <input  type="hidden" name="x">
    </button>
</form>`

page 2

if(isset($_POST['x'])) {
    $new_value=$_GET['variable_name'];
}

How do I get first name and last name as whole name in a MYSQL query?

When you have three columns : first_name, last_name, mid_name:

SELECT CASE 
    WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
        CONCAT_WS( " ", first_name, last_name ) 
    ELSE 
        CONCAT_WS( " ", first_name, mid_name, last_name ) 
    END 
FROM USER;

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

This answer might be helpful if you see above error but actually you have CUDA 10 installed:

pip install tensorflow-gpu==2.0.0

output:

I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_100.dll

which was the solution for me.

Binding select element to object in Angular

You can get selected value also with help of click() by passing the selected value through the function

<md-select placeholder="Select Categorie"  
    name="Select Categorie" >
  <md-option *ngFor="let list of categ" [value]="list.value" (click)="sub_cat(list.category_id)" >
    {{ list.category }}
  </md-option>
</md-select>

Is there a difference between "==" and "is"?

As the other people in this post answer the question in details the difference between == and is for comparing Objects or variables, I would emphasize mainly the comparison between is and == for strings which can give different results and I would urge programmers to carefully use them.

For string comparison, make sure to use == instead of is:

str = 'hello'
if (str is 'hello'):
    print ('str is hello')
if (str == 'hello'):
    print ('str == hello')

Out:

str is hello
str == hello

But in the below example == and is will get different results:

str2 = 'hello sam'
    if (str2 is 'hello sam'):
        print ('str2 is hello sam')
    if (str2 == 'hello sam'):
        print ('str2 == hello sam')

Out:

str2 == hello sam

Conclusion and Analysis:

Use is carefully to compare between strings. Since is for comparing objects and since in Python 3+ every variable such as string interpret as an object, let's see what happened in above paragraphs.

In python there is id function that shows a unique constant of an object during its lifetime. This id is using in back-end of Python interpreter to compare two objects using is keyword.

str = 'hello'
id('hello')
> 140039832615152
id(str)
> 140039832615152

But

str2 = 'hello sam'
id('hello sam')
> 140039832615536
id(str2)
> 140039832615792

Random number in range [min - max] using PHP

<?php
  $min=1;
  $max=20;
  echo rand($min,$max);
?>

What is Persistence Context?

Persistence Context is an environment or cache where entity instances(which are capable of holding data and thereby having the ability to be persisted in a database) are managed by Entity Manager.It syncs the entity with database.All objects having @Entity annotation are capable of being persisted. @Entity is nothing but a class which helps us create objects in order to communicate with the database.And the way the objects communicate is using methods.And who supplies those methods is the Entity Manager.

How to use "Share image using" sharing Intent to share images in android?

Simple and Easiest code you can use it to share image from gallery.

 String image_path;
            File file = new File(image_path);
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent .setType("image/*");
            intent .putExtra(Intent.EXTRA_STREAM, uri);
            context.startActivity(intent );

Hashset vs Treeset

1.HashSet allows null object.

2.TreeSet will not allow null object. If you try to add null value it will throw a NullPointerException.

3.HashSet is much faster than TreeSet.

e.g.

 TreeSet<String> ts = new TreeSet<String>();
 ts.add(null); // throws NullPointerException

 HashSet<String> hs = new HashSet<String>();
 hs.add(null); // runs fine

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I was getting similar errors and eventually found just that cleaning the build folder resolved my issue.

mvn clean install

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

Catching errors in Angular HttpClient

You probably want to have something like this:

this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})

It highly depends also how do you use your service but this is the basic case.

Python - How to cut a string in Python?

You can use find()

>>> s = 'http://www.domain.com/?s=some&two=20'
>>> s[:s.find('&')]
'http://www.domain.com/?s=some'

Of course, if there is a chance that the searched for text will not be present then you need to write more lengthy code:

pos = s.find('&')
if pos != -1:
    s = s[:pos]

Whilst you can make some progress using code like this, more complex situations demand a true URL parser.

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

Even for async tests, there is a timeout that goes off in this cases, You can work around this error by increasing the value for the limit timeout to evaluate an async Jasmine callback

describe('Helper', function () {
    var originalTimeout;

    beforeEach(function() {
        originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000;
    });

    afterEach(function() {
      jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
    });

    it('Template advance', function(doneFn) {
        $.ajax({
            url: 'public/your-end-point.mock.json',
            dataType: 'json',
            success: function (data, response) {
                // Here your expected using data
                expect(1).toBe(1)
                doneFn();
            },
            error: function (data, response) {
                // Here your expected using data
                expect(1).toBe(1)
                doneFn();
            }
        });
    });
});

Source: http://jasmine.github.io/2.0/introduction.html#section-42

Compiling and Running Java Code in Sublime Text 2

You can compile and run your code entirely in ST, and it's very quick/simple. There's a recent ST package called Javatar that can do this. https://javatar.readthedocs.org

html button to send email

This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...

HTML:

<form id="fr1">
    <input type="text" id="tb1" />
    <input type="text" id="tb2" />
    <input type="button" id="bt1" value="click" />
</form>

JavaScript (with jQuery):

$(document).ready(function() {
    $('#bt1').click(function() {
        $('#fr1').attr('action',
                       'mailto:[email protected]?subject=' +
                       $('#tb1').val() + '&body=' + $('#tb2').val());
        $('#fr1').submit();
    });
});

Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit type, it's just a button type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.

It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.

HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.

How to install npm peer dependencies automatically?

The automatic install of peer dependencies was explicitly removed with npm 3, as it cause more problems than it tried to solve. You can read about it here for example:

So no, for the reasons given, you cannot install them automatically with npm 3 upwards.

NPM V7

NPM v7 has reintroduced the automatic peerDependencies installation. They had made some changes to fix old problems as version compatibility across multiple dependants. You can see the discussion here and the announcement here

Now in V7, as in versions before V3, you only need to do an npm i and all peerDependences should be automatically installed.

sudo: npm: command not found

On macOS, this worked for me:

brew reinstall node

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

For some reason, there is no option in the create page dialogue to select a master page. I have tried both programatically declaring the MP and by updating the property in the Properties pane. – NoCarrier 13 mins ago

I believe its because i'm using a "web application" vs a "web site" – NoCarrier 9 mins ago

Chances are it is in the <@PAGE> tag where your problem is. That said, it doesnt make a difference if you are using a Web Application or not. To create a Child Page, right click on your master page in the Solution Explorer and choose Add Content Page.

Best way to do nested case statement logic in SQL Server

a user-defined function may server better, at least to hide the logic - esp. if you need to do this in more than one query

saving a file (from stream) to disk using c#

Just do it with a simple filestream.

var sr1 = new FileStream(FilePath, FileMode.Create);
                sr1.Write(_UploadFile.File, 0, _UploadFile.File.Length);
                sr1.Close();
                sr1.Dispose();

_UploadFile.File is a byte[], and in the FilePath you get to specify the file extention.

How to put a jpg or png image into a button in HTML

You can use some inline CSS like this

<input type="submit" name="submit" style="background: url(images/stack.png); width:100px; height:25px;" />

Should do the magic, also you may wanna do a border:none; to get rid of the standard borders.

How do I trigger a macro to run after a new mail is received in Outlook?

Try something like this inside ThisOutlookSession:

Private Sub Application_NewMail()
    Call Your_main_macro
End Sub

My outlook vba just fired when I received an email and had that application event open.

Edit: I just tested a hello world msg box and it ran after being called in the application_newmail event when an email was received.

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

if you are using cocoapods make sure your target's build settings contain $(inherited) in the other linker flags section

enter image description here

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

Since GDB 7.5 you can use these native Convenience Functions:

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

Seems quite less problematic than having to execute a "foreign" strcmp() on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.

Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running show configuration inside GDB and searching for --with-python. This little oneliner does the trick, too:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

For your demo case, the usage would be

break <where> if $_streq(x, "hello")

or, if your breakpoint already exists and you just want to add the condition to it

condition <breakpoint number> $_streq(x, "hello")

$_streq only matches the whole string, so if you want something more cunning you should use $_regex, which supports the Python regular expression syntax.

How do I get interactive plots again in Spyder/IPython/matplotlib?

This is actually pretty easy to fix and doesn't take any coding:

1.Click on the Plots tab above the console. 2.Then at the top right corner of the plots screen click on the options button. 3.Lastly uncheck the "Mute inline plotting" button

Now re-run your script and your graphs should show up in the console.

Cheers.

Get second child using jQuery

Use .find() method

$(t).find("td:eq(1)");

td:eq(x) // x is index of child you want to retrieve. eq(1) means equal to 1. //1 denote second element

Set textarea width to 100% in bootstrap modal

I had the same problem. I fixed it by adding this piece of code inside the text area's style.

resize: vertical;

You can check the Bootstrap reference here

Android - set TextView TextStyle programmatically?

Search for setTextAppearance or also setTextTypeface. There is similar question on stackoverflow: How to change a TextView's style at runtime

LDAP filter for blank (empty) attribute

Semantically there is no difference between these cases in LDAP.

How to read Data from Excel sheet in selenium webdriver

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

String FilePath = "/home/lahiru/Desktop/Sample.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);

String <variable> = sh.getCell("A2").getContents();

How do I tell Spring Boot which main class to use for the executable jar?

For those using Gradle (instead of Maven), referencing here:

The main class can also be configured explicitly using the task’s mainClassName property:

bootJar {
    mainClassName = 'com.example.ExampleApplication'
}

Alternatively, the main class name can be configured project-wide using the mainClassName property of the Spring Boot DSL:

springBoot {
    mainClassName = 'com.example.ExampleApplication'
}

SQL Server stored procedure parameters

Why would you pass a parameter to a stored procedure that doesn't use it?

It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.

How to convert int[] into List<Integer> in Java?

I'll add another answer with a different method; no loop but an anonymous class that will utilize the autoboxing features:

public List<Integer> asList(final int[] is)
{
    return new AbstractList<Integer>() {
            public Integer get(int i) { return is[i]; }
            public int size() { return is.length; }
    };
}

grep without showing path/file:line

From the man page:

-h, --no-filename
    Suppress the prefixing of file names on output. This is the default when there
    is only one file (or only standard input) to search.

NodeJS/express: Cache and 304 status code

Old question, I know. Disabling the cache facility is not needed and not the best way to manage the problem. By disabling the cache facility the server needs to work harder and generates more traffic. Also the browser and device needs to work harder, especially on mobile devices this could be a problem.

The empty page can be easily solved by using Shift key+reload button at the browser.

The empty page can be a result of:

  • a bug in your code
  • while testing you served an empty page (you can't remember) that is cached by the browser
  • a bug in Safari (if so, please report it to Apple and don't try to fix it yourself)

Try first the Shift keyboard key + reload button and see if the problem still exists and review your code.

Currency formatting in Python

A lambda for calculating it inside a function, with help from @Nate's answer

converter = lambda amount, currency: "%s%s%s" %(
    "-" if amount < 0 else "", 
    currency, 
    ('{:%d,.2f}'%(len(str(amount))+3)).format(abs(amount)).lstrip())

and then,

>>> converter(123132132.13, "$")
'$123,132,132.13'

>>> converter(-123132132.13, "$")
'-$123,132,132.13'

Chmod 777 to a folder and all contents

If by all permissions you mean 777

Navigate to folder and

chmod -R 777 .

How to take the first N items from a generator or list?

@Shaikovsky's answer is excellent (…and heavily edited since I posted this answer), but I wanted to clarify a couple of points.

[next(generator) for _ in range(n)]

This is the most simple approach, but throws StopIteration if the generator is prematurely exhausted.


On the other hand, the following approaches return up to n items which is preferable in many circumstances:

List: [x for _, x in zip(range(n), records)]

Generator: (x for _, x in zip(range(n), records))

Sorting HashMap by values

As a kind of simple solution you can use temp TreeMap if you need just a final result:

TreeMap<String, Integer> sortedMap = new TreeMap<String, Integer>();
for (Map.Entry entry : map.entrySet()) {
    sortedMap.put((String) entry.getValue(), (Integer)entry.getKey());
}

This will get you strings sorted as keys of sortedMap.

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Right click on your folder on your server or local machine and give full permissions to

IIS_IUSRS

that's it.

Javascript: console.log to html

You can override the default implementation of console.log()

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function (message) {
        if (typeof message == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(message) : message) + '<br />';
        } else {
            logger.innerHTML += message + '<br />';
        }
    }
})();

Demo: Fiddle

How to save a new sheet in an existing excel file, using Pandas?

A simple example for writing multiple data to excel at a time. And also when you want to append data to a sheet on a written excel file (closed excel file).

When it is your first time writing to an excel. (Writing "df1" and "df2" to "1st_sheet" and "2nd_sheet")

import pandas as pd 
from openpyxl import load_workbook

df1 = pd.DataFrame([[1],[1]], columns=['a'])
df2 = pd.DataFrame([[2],[2]], columns=['b'])
df3 = pd.DataFrame([[3],[3]], columns=['c'])

excel_dir = "my/excel/dir"

with pd.ExcelWriter(excel_dir, engine='xlsxwriter') as writer:    
    df1.to_excel(writer, '1st_sheet')   
    df2.to_excel(writer, '2nd_sheet')   
    writer.save()    

After you close your excel, but you wish to "append" data on the same excel file but another sheet, let's say "df3" to sheet name "3rd_sheet".

book = load_workbook(excel_dir)
with pd.ExcelWriter(excel_dir, engine='openpyxl') as writer:
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)    

    ## Your dataframe to append. 
    df3.to_excel(writer, '3rd_sheet')  

    writer.save()     

Be noted that excel format must not be xls, you may use xlsx one.

How to pass parameter to function using in addEventListener?

No need to pass anything in. The function used for addEventListener will automatically have this bound to the current element. Simply use this in your function:

productLineSelect.addEventListener('change', getSelection, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Here's the fiddle: http://jsfiddle.net/dJ4Wm/


If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:

productLineSelect.addEventListener('change', function() {
    foo('bar');
}, false);

function foo(message) {
    alert(message);
}

Here's the fiddle: http://jsfiddle.net/t4Gun/


If you want to set the value of this manually, you can use the call method to call the function:

var self = this;
productLineSelect.addEventListener('change', function() {
    getSelection.call(self);
    // This'll set the `this` value inside of `getSelection` to `self`
}, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Best way to handle list.index(might-not-exist) in python?

There is nothing "dirty" about using try-except clause. This is the pythonic way. ValueError will be raised by the .index method only, because it's the only code you have there!

To answer the comment:
In Python, easier to ask forgiveness than to get permission philosophy is well established, and no index will not raise this type of error for any other issues. Not that I can think of any.

Remove padding or margins from Google Charts

I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.

        var options = {
        chartArea:{left:10,top:20,width:"100%",height:"100%"}
    };

Left and top options will define the amount of padding from left and top. Hope this will help.

ALTER TABLE to add a composite primary key

It`s definitely better to use COMPOSITE UNIQUE KEY, as @GranadaCoder offered, a little bit tricky example though:

ALTER IGNORE TABLE table_name ADD UNIQUES INDEX idx_name(some_id, another_id, one_more_id);

Javascript/jQuery: Set Values (Selection) in a multiple Select

var groups = ["Test", "Prof","Off"];

    $('#fruits option').filter(function() {
      return groups.indexOf($(this).text()) > -1; //Options text exists in array
    }).prop('selected', true); //Set selected

What is the best way to modify a list in a 'foreach' loop?

Make a copy of the enumeration, using an IEnumerable extension method in this case, and enumerate over it. This would add a copy of every element in every inner enumerable to that enumeration.

foreach(var item in Enumerable)
{
    foreach(var item2 in item.Enumerable.ToList())
    {
        item.Add(item2)
    }
}

String strip() for JavaScript?

Gumbo already noted this in a comment, but this bears repeating as an answer: the trim() method was added in JavaScript 1.8.1 and is supported by all modern browsers (Firefox 3.5+, IE 9, Chrome 10, Safari 5.x), although IE 8 and older do not support it. Usage is simple:

 "  foo\n\t  ".trim() => "foo"

See also:

htaccess redirect if URL contains a certain string

If url contains a certen string, redirect to index.php . You need to match against the %{REQUEST_URI} variable to check if the url contains a certen string.

To redirect example.com/foo/bar to /index.php if the uri contains bar anywhere in the uri string , you can use this :

RewriteEngine on

RewriteCond %{REQUEST_URI} bar
RewriteRule ^ /index.php [L,R]

Equals(=) vs. LIKE

This is a copy/paste of another answer of mine for question SQL 'like' vs '=' performance:

A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.

When using a like on an index as below(no wildcards), it took about 30 seconds:

where login like '12345678'

using 'explain' I get:

enter image description here

When using an '=' on the same query, it took about 0.1 seconds:

where login ='12345678'

Using 'explain' I get:

enter image description here

As you can see, the like completely cancelled the index seek, so query took 300 times more time.

How to get milliseconds from LocalDateTime in Java 8

To get the current time in milliseconds (since the epoch), use System.currentTimeMillis().

Add Expires headers

In ASP.NET there is similar object, you can use Caching Portions in WebFormsUserControls in order to cache objects of a page for a period of time and save server resources. This is also known as fragment caching.
If you include this code to top of your user control, a version of the control stored in the output cache for 150 seconds. You can create your own control that would contain expire header for a specific resource you want.

<%@ OutputCache Duration="150" VaryByParam="None" %>

This article explain it completely: Caching Portions of an ASP.NET Page

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

Regex (grep) for multi-line search needed

I am not very good in grep. But your problem can be solved using AWK command. Just see

awk '/select/,/from/' *.sql

The above code will result from first occurence of select till first sequence of from. Now you need to verify whether returned statements are having customername or not. For this you can pipe the result. And can use awk or grep again.

How to show a running progress bar while page is loading

In this sample, I created a JavaScript progress bar (with percentage display), you can control it and hide it with JavaScript.

In this sample, the progress bar advances every 100ms. You can see it in JSFiddle

var elapsedTime = 0;
var interval = setInterval(function() {
  timer()
}, 100);

function progressbar(percent) {
  document.getElementById("prgsbarcolor").style.width = percent + '%';
  document.getElementById("prgsbartext").innerHTML = percent + '%';
}

function timer() {
  if (elapsedTime > 100) {
    document.getElementById("prgsbartext").style.color = "#FFF";
    document.getElementById("prgsbartext").innerHTML = "Completed.";
    if (elapsedTime >= 107) {
      clearInterval(interval);
      history.go(-1);
    }
  } else {
    progressbar(elapsedTime);
  }
  elapsedTime++;
}

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 /?.

Converting an OpenCV Image to Black and White

Here's a two line code I found online that might be helpful for a beginner

# Absolute value of the 32/64
abs_image_in32_64 = np.absolute(image_in32_64)

image_8U = np.uint8(abs_image_in32_64)

jQuery Remove string from string

pretty sure you just want the plain old replace function. use like this:

myString.replace('username1','');

i suppose if you want to remove the trailing comma do this instead:

myString.replace('username1,','');

edit:

here is your site specific code:

jQuery("#post_like_list-510").text().replace(...) 

How to parse data in JSON format?

Sometimes your json is not a string. For example if you are getting a json from a url like this:

j = urllib2.urlopen('http://site.com/data.json')

you will need to use json.load, not json.loads:

j_obj = json.load(j)

(it is easy to forget: the 's' is for 'string')

Sort list in C# with LINQ

I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:

var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();

How do I retrieve the number of columns in a Pandas data frame?

There are multiple option to get column number and column information such as:
let's check them.

local_df = pd.DataFrame(np.random.randint(1,12,size=(2,6)),columns =['a','b','c','d','e','f']) 1. local_df.shape[1] --> Shape attribute return tuple as (row & columns) (0,1).

  1. local_df.info() --> info Method will return detailed information about data frame and it's columns such column count, data type of columns, Not null value count, memory usage by Data Frame

  2. len(local_df.columns) --> columns attribute will return index object of data frame columns & len function will return total available columns.

  3. local_df.head(0) --> head method with parameter 0 will return 1st row of df which actually nothing but header.

Assuming number of columns are not more than 10. For loop fun: li_count =0 for x in local_df: li_count =li_count + 1 print(li_count)

Best way to use PHP to encrypt and decrypt passwords?

You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. This answer explains how to properly implement password hashing in PHP. Still, here is how you would encrypt/decrypt:

$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces

To Encrypt:

$iv = mcrypt_create_iv(
    mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
    MCRYPT_DEV_URANDOM
);

$encrypted = base64_encode(
    $iv .
    mcrypt_encrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        $string,
        MCRYPT_MODE_CBC,
        $iv
    )
);

To Decrypt:

$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));

$decrypted = rtrim(
    mcrypt_decrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
        MCRYPT_MODE_CBC,
        $iv
    ),
    "\0"
);

Warning: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. You should not rely on unauthenticated encryption for security, especially since the code as provided is vulnerable to padding oracle attacks.

See also:

Also, don't just use a "password" for an encryption key. Encryption keys are random strings.


Demo at 3v4l.org:

echo 'Encrypted:' . "\n";
var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688="

echo "\n";

echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "

Where is my m2 folder on Mac OS X Mavericks

If you have used brew to install maven, create .m2 directory and then copy settings.xml in .m2 directory.

mkdir ~/.m2
cp /usr/local/Cellar/maven32/3.2.5/libexec/conf/settings.xml ~/.m2

You may need to change the maven version in the path, mine is 3.2.5

How do I compare version numbers in Python?

There is packaging package available, which will allow you to compare versions as per PEP-440, as well as legacy versions.

>>> from packaging.version import Version, LegacyVersion
>>> Version('1.1') < Version('1.2')
True
>>> Version('1.2.dev4+deadbeef') < Version('1.2')
True
>>> Version('1.2.8.5') <= Version('1.2')
False
>>> Version('1.2.8.5') <= Version('1.2.8.6')
True

Legacy version support:

>>> LegacyVersion('1.2.8.5-5-gdeadbeef')
<LegacyVersion('1.2.8.5-5-gdeadbeef')>

Comparing legacy version with PEP-440 version.

>>> LegacyVersion('1.2.8.5-5-gdeadbeef') < Version('1.2.8.6')
True

Illegal character in path at index 16

There's an illegal character at index 16. I'd say it doesn't like the space in the path. You can percent encode special characters like spaces. Replace it with a %20 in this case.

The question I linked to above suggests using URLEncoder:

String thePath = "file://E:/Program Files/IBM/SDP/runtimes/base";
thePath = URLEncoder.encode(thePath, "UTF-8"); 

How to switch a user per task or set of tasks?

You can specify become_method to override the default method set in ansible.cfg (if any), and which can be set to one of sudo, su, pbrun, pfexec, doas, dzdo, ksu.

- name: I am confused
  command: 'whoami'
  become: true
  become_method: su
  become_user: some_user
  register: myidentity

- name: my secret identity
  debug:
    msg: '{{ myidentity.stdout }}'

Should display

TASK [my-task : my secret identity] ************************************************************
ok: [my_ansible_server] => {
    "msg": "some_user"
}

Which browsers support <script async="async" />?

The async is currently supported by all latest versions of the major browsers. It has been supported for some years now on most browsers.

You can keep track of which browsers support async (and defer) in the MDN website here:
https://developer.mozilla.org/en-US/docs/HTML/Element/script

Excel: How to check if a cell is empty with VBA?

This site uses the method isEmpty().

Edit: content grabbed from site, before the url will going to be invalid.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop

In the first step the data in the first column from Sheet1 will be sort. In the second step, all rows with same data will be removed.

How to: Install Plugin in Android Studio

  1. Launch Android Studio application
  2. Choose Project Settings
  3. Choose Plugin from disk, if on disk then choose that location of *.jar, in my case is GenyMotion jar
  4. Click on Apply and OK.
  5. Then Android studio will ask for Restart.

That's all Folks! enter image description here

Python urllib2, basic HTTP authentication, and tr.im

Really cheap solution:

urllib.urlopen('http://user:[email protected]/api')

(which you may decide is not suitable for a number of reasons, like security of the url)

Github API example:

>>> import urllib, json
>>> result = urllib.urlopen('https://personal-access-token:[email protected]/repos/:owner/:repo')
>>> r = json.load(result.fp)
>>> result.close()

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

Use the createFromFormat method:

$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);

UPDATE

I now recommend the use of Carbon

Setting environment variables for accessing in PHP when using Apache

Something along the lines:

<VirtualHost hostname:80>
   ...
   SetEnv VARIABLE_NAME variable_value
   ...
</VirtualHost>

Twitter bootstrap hide element on small devices

<div class="small hidden-xs">
    Some Content Here
</div>

This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.

This answer satisfies the question in the OP title (which is how I found this Q/A).

Repeat a task with a time delay?

Based on the above post concerning the ScheduledThreadPoolExecutor, I came up with a utility that suited my needs (wanted to fire a method every 3 seconds):

class MyActivity {
    private ScheduledThreadPoolExecutor mDialogDaemon;

    private void initDebugButtons() {
        Button btnSpawnDialogs = (Button)findViewById(R.id.btn_spawn_dialogs);
        btnSpawnDialogs.setVisibility(View.VISIBLE);
        btnSpawnDialogs.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                spawnDialogs();
            }
        });
    }

    private void spawnDialogs() {
        if (mDialogDaemon != null) {
            mDialogDaemon.shutdown();
            mDialogDaemon = null;
        }
        mDialogDaemon = new ScheduledThreadPoolExecutor(1);
        // This process will execute immediately, then execute every 3 seconds.
        mDialogDaemon.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Do something worthwhile
                    }
                });
            }
        }, 0L, 3000L, TimeUnit.MILLISECONDS);
    }
}

ASP.NET MVC Razor pass model to layout

Why dont you just add a new Partial View with i's own specific controller passing the required model to the partial view and finally Render the mentioned partial view on your Layout.cshtml using RenderPartial or RenderAction ?

I use this method for showing the logged in user's info like name , profile picture and etc.

Validation for 10 digit mobile number and focus input field on invalid

I used $form.submit() as it keeps html input validation.

Also I used input type tel as it supported by mobile browsers, only display numeric keypad.

<input type="tel" minlength="10" maxlength="10" id="mobile" name="mobile" title="10 digit mobile number" required>


$('#mob_frm').submit(function(e) {
            e.preventDefault();
            if(!$('#mobile').val().match('[0-9]{10}'))  {
                alert("Please put 10 digit mobile number");
                return;
            }  

        });

PermissionError: [Errno 13] Permission denied

I had a similar problem. I thought it might be with the system. But, using shutil.copytree() from the shutil module solved the problem for me!

When to use Common Table Expression (CTE)

One of the scenarios I found useful to use CTE is when you want to get DISTINCT rows of data based on one or more columns but return all columns in the table. With a standard query you might first have to dump the distinct values into a temp table and then try to join them back to the original table to retrieve the rest of the columns or you might write an extremely complex partition query that can return the results in one run but in most likelihood, it will be unreadable and cause performance issue.

But by using CTE (as answered by Tim Schmelter on Select the first instance of a record)

WITH CTE AS(
    SELECT myTable.*
    , RN = ROW_NUMBER()OVER(PARTITION BY patientID ORDER BY ID)
    FROM myTable 
)
SELECT * FROM CTE
WHERE RN = 1

As you can see, this is much easier to read and maintain. And in comparison to other queries, is much better at performance.

'node' is not recognized as an internal or external command

Make sure nodejs in the PATH is in front of anything that uses node.

Convert an integer to a float number

intutils.ToFloat32

// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
    return float32(in)
}

// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
    return float64(in)
}

Mockito How to mock and assert a thrown exception?

Use Mockito's doThrow and then catch the desired exception to assert it was thrown later.

@Test
public void fooShouldThrowMyException() {
    // given
    val myClass = new MyClass();
    val arg = mock(MyArgument.class);
    doThrow(MyException.class).when(arg).argMethod(any());
    Exception exception = null;

    // when
    try {
        myClass.foo(arg);
    } catch (MyException t) {
        exception = t;
    }

    // then
    assertNotNull(exception);
}

Reducing MongoDB database file size

In case a large chunk of data is deleted from a collection and the collection never uses the deleted space for new documents, this space needs to be returned to the operating system so that it can be used by other databases or collections. You will need to run a compact or repair operation in order to defragment the disk space and regain the usable free space.

Behavior of compaction process is dependent on MongoDB engine as follows

db.runCommand({compact: collection-name })

MMAPv1

Compaction operation defragments data files & indexes. However, it does not release space to the operating system. The operation is still useful to defragment and create more contiguous space for reuse by MongoDB. However, it is of no use though when the free disk space is very low.

An additional disk space up to 2GB is required during the compaction operation.

A database level lock is held during the compaction operation.

WiredTiger

The WiredTiger engine provides compression by default which consumes less disk space than MMAPv1.

The compact process releases the free space to the operating system. Minimal disk space is required to run the compact operation. WiredTiger also blocks all operations on the database as it needs database level lock.

For MMAPv1 engine, compact doest not return the space to operating system. You require to run repair operation to release the unused space.

db.runCommand({repairDatabase: 1})

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

Answering to myself. From the RequireJS website:

//THIS WILL FAIL
define(['require'], function (require) {
    var namedModule = require('name');
});

This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.

My solution:

// Modules configuration (modules that will be used as Jade helpers)
define(function () {
    return {
        'moment':   'path/to/moment',
        'filesize': 'path/to/filesize',
        '_':        'path/to/lodash',
        '_s':       'path/to/underscore.string'
    };
});

The loader:

define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
    var deps;

    // Dynamic require
    require(_.values(Config), function () {
        deps = _.object(_.keys(Config), arguments);

        // Use deps...
    });
});

Difference between innerText, innerHTML and value?

InnerText property html-encodes the content, turning <p> to &lt;p&gt;, etc. If you want to insert HTML tags you need to use InnerHTML.

Styling input radio with css

You should use some background image to your radio buttons and flip it with another image on change

.radio {
    background: url(customButton.png) no-repeat;
}

Chrome refuses to execute an AJAX script due to wrong MIME type

If your proxy server or container adds the following header when serving the .js file, it will force some browsers such as Chrome to perform strict checking of MIME types:

X-Content-Type-Options: nosniff

Remove this header to prevent Chrome performing the MIME check.

TSQL: How to convert local time to UTC? (SQL Server 2008)

For SQL Server 2016 and newer, and Azure SQL Database, use the built in AT TIME ZONE statement.

For older editions of SQL Server, you can use my SQL Server Time Zone Support project to convert between IANA standard time zones, as listed here.

UTC to Local is like this:

SELECT Tzdb.UtcToLocal('2015-07-01 00:00:00', 'America/Los_Angeles')

Local to UTC is like this:

SELECT Tzdb.LocalToUtc('2015-07-01 00:00:00', 'America/Los_Angeles', 1, 1)

The numeric options are flag for controlling the behavior when the local time values are affected by daylight saving time. These are described in detail in the project's documentation.

How to convert a 3D point into 2D perspective projection?

All of the answers address the question posed in the title. However, I would like to add a caveat that is implicit in the text. Bézier patches are used to represent the surface, but you cannot just transform the points of the patch and tessellate the patch into polygons, because this will result in distorted geometry. You can, however, tessellate the patch first into polygons using a transformed screen tolerance and then transform the polygons, or you can convert the Bézier patches to rational Bézier patches, then tessellate those using a screen-space tolerance. The former is easier, but the latter is better for a production system.

I suspect that you want the easier way. For this, you would scale the screen tolerance by the norm of the Jacobian of the inverse perspective transformation and use that to determine the amount of tessellation that you need in model space (it might be easier to compute the forward Jacobian, invert that, then take the norm). Note that this norm is position-dependent, and you may want to evaluate this at several locations, depending on the perspective. Also remember that since the projective transformation is rational, you need to apply the quotient rule to compute the derivatives.

How to create Windows EventLog source from command line?

you can create your own custom event by using diagnostics.Event log class. Open a windows application and on a button click do the following code.

System.Diagnostics.EventLog.CreateEventSource("ApplicationName", "MyNewLog");

"MyNewLog" means the name you want to give to your log in event viewer.

for more information check this link [ http://msdn.microsoft.com/en-in/library/49dwckkz%28v=vs.90%29.aspx]

Encode/Decode URLs in C++

CGICC includes methods to do url encode and decode. form_urlencode and form_urldecode

Google Chrome: This setting is enforced by your administrator

On Linux, you can get rid of "Managed by your organization" Chrome policies, by removing these directories (as sudo probably):

/etc/opt/chrome/policies
/etc/opt/chrome/policies/managed
/etc/opt/chrome/policies/recommended

FileNotFoundException..Classpath resource not found in spring?

I was getting the same problem when running my project. On checking the files structure, I realised that Spring's xml file was inside the project's package and thus couldn't be found. I put it outside the package and it worked just fine.

Copy and paste content from one file to another file in vi

Use the variations of d like dd to cut.

To write a range of lines to another file you can use:

:<n>,<m> w filename

Where <n> and <m> are numbers (or symbols) that designate a range of lines.

For using the desktop clipboard, take a look at the +g commands.

How to enable native resolution for apps on iPhone 6 and 6 Plus?

I didn't want to introduce an asset catalog.

Per the answer from seahorseseaeo here, adding the following to info.plist worked for me. (I edited it as a "source code".) I then named the images [email protected] and [email protected]

<key>UILaunchImages</key>
<array>
    <dict>
        <key>UILaunchImageMinimumOSVersion</key>
        <string>8.0</string>
        <key>UILaunchImageName</key>
        <string>Default-667h</string>
        <key>UILaunchImageOrientation</key>
        <string>Portrait</string>
        <key>UILaunchImageSize</key>
        <string>{375, 667}</string>
    </dict>
    <dict>
        <key>UILaunchImageMinimumOSVersion</key>
        <string>8.0</string>
        <key>UILaunchImageName</key>
        <string>Default-736h</string>
        <key>UILaunchImageOrientation</key>
        <string>Portrait</string>
        <key>UILaunchImageSize</key>
        <string>{414, 736}</string>
    </dict>
</array>

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;