Programs & Examples On #Neat

Neat is an open source semantic grid framework built on top of Sass and Bourbon.

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

Faced the same issue, another solution is to add default includes, this fixed the problem for me:

$(IncludePath);

File URL "Not allowed to load local resource" in the Internet Browser

I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.

Based on your screenshot, try formatting your link like so:

<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>

(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)

How to handle errors with boto3?

Use the response contained within the exception. Here is an example:

import boto3
from botocore.exceptions import ClientError

try:
    iam = boto3.client('iam')
    user = iam.create_user(UserName='fred')
    print("Created user: %s" % user)
except ClientError as e:
    if e.response['Error']['Code'] == 'EntityAlreadyExists':
        print("User already exists")
    else:
        print("Unexpected error: %s" % e)

The response dict in the exception will contain the following:

  • ['Error']['Code'] e.g. 'EntityAlreadyExists' or 'ValidationError'
  • ['ResponseMetadata']['HTTPStatusCode'] e.g. 400
  • ['ResponseMetadata']['RequestId'] e.g. 'd2b06652-88d7-11e5-99d0-812348583a35'
  • ['Error']['Message'] e.g. "An error occurred (EntityAlreadyExists) ..."
  • ['Error']['Type'] e.g. 'Sender'

For more information see:

[Updated: 2018-03-07]

The AWS Python SDK has begun to expose service exceptions on clients (though not on resources) that you can explicitly catch, so it is now possible to write that code like this:

import botocore
import boto3

try:
    iam = boto3.client('iam')
    user = iam.create_user(UserName='fred')
    print("Created user: %s" % user)
except iam.exceptions.EntityAlreadyExistsException:
    print("User already exists")
except botocore.exceptions.ParamValidationError as e:
    print("Parameter validation error: %s" % e)
except botocore.exceptions.ClientError as e:
    print("Unexpected error: %s" % e)

Unfortunately, there is currently no documentation for these exceptions but you can get a list of them as follows:

import botocore
import boto3
dir(botocore.exceptions)

Note that you must import both botocore and boto3. If you only import botocore then you will find that botocore has no attribute named exceptions. This is because the exceptions are dynamically populated into botocore by boto3.

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

How do I plot only a table in Matplotlib?

If you just wanted to change the example and put the table at the top, then loc='top' in the table declaration is what you need,

the_table = ax.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='top')

Then adjusting the plot with,

plt.subplots_adjust(left=0.2, top=0.8)

A more flexible option is to put the table in its own axis using subplots,

import numpy as np
import matplotlib.pyplot as plt


fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')

axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()

which looks like this,

enter image description here

You are then free to adjust the locations of the axis as required.

is there a function in lodash to replace matched item

As the time passes you should embrace a more functional approach in which you should avoid data mutations and write small, single responsibility functions. With the ECMAScript 6 standard, you can enjoy functional programming paradigm in JavaScript with the provided map, filter and reduce methods. You don't need another lodash, underscore or what else to do most basic things.

Down below I have included some proposed solutions to this problem in order to show how this problem can be solved using different language features:

Using ES6 map:

_x000D_
_x000D_
const replace = predicate => replacement => element =>_x000D_
  predicate(element) ? replacement : element_x000D_
 _x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = arr.map(replace (predicate) (replacement))_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_


Recursive version - equivalent of mapping:

Requires destructuring and array spread.

_x000D_
_x000D_
const replace = predicate => replacement =>_x000D_
{_x000D_
  const traverse = ([head, ...tail]) =>_x000D_
    head_x000D_
    ? [predicate(head) ? replacement : head, ...tail]_x000D_
    : []_x000D_
  return traverse_x000D_
}_x000D_
 _x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = replace (predicate) (replacement) (arr)_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_


When the final array's order is not important you can use an object as a HashMap data structure. Very handy if you already have keyed collection as an object - otherwise you have to change your representation first.

Requires object rest spread, computed property names and Object.entries.

_x000D_
_x000D_
const replace = key => ({id, ...values}) => hashMap =>_x000D_
({_x000D_
  ...hashMap,       //original HashMap_x000D_
  [key]: undefined, //delete the replaced value_x000D_
  [id]: values      //assign replacement_x000D_
})_x000D_
_x000D_
// HashMap <-> array conversion_x000D_
const toHashMapById = array =>_x000D_
  array.reduce(_x000D_
    (acc, { id, ...values }) => _x000D_
    ({ ...acc, [id]: values })_x000D_
  , {})_x000D_
  _x000D_
const toArrayById = hashMap =>_x000D_
  Object.entries(hashMap)_x000D_
  .filter( // filter out undefined values_x000D_
    ([_, value]) => value _x000D_
  ) _x000D_
  .map(_x000D_
    ([id, values]) => ({ id, ...values })_x000D_
  )_x000D_
_x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const replaceKey = 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
// Create a HashMap from the array, treating id properties as keys_x000D_
const hashMap = toHashMapById(arr)_x000D_
console.log(hashMap)_x000D_
_x000D_
// Result of replacement - notice an undefined value for replaced key_x000D_
const resultHashMap = replace (replaceKey) (replacement) (hashMap)_x000D_
console.log(resultHashMap)_x000D_
_x000D_
// Final result of conversion from the HashMap to an array_x000D_
const result = toArrayById (resultHashMap)_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Android "elevation" not showing a shadow

I had some luck with setting clipChildren="false" on the parent layout.

Inline for loop

q  = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1,1,2,3,1]

p = []
for v in vm:
    if v in q:
        p.append(q.index(v))
    else:
        p.append(99999)

print p
p = [q.index(v) if v in q else 99999 for v in vm]
print p

Output:

[99999, 99999, 99999, 99999, 0, 1, 2, 0]
[99999, 99999, 99999, 99999, 0, 1, 2, 0]

Instead of using append() in the list comprehension you can reference the p as direct output, and use q.index(v) and 99999 in the LC.

Not sure if this is intentional but note that q.index(v) will find just the first occurrence of v, even tho you have several in q. If you want to get the index of all v in q, consider using a enumerator and a list of already visited indexes

Something in those lines(pseudo-code):

visited = []
for i, v in enumerator(vm):
   if i not in visited:
       p.append(q.index(v))
   else:
       p.append(q.index(v,max(visited))) # this line should only check for v in q after the index of max(visited)
   visited.append(i)

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Easy — just use Font Awesome 5's default fa-[size]x classes. You can scale icons up to 10x of the parent element's font-size Read the docs about icon sizing.

Examples:

<span class="fas fa-info-circle fa-6x"></span>
<span class="fas fa-info-circle fa-7x"></span>
<span class="fas fa-info-circle fa-8x"></span>
<span class="fas fa-info-circle fa-9x"></span>
<span class="fas fa-info-circle fa-10x"></span>

ansible : how to pass multiple commands

Shell works for me.

Simply to say, Shell is the same as you run a shell script.

Notes:

  1. Make sure use | when running multiple cmds.
  2. Shell won't return errors if the last cmd is success (just like normal shell)
  3. Control it with exit 0/1 if you want to stop ansible when error occurs.

The following example shows an error in shell, but it's success at the end of the execution.

- name: test shell with an error
become: no
shell: |
  rm -f /test1  # This should be an error.
  echo "test2"
  echo "test1"
  echo "test3" # success

This example shows stopinng shell with exit 1 error.

- name: test shell with exit 1
become: no
shell: |
  rm -f /test1  # This should be an error.
  echo "test2"
  exit 1        # this stops ansible due to returning an error
  echo "test1"
  echo "test3" # success

reference: https://docs.ansible.com/ansible/latest/modules/shell_module.html

Java 8 Stream and operation on arrays

Be careful if you have to deal with large numbers.

int[] arr = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
long sum = Arrays.stream(arr).sum(); // Wrong: sum == 0

The sum above is not 2 * Integer.MIN_VALUE. You need to do this in this case.

long sum = Arrays.stream(arr).mapToLong(Long::valueOf).sum(); // Correct

Does Java SE 8 have Pairs or Tuples?

Since Java 9, you can create instances of Map.Entry easier than before:

Entry<Integer, String> pair = Map.entry(1, "a");

Map.entry returns an unmodifiable Entry and forbids nulls.

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

I got a similar error with '/' operand while processing images. I discovered the folder included a text file created by the 'XnView' image viewer. So, this kind of error occurs when some object is not the kind of object expected.

Injecting $scope into an angular service function()

Instead of trying to modify the $scope within the service, you can implement a $watch within your controller to watch a property on your service for changes and then update a property on the $scope. Here is an example you might try in a controller:

angular.module('cfd')
    .controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) {

        $scope.students = null;

        (function () {
            $scope.$watch(function () {
                return StudentService.students;
            }, function (newVal, oldVal) {
                if ( newValue !== oldValue ) {
                    $scope.students = newVal;
                }
            });
        }());
    }]);

One thing to note is that within your service, in order for the students property to be visible, it needs to be on the Service object or this like so:

this.students = $http.get(path).then(function (resp) {
  return resp.data;
});

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

Make Https call using HttpClient

Your code should be modified in this way:

httpClient.BaseAddress = new Uri("https://foobar.com/");

You have just to use the https: URI scheme. There's a useful page here on MSDN about the secure HTTP connections. Indeed:

Use the https: URI scheme

The HTTP Protocol defines two URI schemes:

http : Used for unencrypted connections.

https : Used for secure connections that should be encrypted. This option also uses digital certificates and certificate authorities to verify that the server is who it claims to be.

Moreover, consider that the HTTPS connections use a SSL certificate. Make sure your secure connection has this certificate otherwise the requests will fail.

EDIT:

Above code works fine for making http calls. But when I change the scheme to https it does not work, let me post the error.

What does it mean doesn't work? The requests fail? An exception is thrown? Clarify your question.

If the requests fail, then the issue should be the SSL certificate.

To fix the issue, you can use the class HttpWebRequest and then its property ClientCertificate. Furthermore, you can find here a useful sample about how to make a HTTPS request using the certificate.

An example is the following (as shown in the MSDN page linked before):

//You must change the path to point to your .cer file location. 
X509Certificate Cert = X509Certificate.CreateFromCertFile("C:\\mycert.cer");
// Handle any certificate errors on the certificate from the server.
ServicePointManager.CertificatePolicy = new CertPolicy();
// You must change the URL to point to your Web server.
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://YourServer/sample.asp");
Request.ClientCertificates.Add(Cert);
Request.UserAgent = "Client Cert Sample";
Request.Method = "GET";
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

How do I get the Back Button to work with an AngularJS ui-router state machine?

Note

The answers that suggest using variations of $window.history.back() have all missed a crucial part of the question: How to restore the application's state to the correct state-location as the history jumps (back/forward/refresh). With that in mind; please, read on.


Yes, it is possible to have the browser back/forward (history) and refresh whilst running a pure ui-router state-machine but it takes a bit of doing.

You need several components:

  • Unique URLs. The browser only enables the back/forward buttons when you change urls, so you must generate a unique url per visited state. These urls need not contain any state information though.

  • A Session Service. Each generated url is correlated to a particular state so you need a way to store your url-state pairs so that you can retrieve the state information after your angular app has been restarted by back / forward or refresh clicks.

  • A State History. A simple dictionary of ui-router states keyed by unique url. If you can rely on HTML5 then you can use the HTML5 History API, but if, like me, you can't then you can implement it yourself in a few lines of code (see below).

  • A Location Service. Finally, you need to be able manage both ui-router state changes, triggered internally by your code, and normal browser url changes typically triggered by the user clicking browser buttons or typing stuff into the browser bar. This can all get a bit tricky because it is easy to get confused about what triggered what.

Here is my implementation of each of these requirements. I have bundled everything up into three services:

The Session Service

class SessionService

    setStorage:(key, value) ->
        json =  if value is undefined then null else JSON.stringify value
        sessionStorage.setItem key, json

    getStorage:(key)->
        JSON.parse sessionStorage.getItem key

    clear: ->
        @setStorage(key, null) for key of sessionStorage

    stateHistory:(value=null) ->
        @accessor 'stateHistory', value

    # other properties goes here

    accessor:(name, value)->
        return @getStorage name unless value?
        @setStorage name, value

angular
.module 'app.Services'
.service 'sessionService', SessionService

This is a wrapper for the javascript sessionStorage object. I have cut it down for clarity here. For a full explanation of this please see: How do I handle page refreshing with an AngularJS Single Page Application

The State History Service

class StateHistoryService
    @$inject:['sessionService']
    constructor:(@sessionService) ->

    set:(key, state)->
        history = @sessionService.stateHistory() ? {}
        history[key] = state
        @sessionService.stateHistory history

    get:(key)->
        @sessionService.stateHistory()?[key]

angular
.module 'app.Services'
.service 'stateHistoryService', StateHistoryService

The StateHistoryService looks after the storage and retrieval of historical states keyed by generated, unique urls. It is really just a convenience wrapper for a dictionary style object.

The State Location Service

class StateLocationService
    preventCall:[]
    @$inject:['$location','$state', 'stateHistoryService']
    constructor:(@location, @state, @stateHistoryService) ->

    locationChange: ->
        return if @preventCall.pop('locationChange')?
        entry = @stateHistoryService.get @location.url()
        return unless entry?
        @preventCall.push 'stateChange'
        @state.go entry.name, entry.params, {location:false}

    stateChange: ->
        return if @preventCall.pop('stateChange')?
        entry = {name: @state.current.name, params: @state.params}
        #generate your site specific, unique url here
        url = "/#{@state.params.subscriptionUrl}/#{Math.guid().substr(0,8)}"
        @stateHistoryService.set url, entry
        @preventCall.push 'locationChange'
        @location.url url

angular
.module 'app.Services'
.service 'stateLocationService', StateLocationService

The StateLocationService handles two events:

  • locationChange. This is called when the browsers location is changed, typically when the back/forward/refresh button is pressed or when the app first starts or when the user types in a url. If a state for the current location.url exists in the StateHistoryService then it is used to restore the state via ui-router's $state.go.

  • stateChange. This is called when you move state internally. The current state's name and params are stored in the StateHistoryService keyed by a generated url. This generated url can be anything you want, it may or may not identify the state in a human readable way. In my case I am using a state param plus a randomly generated sequence of digits derived from a guid (see foot for the guid generator snippet). The generated url is displayed in the browser bar and, crucially, added to the browser's internal history stack using @location.url url. Its adding the url to the browser's history stack that enables the forward / back buttons.

The big problem with this technique is that calling @location.url url in the stateChange method will trigger the $locationChangeSuccess event and so call the locationChange method. Equally calling the @state.go from locationChange will trigger the $stateChangeSuccess event and so the stateChange method. This gets very confusing and messes up the browser history no end.

The solution is very simple. You can see the preventCall array being used as a stack (pop and push). Each time one of the methods is called it prevents the other method being called one-time-only. This technique does not interfere with the correct triggering of the $ events and keeps everything straight.

Now all we need to do is call the HistoryService methods at the appropriate time in the state transition life-cycle. This is done in the AngularJS Apps .run method, like this:

Angular app.run

angular
.module 'app', ['ui.router']
.run ($rootScope, stateLocationService) ->

    $rootScope.$on '$stateChangeSuccess', (event, toState, toParams) ->
        stateLocationService.stateChange()

    $rootScope.$on '$locationChangeSuccess', ->
        stateLocationService.locationChange()

Generate a Guid

Math.guid = ->
    s4 = -> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
    "#{s4()}#{s4()}-#{s4()}-#{s4()}-#{s4()}-#{s4()}#{s4()}#{s4()}"

With all this in place, the forward / back buttons and the refresh button all work as expected.

Is there a TRY CATCH command in Bash

Below is an complete copy of the simplified script used in my other answer. Beyond additional error checking, there is an alias which allows the user to change the name of an existing alias. The syntax is given below. If the new_alias parameter is omitted, then the alias is removed.

ChangeAlias old_alias [new_alias]

The complete script is given below.

common.GetAlias() {
    local "oldname=${1:-0}"
    if [[ $oldname =~ ^[0-9]+$ && oldname+1 -lt ${#FUNCNAME[@]} ]]; then
        oldname="${FUNCNAME[oldname + 1]}"
    fi
    name="common_${oldname#common.}"
    echo "${!name:-$oldname}"
}

common.Alias() {
    if [[ $# -ne 2 || -z $1 || -z $2 ]]; then
        echo "$(common.GetAlias): The must be only two parameters of nonzero length" >&2
        return 1;
    fi
    eval "alias $1='$2'"
    local "f=${2##*common.}"
    f="${f%%;*}"
    local "v=common_$f"
    f="common.$f"
    if [[ -n ${!v:-} ]]; then
        echo "$(common.GetAlias): $1: Function \`$f' already paired with name \`${!v}'" >&2
        return 1;
    fi
    shopt -s expand_aliases
    eval "$v=\"$1\""
}

common.ChangeAlias() {
    if [[ $# -lt 1 || $# -gt 2 ]]; then
        echo "usage: $(common.GetAlias) old_name [new_name]" >&2
        return "1"
    elif ! alias "$1" &>"/dev/null"; then
        echo "$(common.GetAlias): $1: Name not found" >&2
        return 1;
    fi
    local "s=$(alias "$1")" 
    s="${s#alias $1=\'}"
    s="${s%\'}"
    local "f=${s##*common.}"
    f="${f%%;*}"
    local "v=common_$f"
    f="common.$f"
    if [[ ${!v:-} != "$1" ]]; then
        echo "$(common.GetAlias): $1: Name not paired with a function \`$f'" >&2
        return 1;
    elif [[ $# -gt 1 ]]; then
        eval "alias $2='$s'"
        eval "$v=\"$2\""
    else
        unset "$v"
    fi
    unalias "$1"
}

common.Alias exception             'common.Exception'
common.Alias throw                 'common.Throw'
common.Alias try                   '{ if common.Try; then'
common.Alias yrt                   'common.EchoExitStatus; fi; common.yrT; }'
common.Alias catch                 '{ while common.Catch'
common.Alias hctac                 'common.hctaC -r; done; common.hctaC; }'
common.Alias finally               '{ if common.Finally; then'
common.Alias yllanif               'fi; common.yllaniF; }'
common.Alias caught                'common.Caught'
common.Alias EchoExitStatus        'common.EchoExitStatus'
common.Alias EnableThrowOnError    'common.EnableThrowOnError'
common.Alias DisableThrowOnError   'common.DisableThrowOnError'
common.Alias GetStatus             'common.GetStatus'
common.Alias SetStatus             'common.SetStatus'
common.Alias GetMessage            'common.GetMessage'
common.Alias MessageCount          'common.MessageCount'
common.Alias CopyMessages          'common.CopyMessages'
common.Alias TryCatchFinally       'common.TryCatchFinally'
common.Alias DefaultErrHandler     'common.DefaultErrHandler'
common.Alias DefaultUnhandled      'common.DefaultUnhandled'
common.Alias CallStack             'common.CallStack'
common.Alias ChangeAlias           'common.ChangeAlias'
common.Alias TryCatchFinallyAlias  'common.Alias'

common.CallStack() {
    local -i "i" "j" "k" "subshell=${2:-0}" "wi" "wl" "wn"
    local "format= %*s  %*s  %-*s  %s\n" "name"
    eval local "lineno=('' ${BASH_LINENO[@]})"
    for (( i=${1:-0},j=wi=wl=wn=0; i<${#FUNCNAME[@]}; ++i,++j )); do  
        name="$(common.GetAlias "$i")"
        let "wi = ${#j} > wi ? wi = ${#j} : wi"
        let "wl = ${#lineno[i]} > wl ? wl = ${#lineno[i]} : wl"
        let "wn = ${#name} > wn ? wn = ${#name} : wn"
    done
    for (( i=${1:-0},j=0; i<${#FUNCNAME[@]}; ++i,++j )); do
        ! let "k = ${#FUNCNAME[@]} - i - 1"
        name="$(common.GetAlias "$i")"
        printf "$format" "$wi" "$j" "$wl" "${lineno[i]}" "$wn" "$name" "${BASH_SOURCE[i]}"
    done
}

common.Echo() {
    [[ $common_options != *d* ]] || echo "$@" >"$common_file"
}

common.DefaultErrHandler() {
    echo "Orginal Status: $common_status"
    echo "Exception Type: ERR"
}

common.Exception() {
    common.TryCatchFinallyVerify || return
    if [[ $# -eq 0 ]]; then
        echo "$(common.GetAlias): At least one parameter is required" >&2
        return "1"         
    elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ]]; then
        echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
        return "1"
    fi
    let "common_status = 10#$1"
    shift
    common_messages=()
    for message in "$@"; do
        common_messages+=("$message")
    done
    if [[ $common_options == *c* ]]; then
        echo "Call Stack:" >"$common_fifo"
        common.CallStack "2" >"$common_fifo"
    fi
}

common.Throw() {
    common.TryCatchFinallyVerify || return
    local "message"
    if ! common.TryCatchFinallyExists; then
        echo "$(common.GetAlias): No Try-Catch-Finally exists" >&2
        return "1"        
    elif [[ $# -eq 0 && common_status -eq 0 ]]; then
        echo "$(common.GetAlias): No previous unhandled exception" >&2 
        return "1"
    elif [[ $# -gt 0 && ( ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ) ]]; then
        echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
        return "1"
    fi
    common.Echo -n "In Throw ?=$common_status "
    common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL #=$#"
    if [[ $common_options == *k* ]]; then
        common.CallStack "2" >"$common_file"
    fi
    if [[ $# -gt 0 ]]; then
        let "common_status = 10#$1"
        shift
        for message in "$@"; do
            echo "$message" >"$common_fifo"
        done
        if [[ $common_options == *c* ]]; then
            echo "Call Stack:" >"$common_fifo"
            common.CallStack "2" >"$common_fifo"
        fi
    elif [[ ${#common_messages[@]} -gt 0 ]]; then
        for message in "${common_messages[@]}"; do
            echo "$message" >"$common_fifo"
        done
    fi
    chmod "0400" "$common_fifo"
    common.Echo "Still in Throw $=$common_status subshell=$BASH_SUBSHELL #=$# -=$-"
    exit "$common_status"
}

common.ErrHandler() {
    common_status=$?
    trap ERR
    common.Echo -n "In ErrHandler ?=$common_status debug=$common_options "
    common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL order=$common_order"
    if [[ -w "$common_fifo" ]]; then
        if [[ $common_options != *e* ]]; then
            common.Echo "ErrHandler is ignoring"
            common_status="0"
            return "$common_status" # value is ignored
        fi
        if [[ $common_options == *k* ]]; then
            common.CallStack "2" >"$common_file"
        fi
        common.Echo "Calling ${common_errHandler:-}"
        eval "${common_errHandler:-} \"${BASH_LINENO[0]}\" \"${BASH_SOURCE[1]}\" \"${FUNCNAME[1]}\" >$common_fifo <$common_fifo"
        if [[ $common_options == *c* ]]; then
            echo "Call Stack:" >"$common_fifo"
            common.CallStack "2" >"$common_fifo"
        fi
        chmod "0400" "$common_fifo"
    fi
    common.Echo "Still in ErrHandler $=$common_status subshell=$BASH_SUBSHELL -=$-"
    if [[ common_trySubshell -eq BASH_SUBSHELL ]]; then
        return "$common_status" # value is ignored   
    else
        exit "$common_status"
    fi
}

common.Token() {
    local "name"
    case $1 in
    b) name="before";;
    t) name="$common_Try";;
    y) name="$common_yrT";;
    c) name="$common_Catch";;
    h) name="$common_hctaC";;
    f) name="$common_yllaniF";;
    l) name="$common_Finally";;
    *) name="unknown";;
    esac
    echo "$name"
}

common.TryCatchFinallyNext() {
    common.ShellInit
    local "previous=$common_order" "errmsg"
    common_order="$2"
    if [[ $previous != $1 ]]; then
        errmsg="${BASH_SOURCE[2]}: line ${BASH_LINENO[1]}: syntax error_near unexpected token \`$(common.Token "$2")'"
        echo "$errmsg" >&2
        [[ /dev/fd/2 -ef $common_file ]] || echo "$errmsg" >"$common_file"
        kill -s INT 0
        return "1"        
    fi
}

common.ShellInit() {
    if [[ common_initSubshell -ne BASH_SUBSHELL ]]; then
        common_initSubshell="$BASH_SUBSHELL"
        common_order="b"
    fi
}

common.Try() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[byhl]" "t" || return 
    common_status="0"
    common_subshell="$common_trySubshell"
    common_trySubshell="$BASH_SUBSHELL"
    common_messages=()
    common.Echo "-------------> Setting try=$common_trySubshell at subshell=$BASH_SUBSHELL"
}

common.yrT() {
    local "status=$?"
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[t]" "y" || return 
    common.Echo -n "Entered yrT ?=$status status=$common_status "
    common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL"
    if [[ common_status -ne 0 ]]; then    

        common.Echo "Build message array. ?=$common_status, subshell=$BASH_SUBSHELL"
        local "message=" "eof=TRY_CATCH_FINALLY_END_OF_MESSAGES_$RANDOM"
        chmod "0600" "$common_fifo"
        echo "$eof" >"$common_fifo"
        common_messages=()
        while read "message"; do

            common.Echo "----> $message"

            [[ $message != *$eof ]] || break
            common_messages+=("$message")
        done <"$common_fifo"
    fi

    common.Echo "In ytT status=$common_status"
    common_trySubshell="$common_subshell"
}

common.Catch() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[yh]" "c" || return 
    [[ common_status -ne 0 ]] || return "1"
    local "parameter" "pattern" "value"
    local "toggle=true" "compare=p" "options=$-"
    local -i "i=-1" "status=0"
    set -f
    for parameter in "$@"; do
        if "$toggle"; then
            toggle="false"
            if [[ $parameter =~ ^-[notepr]$ ]]; then
                compare="${parameter#-}"
                continue 
            fi
        fi
        toggle="true"
        while "true"; do
            eval local "patterns=($parameter)"
            if [[ ${#patterns[@]} -gt 0 ]]; then
                for pattern in "${patterns[@]}"; do
                    [[ i -lt ${#common_messages[@]} ]] || break
                    if [[ i -lt 0 ]]; then
                        value="$common_status"
                    else
                        value="${common_messages[i]}"
                    fi
                    case $compare in
                    [ne]) [[ ! $value == "$pattern" ]] || break 2;;
                    [op]) [[ ! $value == $pattern ]] || break 2;;
                    [tr]) [[ ! $value =~ $pattern ]] || break 2;;
                    esac
                done
            fi
            if [[ $compare == [not] ]]; then
                let "++i,1"
                continue 2
            else
                status="1"
                break 2
            fi
        done
        if [[ $compare == [not] ]]; then
            status="1"
            break
        else
            let "++i,1"
        fi
    done
    [[ $options == *f* ]] || set +f
    return "$status"
} 

common.hctaC() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[c]" "h" || return 
    [[ $# -ne 1 || $1 != -r ]] || common_status="0"
}

common.Finally() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[ych]" "f" || return 
}

common.yllaniF() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[f]" "l" || return 
    [[ common_status -eq 0 ]] || common.Throw
}

common.Caught() {
    common.TryCatchFinallyVerify || return
    [[ common_status -eq 0 ]] || return 1
}

common.EchoExitStatus() {
    return "${1:-$?}"
}

common.EnableThrowOnError() {
    common.TryCatchFinallyVerify || return
    [[ $common_options == *e* ]] || common_options+="e"
}

common.DisableThrowOnError() {
    common.TryCatchFinallyVerify || return
    common_options="${common_options/e}"
}

common.GetStatus() {
    common.TryCatchFinallyVerify || return
    echo "$common_status"
}

common.SetStatus() {
    common.TryCatchFinallyVerify || return
    if [[ $# -ne 1 ]]; then
        echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
        return "1"         
    elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ]]; then
        echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
        return "1"
    fi
    let "common_status = 10#$1"
}

common.GetMessage() {
    common.TryCatchFinallyVerify || return
    local "upper=${#common_messages[@]}"
    if [[ upper -eq 0 ]]; then
        echo "$(common.GetAlias): $1: There are no messages" >&2
        return "1"
    elif [[ $# -ne 1 ]]; then
        echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
        return "1"         
    elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -ge upper ]]; then
        echo "$(common.GetAlias): $1: First parameter was an invalid index" >&2
        return "1"
    fi
    echo "${common_messages[$1]}"
}

common.MessageCount() {
    common.TryCatchFinallyVerify || return
    echo "${#common_messages[@]}"
}

common.CopyMessages() {
    common.TryCatchFinallyVerify || return
    if [[ $# -ne 1 ]]; then
        echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
        return "1"         
    elif [[ ${#common_messages} -gt 0 ]]; then
        eval "$1=(\"\${common_messages[@]}\")"
    else
        eval "$1=()"
    fi
}

common.TryCatchFinallyExists() {
    [[ ${common_fifo:-u} != u ]]
}

common.TryCatchFinallyVerify() {
    local "name"
    if ! common.TryCatchFinallyExists; then
        echo "$(common.GetAlias "1"): No Try-Catch-Finally exists" >&2
        return "2"        
    fi
}

common.GetOptions() {
    local "opt"
    local "name=$(common.GetAlias "1")"
    if common.TryCatchFinallyExists; then
        echo "$name: A Try-Catch-Finally already exists" >&2
        return "1"        
    fi
    let "OPTIND = 1"
    let "OPTERR = 0"
    while getopts ":cdeh:ko:u:v:" opt "$@"; do
        case $opt in
        c)  [[ $common_options == *c* ]] || common_options+="c";;
        d)  [[ $common_options == *d* ]] || common_options+="d";;
        e)  [[ $common_options == *e* ]] || common_options+="e";;
        h)  common_errHandler="$OPTARG";;
        k)  [[ $common_options == *k* ]] || common_options+="k";;
        o)  common_file="$OPTARG";;
        u)  common_unhandled="$OPTARG";;
        v)  common_command="$OPTARG";;
        \?) #echo "Invalid option: -$OPTARG" >&2
            echo "$name: Illegal option: $OPTARG" >&2
            return "1";;
        :)  echo "$name: Option requires an argument: $OPTARG" >&2
            return "1";;
        *)  echo "$name: An error occurred while parsing options." >&2
            return "1";;
        esac
    done

    shift "$((OPTIND - 1))"
    if [[ $# -lt 1 ]]; then
        echo "$name: The fifo_file parameter is missing" >&2
        return "1"
    fi
    common_fifo="$1"
    if [[ ! -p $common_fifo ]]; then
        echo "$name: $1: The fifo_file is not an open FIFO" >&2
        return "1"  
    fi

    shift
    if [[ $# -lt 1 ]]; then
        echo "$name: The function parameter is missing" >&2
        return "1"
    fi
    common_function="$1"
    if ! chmod "0600" "$common_fifo"; then
        echo "$name: $common_fifo: Can not change file mode to 0600" >&2
        return "1"
    fi

    local "message=" "eof=TRY_CATCH_FINALLY_END_OF_FILE_$RANDOM"
    { echo "$eof" >"$common_fifo"; } 2>"/dev/null"
    if [[ $? -ne 0 ]]; then
        echo "$name: $common_fifo: Can not write" >&2
        return "1"
    fi   
    { while [[ $message != *$eof ]]; do
        read "message"
    done <"$common_fifo"; } 2>"/dev/null"
    if [[ $? -ne 0 ]]; then
        echo "$name: $common_fifo: Can not read" >&2
        return "1"
    fi   

    return "0"
}

common.DefaultUnhandled() {
    local -i "i"
    echo "-------------------------------------------------"
    echo "$(common.GetAlias "common.TryCatchFinally"): Unhandeled exception occurred"
    echo "Status: $(GetStatus)"
    echo "Messages:"
    for ((i=0; i<$(MessageCount); i++)); do
        echo "$(GetMessage "$i")"
    done
    echo "-------------------------------------------------"
}

common.TryCatchFinally() {
    local "common_file=/dev/fd/2"
    local "common_errHandler=common.DefaultErrHandler"
    local "common_unhandled=common.DefaultUnhandled"
    local "common_options="
    local "common_fifo="
    local "common_function="
    local "common_flags=$-"
    local "common_trySubshell=-1"
    local "common_initSubshell=-1"
    local "common_subshell"
    local "common_status=0"
    local "common_order=b"
    local "common_command="
    local "common_messages=()"
    local "common_handler=$(trap -p ERR)"
    [[ -n $common_handler ]] || common_handler="trap ERR"

    common.GetOptions "$@" || return "$?"
    shift "$((OPTIND + 1))"

    [[ -z $common_command ]] || common_command+="=$"
    common_command+='("$common_function" "$@")'

    set -E
    set +e
    trap "common.ErrHandler" ERR
    if true; then
        common.Try 
        eval "$common_command"
        common.EchoExitStatus
        common.yrT
    fi
    while common.Catch; do
        "$common_unhandled" >&2
        break
        common.hctaC -r
    done
    common.hctaC
    [[ $common_flags == *E* ]] || set +E
    [[ $common_flags != *e* ]] || set -e
    [[ $common_flags != *f* || $- == *f* ]] || set -f
    [[ $common_flags == *f* || $- != *f* ]] || set +f
    eval "$common_handler"
    return "$((common_status?2:0))"
}

Mapping a JDBC ResultSet to an object

I would like to hint on q2o. It is a JPA based Java object mapper which helps with many of the tedious SQL and JDBC ResultSet related tasks, but without all the complexity an ORM framework comes with. With its help mapping a ResultSet to an object is as easy as this:

while(rs.next()) {
    users.add(Q2Obj.fromResultSet(rs, User.class));
}

More about q2o can be found here.

Add a UIView above all, even the navigation bar

@Nam's answer works great if you just want to display your custom view but if your custom view needs user interaction you need to disable interaction for the navigationBar.

self.navigationController.navigationBar.layer.zPosition = -1
self.navigationController.navigationBar.isUserInteractionEnabled = false

Like said in Nam's answer don't forget to reverse these changes:

self.navigationController.navigationBar.layer.zPosition = 0
self.navigationController.navigationBar.isUserInteractionEnabled = true


You can do this in a better way with an extension:

extension UINavigationBar {
    func toggle() {
        if self.layer.zPosition == -1 {
            self.layer.zPosition = 0
            self.isUserInteractionEnabled = true
        } else {
            self.layer.zPosition = -1
            self.isUserInteractionEnabled = false
        }
    }
}

And simply use it like this:

self.navigationController.navigationBar.toggle()

Responsive bootstrap 3 timepicker?

As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

This is an old post of mine, the accepted answers are good for the most part. However i decided to benchmark each solution and another obvious one (just for fun). I wondered if there was a difference between the regex patterns on different browsers with different sized strings.

So basically i used jsPerf on

  • Testing in Chrome 65.0.3325 / Windows 10 0.0.0
  • Testing in Edge 16.16299.0 / Windows 10 0.0.0

The regex patterns i tested were

  • /[\W_]+/g
  • /[^a-z0-9]+/gi
  • /[^a-zA-Z0-9]+/g

I loaded them up with a string length of random characters

  • length 5000
  • length 1000
  • length 200

Example javascript i used var newstr = str.replace(/[\W_]+/g," ");

Each run consisted of 50 or more sample on each regex, and i run them 5 times on each browser.

Lets race our horses!

Results

                                Chrome                  Edge
Chars   Pattern                 Ops/Sec     Deviation   Op/Sec      Deviation
------------------------------------------------------------------------
5,000   /[\W_]+/g                19,977.80  1.09         10,820.40  1.32
5,000   /[^a-z0-9]+/gi           19,901.60  1.49         10,902.00  1.20
5,000   /[^a-zA-Z0-9]+/g         19,559.40  1.96         10,916.80  1.13
------------------------------------------------------------------------
1,000   /[\W_]+/g                96,239.00  1.65         52,358.80  1.41
1,000   /[^a-z0-9]+/gi           97,584.40  1.18         52,105.00  1.60
1,000   /[^a-zA-Z0-9]+/g         96,965.80  1.10         51,864.60  1.76
------------------------------------------------------------------------
  200   /[\W_]+/g               480,318.60  1.70        261,030.40  1.80
  200   /[^a-z0-9]+/gi          476,177.80  2.01        261,751.60  1.96
  200   /[^a-zA-Z0-9]+/g        486,423.00  0.80        258,774.20  2.15

Truth be known, Regex in both browsers (taking into consideration deviation) were nearly indistinguishable, however i think if it run this even more times the results would become a little more clearer (but not by much).

Theoretical scaling for 1 character

                            Chrome                        Edge
Chars   Pattern             Ops/Sec     Scaled            Op/Sec    Scaled
------------------------------------------------------------------------
5,000   /[\W_]+/g            19,977.80  99,889,000       10,820.40  54,102,000
5,000   /[^a-z0-9]+/gi       19,901.60  99,508,000       10,902.00  54,510,000
5,000   /[^a-zA-Z0-9]+/g     19,559.40  97,797,000       10,916.80  54,584,000
------------------------------------------------------------------------

1,000   /[\W_]+/g            96,239.00  96,239,000       52,358.80  52,358,800
1,000   /[^a-z0-9]+/gi       97,584.40  97,584,400       52,105.00  52,105,000
1,000   /[^a-zA-Z0-9]+/g     96,965.80  96,965,800       51,864.60  51,864,600
------------------------------------------------------------------------

  200   /[\W_]+/g           480,318.60  96,063,720      261,030.40  52,206,080
  200   /[^a-z0-9]+/gi      476,177.80  95,235,560      261,751.60  52,350,320
  200   /[^a-zA-Z0-9]+/g    486,423.00  97,284,600      258,774.20  51,754,840

I wouldn't take to much into these results as this is not really a significant differences, all we can really tell is edge is slower :o . Additionally that i was super bored.

Anyway you can run the benchmark for your self.

Jsperf Benchmark here

Preventing HTML and Script injections in Javascript

I use this function htmlentities($string):

$msg = "<script>alert("hello")</script> <h1> Hello World </h1>"
$msg = htmlentities($msg);
echo $msg;

Is there a splice method for strings?

It is faster to slice the string twice, like this:

function spliceSlice(str, index, count, add) {
  // We cannot pass negative indexes directly to the 2nd slicing operation.
  if (index < 0) {
    index = str.length + index;
    if (index < 0) {
      index = 0;
    }
  }

  return str.slice(0, index) + (add || "") + str.slice(index + count);
}

than using a split followed by a join (Kumar Harsh's method), like this:

function spliceSplit(str, index, count, add) {
  var ar = str.split('');
  ar.splice(index, count, add);
  return ar.join('');
}

Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)

Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.

How do I vertically center an H1 in a div?

you can achieve vertical aligning with display:table-cell:

#section1 {
    height: 90%; 
    text-align:center; 
    display:table;
    width:100%;
}

#section1 h1 {display:table-cell; vertical-align:middle}

Example

Update - CSS3

For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:

#section1 {
    height: 90%; 
    width:100%;
    display:flex;
    align-items: center;
    justify-content: center;
}

Updated fiddle

How to append multiple values to a list in Python

letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
... 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
    

How do I change Bootstrap 3 column order on mobile layout?

In Bootstrap 4, if you want to do something like this:

    Mobile  |   Desktop
-----------------------------
    A       |       A
    C       |   B       C
    B       |       D
    D       |

You need to reverse the order of B then C then apply order-{breakpoint}-first to B. And apply two different settings, one that will make them share the same cols and other that will make them take the full width of the 12 cols:

  • Smaller screens: 12 cols to B and 12 cols to C

  • Larger screens: 12 cols between the sum of them (B + C = 12)

Like this

<div class='row no-gutters'>
    <div class='col-12'>
        A
    </div>
    <div class='col-12'>
        <div class='row no-gutters'>
            <div class='col-12 col-md-6'>
                C
            </div>
            <div class='col-12 col-md-6 order-md-first'>
                B
            </div>
        </div>
    </div>
    <div class='col-12'>
        D
    </div>
</div>

Demo: https://codepen.io/anon/pen/wXLGKa

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

How to apply a CSS filter to a background image

The following is a simple solution for modern browsers in pure CSS with a 'before' pseudo element, like the solution from Matthew Wilcoxson.

To avoid the need of accessing the pseudo element for changing the image and other attributes in JavaScript, simply use inherit as the value and access them via the parent element (here body).

body::before {
    content: ""; /* Important */
    z-index: -1; /* Important */
    position: inherit;
    left: inherit;
    top: inherit;
    width: inherit;
    height: inherit;
    background-image: inherit;
    background-size: cover;
    filter: blur(8px);
}

body {
  background-image: url("xyz.jpg");
  background-size: 0 0;  /* Image should not be drawn here */
  width: 100%;
  height: 100%;
  position: fixed; /* Or absolute for scrollable backgrounds */
}

Netbeans - Error: Could not find or load main class

If none of the above works (Setting Main class, Clean and Build, deleting the cache) and you have a Maven project, try:

mvn clean install

on the command line.

How to write lists inside a markdown table?

If you use the html approach:

don't add blank lines

Like this:

<table>
    <tbody>

        <tr>
            <td>1</td>
            <td>2</td>
        </tr>

        <tr>
            <td>1</td>
            <td>2</td>
        </tr>

    </tbody>
</table>

the markup will break.

Remove blank lines:

<table>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
    </tbody>
</table>

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

Yes, there is a better way: You can use the $parse service in your directive to evaluate an expression in the context of the parent scope while binding certain identifiers in the expression to values visible only inside your directive:

$parse(attributes.callback)(scope.$parent, { arg2: yourSecondArgument });

Add this line to the link function of the directive where you can access the directive's attributes.

Your callback attribute may then be set like callback = "callback(item.id, arg2)" because arg2 is bound to yourSecondArgument by the $parse service inside the directive. Directives like ng-click let you access the click event via the $event identifier inside the expression passed to the directive by using exactly this mechanism.

Note that you do not have to make callback a member of your isolated scope with this solution.

Representing Directory & File Structure in Markdown Syntax

If you're using Atom editor, you can accomplish this by the ascii-tree package.

You can write the following tree:

root
+-- dir1
    +--file1
+-- dir2
    +-- file2

and convert it to the following by selecting it and pressing ctrl-alt-t:

root
+-- dir1
¦   +-- file1
+-- dir2
    +-- file2

How to add fixed button to the bottom right of page

This will be helpful for the right bottom rounded button

HTML :

      <a class="fixedButton" href>
         <div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
      </a>
    

CSS:

       .fixedButton{
            position: fixed;
            bottom: 0px;
            right: 0px; 
            padding: 20px;
        }
        .roundedFixedBtn{
          height: 60px;
          line-height: 80px;  
          width: 60px;  
          font-size: 2em;
          font-weight: bold;
          border-radius: 50%;
          background-color: #4CAF50;
          color: white;
          text-align: center;
          cursor: pointer;
        }
    

Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/

CSS float right not working correctly

You have not used float:left command for your text.

How can I get input radio elements to horizontally align?

Here is updated Fiddle

Simply remove </br> between input radio's

<div class="clearBoth"></div>
<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change
<div class="clearBoth"></div>

Xcode 5 and iOS 7: Architecture and Valid architectures

None of the answers worked and then I was forgetting to set minimum deployment target which can be found in Project -> General -> Deployment Info -> Deployment Target -> 8.0

Example

How to convert string to binary?

We just need to encode it.

'string'.encode('ascii')

Responsive image align center bootstrap 3

Try this code it will work for small icons too with bootstrap 4 because there is no center-block class is bootstrap 4 so try this method it will be helpful. You can change the position of the image by setting the .col-md-12 to .col-md-8 or .col-md-4, it's upto you.

<div class="container">
       <div class="row">
          <div class="col-md-12">
            <div class="text-xs-center text-lg-center">
           <img src="" class="img-thumbnail">
           </div>
          </div>
       </div>
  </div>

How can I create a link to a local file on a locally-run web page?

If you are running IIS on your PC you can add the directory that you are trying to reach as a Virtual Directory. To do this you right-click on your Site in ISS and press "Add Virtual Directory". Name the virtual folder. Point the virtual folder to your folder location on your local PC. You also have to supply credentials that has privileges to access the specific folder eg. HOSTNAME\username and password. After that you can access the file in the virtual folder as any other file on your site.

http://sitename.com/virtual_folder_name/filename.fileextension

By the way, this also works with Chrome that otherwise does not accept the file-protocol file://

Hope this helps someone :)

Difference between no-cache and must-revalidate

max-age=0, must-revalidate and no-cache aren't exactly identical. With must-revalidate, if the server doesn't respond to a revalidation request, the browser/proxy is supposed to return a 504 error. With no-cache, it would just show the cached content, which would be probably preferred by the user (better to have something stale than nothing at all). This is why must-revalidate is intended for critical transactions only.

Overlay a background-image with an rgba background-color

Ideally the background property would allow us to layer various backgrounds similar to the background image layering detailed at http://www.css3.info/preview/multiple-backgrounds/. Unfortunately, at least in Chrome (40.0.2214.115), adding an rgba background alongside a url() image background seems to break the property.

The solution I've found is to render the rgba layer as a 1px*1px Base64 encoded image and inline it.

.the-div:hover {
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgkAQAABwAGkn5GOoAAAAASUVORK5CYII=), url("the-image.png");
}

for base64 encoded 1*1 pixel images I used http://px64.net/

Here is your jsfiddle with these changes made. http://jsfiddle.net/325Ft/49/ (I also swapped the image to one that still exists on the internet)

Status bar and navigation bar appear over my view's bounds in iOS 7

edgesForExtendedLayout does the trick for iOS 7. However, if you build the app across iOS 7 SDK and deploy it in iOS 6, the navigation bar appears translucent and the views go beneath it. So, to fix it for both iOS 7 as well as for iOS 6 do this:

self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
    self.edgesForExtendedLayout = UIRectEdgeNone;   // iOS 7 specific

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

How to move div vertically down using CSS

if div.title is a div then put this:

left: 0;
bottom: 0;

Preventing SQL injection in Node.js

The easiest way is to handle all of your database interactions in its own module that you export to your routes. If your route has no context of the database then SQL can't touch it anyway.

boolean in an if statement

The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.

How to Add a Dotted Underline Beneath HTML Text

Without CSS, you basically are stuck with using an image tag. Basically make an image of the text and add the underline. That basically means your page is useless to a screen reader.

With CSS, it is simple.

HTML:

<u class="dotted">I like cheese</u>

CSS:

u.dotted{
  border-bottom: 1px dashed #999;
  text-decoration: none; 
}

Running Example

Example page

<!DOCTYPE HTML>
<html>
<head>
    <style>
        u.dotted{
          border-bottom: 1px dashed #999;
          text-decoration: none; 
        }
    </style>
</head>
<body>
    <u class="dotted">I like cheese</u>
</body>
</html>

Pure CSS collapse/expand div

You just need to iterate the anchors in the two links.

<a href="#hide2" class="hide" id="hide2">+</a>
<a href="#show2" class="show" id="show2">-</a>

See this jsfiddle http://jsfiddle.net/eJX8z/

I also added some margin to the FAQ call to improve the format.

Run jQuery function onclick

Using obtrusive JavaScript (i.e. inline code) as in your example, you can attach the click event handler to the div element with the onclick attribute like so:

 <div id="some-id" class="some-class" onclick="slideonlyone('sms_box');">
     ...
 </div>

However, the best practice is unobtrusive JavaScript which you can easily achieve by using jQuery's on() method or its shorthand click(). For example:

 $(document).ready( function() {
     $('.some-class').on('click', slideonlyone('sms_box'));
     // OR //
     $('.some-class').click(slideonlyone('sms_box'));
 });

Inside your handler function (e.g. slideonlyone() in this case) you can reference the element that triggered the event (e.g. the div in this case) with the $(this) object. For example, if you need its ID, you can access it with $(this).attr('id').


EDIT

After reading your comment to @fmsf below, I see you also need to dynamically reference the target element to be toggled. As @fmsf suggests, you can add this information to the div with a data-attribute like so:

<div id="some-id" class="some-class" data-target="sms_box">
    ...
</div>

To access the element's data-attribute you can use the attr() method as in @fmsf's example, but the best practice is to use jQuery's data() method like so:

 function slideonlyone() {
     var trigger_id = $(this).attr('id'); // This would be 'some-id' in our example
     var target_id  = $(this).data('target'); // This would be 'sms_box'
     ...
 }

Note how data-target is accessed with data('target'), without the data- prefix. Using data-attributes you can attach all sorts of information to an element and jQuery would automatically add them to the element's data object.

Redirect output of mongo query to a csv file

I know this question is old but I spend an hour trying to export a complex query to csv and I wanted to share my thoughts. First I couldn't get any of the json to csv converters to work (although this one looked promising). What I ended up doing was manually writing the csv file in my mongo script.

This is a simple version but essentially what I did:

print("name,id,email");
db.User.find().forEach(function(user){
  print(user.name+","+user._id.valueOf()+","+user.email);
});

This I just piped the query to stdout

mongo test export.js > out.csv

where test is the name of the database I use.

how to have two headings on the same line in html

The Css vertical-align property should help you out here:

vertical-align: bottom;

is what you need for your smaller header :)

Vertical-Align

How create a new deep copy (clone) of a List<T>?

List<Book> books_2 = new List<Book>(books_2.ToArray());

That should do exactly what you want. Demonstrated here.

How to make HTML input tag only accept numerical values?

Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of code of input an integer number:

_x000D_
_x000D_
<!doctype html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" >_x000D_
<head>_x000D_
    <title>Input Key Filter Test</title>_x000D_
 <meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>_x000D_
 _x000D_
 <!-- For compatibility of IE browser with audio element in the beep() function._x000D_
 https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->_x000D_
 <meta http-equiv="X-UA-Compatible" content="IE=9"/>_x000D_
 _x000D_
 <link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">  _x000D_
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>_x000D_
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>_x000D_
 _x000D_
</head>_x000D_
<body>_x000D_
 <h1>Integer field</h1>_x000D_
<input id="Integer">_x000D_
<script>_x000D_
 CreateIntFilter("Integer", function(event){//onChange event_x000D_
   inputKeyFilter.RemoveMyTooltip();_x000D_
   var elementNewInteger = document.getElementById("NewInteger");_x000D_
   var integer = parseInt(this.value);_x000D_
   if(inputKeyFilter.isNaN(integer, this)){_x000D_
    elementNewInteger.innerHTML = "";_x000D_
    return;_x000D_
   }_x000D_
   //elementNewInteger.innerText = integer;//Uncompatible with FireFox_x000D_
   elementNewInteger.innerHTML = integer;_x000D_
  }_x000D_
  _x000D_
  //onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)_x000D_
  , function(event){ inputKeyFilter.isNaN(parseInt(this.value), this); }_x000D_
 );_x000D_
</script>_x000D_
 New integer: <span id="NewInteger"></span>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Also see my page "Integer field:" of the example of the input key filter

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

JavaScript: get code to run every minute

You could use setInterval for this.

<script type="text/javascript">
function myFunction () {
    console.log('Executed!');
}

var interval = setInterval(function () { myFunction(); }, 60000);
</script>

Disable the timer by setting clearInterval(interval).

See this Fiddle: http://jsfiddle.net/p6NJt/2/

R - Markdown avoiding package loading messages

My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.

{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)

#data wrangling
library(dplyr)

#text processing
library(stringi)

What's the difference between console.dir and console.log?

I think Firebug does it differently than Chrome's dev tools. It looks like Firebug gives you a stringified version of the object while console.dir gives you an expandable object. Both give you the expandable object in Chrome, and I think that's where the confusion might come from. Or it's just a bug in Chrome.

In Chrome, both do the same thing. Expanding on your test, I have noticed that Chrome gets the current value of the object when you expand it.

> o = { foo: 1 }
> console.log(o)
Expand now, o.foo = 1
> o.foo = 2
o.foo is still displayed as 1 from previous lines

> o = { foo: 1 }
> console.log(o)
> o.foo = 2
Expand now, o.foo = 2

You can use the following to get a stringified version of an object if that's what you want to see. This will show you what the object is at the time this line is called, not when you expand it.

console.log(JSON.stringify(o));

CSS - center two images in css side by side

I understand that this question is old, but there is a good solution for it in HTML5. You can wrap it all in a <figure></figure> tag. The code would look something like this:

<div id="wrapper">
<figure>

<a href="mailto:[email protected]">
<img id="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp- 
content/uploads/2012/07/email-icon-e1343123697991.jpg"/>
</a>

<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img id="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp- 
content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
</a>

</figure>
</div>

and the CSS:

#wrapper{
 text-align:center;
}

How to add color to Github's README.md file

As an alternative to rendering a raster image, you can embed a SVG file:

<a><img src="http://dump.thecybershadow.net/6c736bfd11ded8cdc5e2bda009a6694a/colortext.svg"/></a>

You can then add color text to the SVG file as usual:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" 
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     width="100" height="50"
>
  <text font-size="16" x="10" y="20">
    <tspan fill="red">Hello</tspan>,
    <tspan fill="green">world</tspan>!
  </text>
</svg>

Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.

Demo: https://gist.github.com/CyberShadow/95621a949b07db295000

Convert string with comma to integer

Some more convenient

"1,1200.00".gsub(/[^0-9]/,'') 

it makes "1 200 200" work properly aswell

Finding moving average from data points in Python

There is a problem with the accepted answer. I think we need to use "valid" instead of "same" here - return numpy.convolve(interval, window, 'same') .

As an Example try out the MA of this data-set = [1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6] - the result should be [4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6,4.6,7.0,6.8], but having "same" gives us an incorrect output of [2.6,3.0,4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6, 4.6,7.0,6.8,6.2,4.8]

Rusty code to try this out -:

result=[]
dataset=[1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6]
window_size=5
for index in xrange(len(dataset)):
    if index <=len(dataset)-window_size :
        tmp=(dataset[index]+ dataset[index+1]+ dataset[index+2]+ dataset[index+3]+ dataset[index+4])/5.0
        result.append(tmp)
    else:
      pass

result==movingaverage(y, window_size) 

Try this with valid & same and see whether the math makes sense.

See also -: http://sentdex.com/sentiment-analysisbig-data-and-python-tutorials-algorithmic-trading/how-to-chart-stocks-and-forex-doing-your-own-financial-charting/calculate-simple-moving-average-sma-python/

Get string character by index - Java

The method you're looking for is charAt. Here's an example:

String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f

For more information, see the Java documentation on String.charAt. If you want another simple tutorial, this one or this one.

If you don't want the result as a char data type, but rather as a string, you would use the Character.toString method:

String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f

If you want more information on the Character class and the toString method, I pulled my info from the documentation on Character.toString.

Spring data JPA query with parameter properties

What you want is not possible. You have to create two parameters, and bind them separately:

select p from Person p where p.forename = :forename and p.surname = :surname
...
query.setParameter("forename", name.getForename());
query.setParameter("surname", name.getSurname());

What's the best way to iterate an Android Cursor?

How about using foreach loop:

Cursor cursor;
for (Cursor c : CursorUtils.iterate(cursor)) {
    //c.doSth()
}

However my version of CursorUtils should be less ugly, but it automatically closes the cursor:

public class CursorUtils {
public static Iterable<Cursor> iterate(Cursor cursor) {
    return new IterableWithObject<Cursor>(cursor) {
        @Override
        public Iterator<Cursor> iterator() {
            return new IteratorWithObject<Cursor>(t) {
                @Override
                public boolean hasNext() {
                    t.moveToNext();
                    if (t.isAfterLast()) {
                        t.close();
                        return false;
                    }
                    return true;
                }
                @Override
                public Cursor next() {
                    return t;
                }
                @Override
                public void remove() {
                    throw new UnsupportedOperationException("CursorUtils : remove : ");
                }
                @Override
                protected void onCreate() {
                    t.moveToPosition(-1);
                }
            };
        }
    };
}

private static abstract class IteratorWithObject<T> implements Iterator<T> {
    protected T t;
    public IteratorWithObject(T t) {
        this.t = t;
        this.onCreate();
    }
    protected abstract void onCreate();
}

private static abstract class IterableWithObject<T> implements Iterable<T> {
    protected T t;
    public IterableWithObject(T t) {
        this.t = t;
    }
}
}

Bootstrap modal appearing under background

I had this issue and the easiest way to fix it was addind z-index greater than 1040 on the modal-dialog div:

<div class="modal-dialog" style="z-index: 1100;">

I believe bootstrap create a div modal-backdrop fade in which in my case has the z-index 1040, so if You put the modal-dialog on top of this, it should not be grey out anymore.

Scroll part of content in fixed position container

What worked for me :

div#scrollable {
    overflow-y: scroll;
    max-height: 100vh;
}

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

SQLite in Android How to update a specific row

  1. I personally prefere .update for its convenience. But execsql will work same.
  2. You are right with your guess that the problem is your content values. You should create a ContentValue Object and put the values for your database row there.

This code should fix your example:

 ContentValues data=new ContentValues();
 data.put("Field1","bob");
 data.put("Field2",19);
 data.put("Field3","male");
 DB.update(Tablename, data, "_id=" + id, null);

REST API Token-based Authentication

Let me seperate up everything and solve approach each problem in isolation:

Authentication

For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.

Auth server load

If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.

Transmission Security

If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.

url = username:[email protected]/api/call/nonce

If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:

nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call

It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).

Secure secret storage

It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.

If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.

(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

HTML:

?<div class="header">This is the header</div>
<div class="content">This is the content</div>?????????????????????????????????

CSS:

?.header
{
    height:50px;
}
.content
{
    position:absolute;
    top: 50px;
    left:0px;
    right:0px;
    bottom:0px;
    overflow-y:scroll;        
}?

Javascript: The prettiest way to compare one value against multiple values

Why not using indexOf from array like bellow?

if ([foo, bar].indexOf(foobar) !== -1) {
    // do something
}

Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
     ELSE '"DECLINED"'
END

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

How do I 'git diff' on a certain directory?

Not only you can add a path, but you can add git diff --relative to get result relative to that folder.

git -C a/folder diff --relative

And with Git 2.28 (Q3 2020), the commands in the "diff" family learned to honor the "diff.relative" configuration variable.

See commit c28ded8 (22 May 2020) by Laurent Arnoud (spk).
(Merged by Junio C Hamano -- gitster -- in commit e34df9a, 02 Jun 2020)

diff: add config option relative

Signed-off-by: Laurent Arnoud
Acked-by: Ðoàn Tr?n Công Danh

The diff.relative boolean option set to true shows only changes in the current directory/value specified by the path argument of the relative option and shows pathnames relative to the aforementioned directory.

Teach --no-relative to override earlier --relative

Add for git-format-patch(1) options documentation --relative and --no-relative

The documentation now includes:

diff.relative:

If set to 'true', 'git diff' does not show changes outside of the directory and show pathnames relative to the current directory.

Best practices for SQL varchar column length

Adding to a_horse_with_no_name's answer you might find the following of interest...

it does not make any difference whether you declare a column as VARCHAR(100) or VACHAR(500).

-- try to create a table with max varchar length
drop table if exists foo;
create table foo(name varchar(65535) not null)engine=innodb;

MySQL Database Error: Row size too large.

-- try to create a table with max varchar length - 2 bytes for the length
drop table if exists foo;
create table foo(name varchar(65533) not null)engine=innodb;

Executed Successfully

-- try to create a table with max varchar length with nullable field
drop table if exists foo;
create table foo(name varchar(65533))engine=innodb;

MySQL Database Error: Row size too large.

-- try to create a table with max varchar length with nullable field
drop table if exists foo;
create table foo(name varchar(65532))engine=innodb;

Executed Successfully

Dont forget the length byte(s) and the nullable byte so:

name varchar(100) not null will be 1 byte (length) + up to 100 chars (latin1)

name varchar(500) not null will be 2 bytes (length) + up to 500 chars (latin1)

name varchar(65533) not null will be 2 bytes (length) + up to 65533 chars (latin1)

name varchar(65532) will be 2 bytes (length) + up to 65532 chars (latin1) + 1 null byte

Hope this helps :)

Executing JavaScript after X seconds

setTimeout will help you to execute any JavaScript code based on the time you set.

Syntax

setTimeout(code, millisec, lang)

Usage,

setTimeout("function1()", 1000);

For more details, see http://www.w3schools.com/jsref/met_win_settimeout.asp

jQuery Clone table row

Try this variation:

$(".tr_clone_add").live('click', CloneRow);

function CloneRow()
{
    $(this).closest('.tr_clone').clone().insertAfter(".tr_clone:last");
}

Turn a simple socket into an SSL socket

For others like me:

There was once an example in the SSL source in the directory demos/ssl/ with example code in C++. Now it's available only via the history: https://github.com/openssl/openssl/tree/691064c47fd6a7d11189df00a0d1b94d8051cbe0/demos/ssl

You probably will have to find a working version, I originally posted this answer at Nov 6 2015. And I had to edit the source -- not much.

Certificates: .pem in demos/certs/apps/: https://github.com/openssl/openssl/tree/master/demos/certs/apps

How can I make content appear beneath a fixed DIV element?

There is (at least) one wayhack to get truly dynamic height without javascript: insert the menu twice:

  • Once in the flow to position the following elements, and
  • once fixed for the desired visual effect.

_x000D_
_x000D_
<div id="the-menu-container">_x000D_
    <nav class="position-static">...</nav>_x000D_
    <nav class="position-fixed">...</nav>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Depending on the rest of your site, you might have to tweak the z-index styles of the <nav> elements.

Programmatically Hide/Show Android Soft Keyboard

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

install / uninstall APKs programmatically (PackageManager vs Intents)

API level 14 introduced two new actions: ACTION_INSTALL_PACKAGE and ACTION_UNINSTALL_PACKAGE. Those actions allow you to pass EXTRA_RETURN_RESULT boolean extra to get an (un)installation result notification.

Example code for invoking the uninstall dialog:

String app_pkg_name = "com.example.app";
int UNINSTALL_REQUEST_CODE = 1;

Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);  
intent.setData(Uri.parse("package:" + app_pkg_name));  
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, UNINSTALL_REQUEST_CODE);

And receive the notification in your Activity#onActivityResult method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == UNINSTALL_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Log.d("TAG", "onActivityResult: user accepted the (un)install");
        } else if (resultCode == RESULT_CANCELED) {
            Log.d("TAG", "onActivityResult: user canceled the (un)install");
        } else if (resultCode == RESULT_FIRST_USER) {
            Log.d("TAG", "onActivityResult: failed to (un)install");
        }
    }
}

How to format code in Xcode?

Key combination to format all text on open file:

Cmd ? A + Ctrl I

How can I format the output of a bash command in neat columns

Since AIX doesn't have a "column" command, I created the simplistic script below. It would be even shorter without the doc & input edits... :)

#!/usr/bin/perl
#       column.pl: convert STDIN to multiple columns on STDOUT
#       Usage: column.pl column-width number-of-columns  file...
#
$width = shift;
($width ne '') or die "must give column-width and number-of-columns\n";
$columns = shift;
($columns ne '') or die "must give number-of-columns\n";
($x = $width) =~ s/[^0-9]//g;
($x eq $width) or die "invalid column-width: $width\n";
($x = $columns) =~ s/[^0-9]//g;
($x eq $columns) or die "invalid number-of-columns: $columns\n";

$w = $width * -1; $c = $columns;
while (<>) {
        chomp;
        if ( $c-- > 1 ) {
                printf "%${w}s", $_;
                next;
        }
        $c = $columns;
        printf "%${w}s\n", $_;
}
print "\n";

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

use labelpad parameter:

pl.xlabel("...", labelpad=20)

or set it after:

ax.xaxis.labelpad = 20

What is the @Html.DisplayFor syntax for?

I think the main benefit would be when you define your own Display Templates, or use Data annotations.

So for example if your title was a date, you could define

[DisplayFormat(DataFormatString = "{0:d}")]

and then on every page it would display the value in a consistent manner. Otherwise you may have to customise the display on multiple pages. So it does not help much for plain strings, but it does help for currencies, dates, emails, urls, etc.

For example instead of an email address being a plain string it could show up as a link:

<a href="mailto:@ViewData.Model">@ViewData.TemplateInfo.FormattedModelValue</a>

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

In AndroidManifest.xml:

<application
    android:icon="@drawable/launcher"
    android:label="@string/app_name"
    android:name="com..."
    android:theme="@style/Theme">...</Application>

In styles.xml: (See android:icon)

<style name="Theme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/ActionBar</item>
</style>
<style name="ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:icon">@drawable/icon</item>
</style>

How to find all occurrences of an element in a list

If you need to search for all element's positions between certain indices, you can state them:

[i for i,x in enumerate([1,2,3,2]) if x==2 & 2<= i <=3] # -> [3]

Replace console output in Python

An easy solution is just writing "\r" before the string and not adding a newline; if the string never gets shorter this is sufficient...

sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

Slightly more sophisticated is a progress bar... this is something I am using:

def startProgress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
    sys.stdout.flush()
    progress_x = 0

def progress(x):
    global progress_x
    x = int(x * 40 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x

def endProgress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

You call startProgress passing the description of the operation, then progress(x) where x is the percentage and finally endProgress()

How do I get IntelliJ to recognize common Python modules?

This is how i solved my problem (i have imported the project and it was showing there only, newly created files were not showing those errors):

1) Command + alt + R (Control in case of windows

2) Debug window will appear, select your file and press right arrow (->) and choose Edit then press enter (Edit configuration setting window will appear)

3) Under configuration, at the bottom you can see the error (please select a module with a valid python sdk), So in Python Interpreter, check Use Specified Interpreter, then in drop down you select your Python version

(In case python is not there download python plugin for intelliJ using following link https://www.jetbrains.com/help/idea/2016.3/installing-updating-and-uninstalling-repository-plugins.html

4) Click on apply then close it.

Bingo it's done.

How to tell if string starts with a number with Python?

Try this:

if string[0] in range(10):

Tools for making latex tables in R

The stargazer package is another good option. It supports objects from many commonly used functions and packages (lm, glm, svyreg, survival, pscl, AER), as well as from zelig. In addition to regression tables, it can also output summary statistics for data frames, or directly output the content of data frames.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.

@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    string cLayout = "";

    if (controller == "Webmaster")
        cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
    else
        cLayout = "~/Views/Shared/_Layout.cshtml";

    Layout = cLayout;
}

Read Complete Article here "How to Render different Layout in ASP.NET MVC"

Add event handler for body.onload by javascript within <body> part

As we were already using jQuery for a graphical eye-candy feature we ended up using this. A code like

$(document).ready(function() {
    // any code goes here
    init();
});

did everything we wanted and cares about browser incompatibilities at its own.

String to HtmlDocument

Using Html Agility Pack as suggested by SLaks, this becomes very easy:

string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);

HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");

Remove all git files from a directory?

The .git folder is only stored in the root directory of the repo, not all the sub-directories like subversion. You should be able to just delete that one folder, unless you are using Submodules...then they will have one too.

Greater than and less than in one statement

java is not python.

you can't do anything like this

if(0 < i < 5) or if(i in range(0,6))

you mentioned the easiest way :

int i = getFilesSize();
if(0 < i && i < 5){
    //operations

}

of

   if(0 < i){
       if(i < 5){
          //operations
       }
     }

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

Java output formatting for Strings

For decimal values you can use DecimalFormat

import java.text.*;

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + "  " + pattern + "  " + output);
   }

   static public void main(String[] args) {

      customFormat("###,###.###", 123456.789);
      customFormat("###.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$###,###.###", 12345.67);  
   }
}

and output will be:

123456.789  ###,###.###   123,456.789
123456.789  ###.##        123456.79
123.78      000000.000    000123.780
12345.67    $###,###.###  $12,345.67

For more details look here:

http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

Though you certainly can build such a device out of existing sequence operators, I would in this case be inclined to write this one up as a custom sequence operator. Something like:

// Returns "other" if the list is empty.
// Returns "other" if the list is non-empty and there are two different elements.
// Returns the element of the list if it is non-empty and all elements are the same.
public static int Unanimous(this IEnumerable<int> sequence, int other)
{
    int? first = null;
    foreach(var item in sequence)
    {
        if (first == null)
            first = item;
        else if (first.Value != item)
            return other;
    }
    return first ?? other;
}

That's pretty clear, short, covers all the cases, and does not unnecessarily create extra iterations of the sequence.

Making this into a generic method that works on IEnumerable<T> is left as an exercise. :-)

How to scroll to top of long ScrollView layout?

I faced Same Problem When i am using Scrollview inside View Flipper or Dialog that case scrollViewObject.fullScroll(ScrollView.FOCUS_UP) returns false so that case scrollViewObject.smoothScrollTo(0, 0) is Worked for me

Scroll Focus Top

Youtube iframe wmode issue

recently I saw that sometimes the flash player doesn't recognize &wmode=opaque, istead you should pass &WMode=opaque too (notice the uppercase).

Select DISTINCT individual columns in django?

It's quite simple actually if you're using PostgreSQL, just use distinct(columns) (documentation).

Productorder.objects.all().distinct('category')

Note that this feature has been included in Django since 1.4

How do I create a circle or square with just CSS - with a hollow center?

Shortly after finding this questions I found these examples on CSS Tricks: http://css-tricks.com/examples/ShapesOfCSS/

Copied so you don't have to click

_x000D_
_x000D_
.square {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
}_x000D_
.circle {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  -moz-border-radius: 50px;_x000D_
  -webkit-border-radius: 50px;_x000D_
  border-radius: 50px;_x000D_
}_x000D_
/* Cleaner, but slightly less support: use "50%" as value */
_x000D_
<div class="square"></div>_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

There are many other shape examples in the above link, but you will have to test for browser compatibility.

Safe String to BigDecimal conversion

resultString = subjectString.replaceAll("[^.\\d]", "");

will remove all characters except digits and the dot from your string.

To make it locale-aware, you might want to use getDecimalSeparator() from java.text.DecimalFormatSymbols. I don't know Java, but it might look like this:

sep = getDecimalSeparator()
resultString = subjectString.replaceAll("[^"+sep+"\\d]", "");

Click through div to underlying elements

Just wrap a tag around all the HTML extract, for example

<a href="/categories/1">
  <img alt="test1" class="img-responsive" src="/assets/photo.jpg" />
  <div class="caption bg-orange">
    <h2>
      test1
    </h2>
  </div>
</a>

in my example my caption class has hover effects, that with pointer-events:none; you just will lose

wrapping the content will keep your hover effects and you can click in all the picture, div included, regards!

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

How to increase font size in NeatBeans IDE?

At Windows in the file C:\Program Files\NetBeans x.x\etc\netbeans.conf

Add "--fontsize [size]" at the end of line netbeans_default_options:

netbeans_default_options=".... --fontsize 16"

Get loop count inside a Python FOR loop

I know rather old question but....came across looking other thing so I give my shot:

[each*2 for each in [1,2,3,4,5] if each % 10 == 0])

How to convert an Array to a Set in Java

For anyone solving for Android:

Kotlin Collections Solution

The asterisk * is the spread operator. It applies all elements in a collection individually, each passed in order to a vararg method parameter. It is equivalent to:

val myArray = arrayOf("data", "foo")
val mySet = setOf(*myArray)

// Equivalent to
val mySet = setOf("data", "foo")

// Multiple spreads ["data", "foo", "bar", "data", "foo"]
val mySet = setOf(*myArray, "bar", *myArray)

Passing no parameters setOf() results in an empty set.

In addition to setOf, you can also use any of these for a specific hash type:

hashSetOf()
linkedSetOf()
mutableSetOf()
sortableSetOf()

This is how to define the collection item type explicitly.

setOf<String>()
hashSetOf<MyClass>()

Does overflow:hidden applied to <body> work on iPhone Safari?

Why not wrap the content you don't want shown in an element with a class and set that class to display:none in a stylesheet meant only for the iphone and other handheld devices?

<!--[if !IE]>-->
<link media="only screen and (max-device-width: 480px)" href="small-device.css" type= "text/css" rel="stylesheet">
<!--<![endif]-->

LaTeX: Multiple authors in a two-column article

What about using a tabular inside \author{}, just like in IEEE macros:

\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c} 
I. M. Author  & M. Y. Coauthor \\
My Department & Coauthor Department \\ 
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle    
\end{document}

This will produce two columns authors with any documentclass.

Results:

enter image description here

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

your question is basically O/RM's vs hand writing SQL

Using an ORM or plain SQL?

Take a look at some of the other O/RM solutions out there, L2S isn't the only one (NHibernate, ActiveRecord)

http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software

to address the specific questions:

  1. Depends on the quality of the O/RM solution, L2S is pretty good at generating SQL
  2. This is normally much faster using an O/RM once you grok the process
  3. Code is also usually much neater and more maintainable
  4. Straight SQL will of course get you more flexibility, but most O/RM's can do all but the most complicated queries
  5. Overall I would suggest going with an O/RM, the flexibility loss is negligable

How to get Locale from its String representation in Java?

Well, I would store instead a string concatenation of Locale.getISO3Language(), getISO3Country() and getVariant() as key, which would allow me to latter call Locale(String language, String country, String variant) constructor.

indeed, relying of displayLanguage implies using the langage of locale to display it, which make it locale dependant, contrary to iso language code.

As an example, en locale key would be storable as

en_EN
en_US

and so on ...

What is the total amount of public IPv4 addresses?

According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.

And too many addresses in this post.

Auto Increment after delete in MySQL

I came here looking for an answer to the Title question "MySQL - Auto Increment after delete" but I could only find an answer for that in the questions

By using something like:

DELETE FROM table;
ALTER TABLE table AUTO_INCREMENT = 1;

Note that Darin Dimitrov's answer explain really well AUTO_INCREMENT and it's usage. Take a look there before doing something you might regret.

PS: The question itself is more "Why you need to recycle key values?" and Dolph's answer cover that.

Iterate over model instance field names and values in template

Here's another approach using a model method. This version resolves picklist/choice fields, skips empty fields, and lets you exclude specific fields.

def get_all_fields(self):
    """Returns a list of all field names on the instance."""
    fields = []
    for f in self._meta.fields:

        fname = f.name        
        # resolve picklists/choices, with get_xyz_display() function
        get_choice = 'get_'+fname+'_display'
        if hasattr(self, get_choice):
            value = getattr(self, get_choice)()
        else:
            try:
                value = getattr(self, fname)
            except AttributeError:
                value = None

        # only display fields with values and skip some fields entirely
        if f.editable and value and f.name not in ('id', 'status', 'workshop', 'user', 'complete') :

            fields.append(
              {
               'label':f.verbose_name, 
               'name':f.name, 
               'value':value,
              }
            )
    return fields

Then in your template:

{% for f in app.get_all_fields %}
  <dt>{{f.label|capfirst}}</dt>
    <dd>
      {{f.value|escape|urlize|linebreaks}}
    </dd>
{% endfor %}

Is it possible to listen to a "style change" event?

Things have moved on a bit since the question was asked - it is now possible to use a MutationObserver to detect changes in the 'style' attribute of an element, no jQuery required:

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        console.log('style changed!');
    });    
});

var target = document.getElementById('myId');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });

The argument that gets passed to the callback function is a MutationRecord object that lets you get hold of the old and new style values.

Support is good in modern browsers including IE 11+.

form_for with nested resources

Be sure to have both objects created in controller: @post and @comment for the post, eg:

@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)

Then in view:

<%= form_for([@post, @comment]) do |f| %>

Be sure to explicitly define the array in the form_for, not just comma separated like you have above.

form with no action and where enter does not reload page

The first response is the best solution:

Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.

More specific with jquery:

$('#your-form-id').submit(function(){return false;});

Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?

Writing Chrome extensions is an example of where you might have a form for user input, but you don't want it to submit. If you use action="javascript:void(0);", the code will probably work but you will end up with this problem where you get an error about running inline Javascript.

If you leave out the action completely, the form will reload which is also undesired in some cases when writing a Chrome extension. Or if you had a webpage with some sort of an embedded calculator, where the user would provide some input and click "Calculate" or something like that.

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

How to not wrap contents of a div?

If you don't care about a minimum width for the div and really just don't want the div to expand across the whole container, you can float it left -- floated divs by default expand to support their contents, like so:

<form>
    <div style="float: left; background-color: blue">
        <input type="button" name="blah" value="lots and lots of characters"/>
        <input type="button" name="blah2" value="some characters"/>
    </div>
</form>

Displaying the build date

In 2018 some of the above solutions do not work anymore or do not work with .NET Core.

I use the following approach which is simple and works for my .NET Core 2.0 project.

Add the following to your .csproj inside the PropertyGroup :

    <Today>$([System.DateTime]::Now)</Today>

This defines a PropertyFunction which you can access in your pre build command.

Your pre-build looks like this

echo $(today) > $(ProjectDir)BuildTimeStamp.txt

Set the property of the BuildTimeStamp.txt to Embedded resource.

Now you can read the time stamp like this

public static class BuildTimeStamp
    {
        public static string GetTimestamp()
        {
            var assembly = Assembly.GetEntryAssembly(); 

            var stream = assembly.GetManifestResourceStream("NamespaceGoesHere.BuildTimeStamp.txt");

            using (var reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }
    }

How to read data when some numbers contain commas as thousand separator?

Using read_delim function, which is part of readr library, you can specify additional parameter:

locale = locale(decimal_mark = ",")

read_delim("filetoread.csv", ';", locale = locale(decimal_mark = ","))

*Semicolon in second line means that read_delim will read csv semicolon separated values.

This will help to read all numbers with a comma as proper numbers.

Regards

Mateusz Kania

Pythonic way to return list of every nth item in a larger list

From manual: s[i:j:k] slice of s from i to j with step k

li = range(100)
sub = li[0::10]

>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Way to get number of digits in an int?

One wants to do this mostly because he/she wants to "present" it, which mostly mean it finally needs to be "toString-ed" (or transformed in another way) explicitly or implicitly anyway; before it can be presented (printed for example).

If that is the case then just try to make the necessary "toString" explicit and count the bits.

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Ajax.BeginForm looks to be a fail.

Using a regular Html.Begin for, this does the trick just nicely:

$('#detailsform').submit(function(e) {
    e.preventDefault();
    $.post($(this).attr("action"), $(this).serialize(), function(r) {
        $("#edit").html(r);
    });
}); 

How can I align text directly beneath an image?

In order to be able to justify the text, you need to know the width of the image. You can just use the normal width of the image, or use a different width, but IE 6 might get cranky at you and not scale.

Here's what you need:

<style type="text/css">
#container { width: 100px; //whatever width you want }

#image {width: 100%; //fill up whole div }

#text { text-align: justify; }    
</style>

 <div id="container"> 
     <img src="" id="image" /> 
     <p id="text">oooh look! text!</p> 
 </div>

How can I make a div stick to the top of the screen once it's been scrolled to?

Here's one more version to try for those having issues with the others. It pulls together the techniques discussed in this duplicate question, and generates the required helper DIVs dynamically so no extra HTML is required.

CSS:

.sticky { position:fixed; top:0; }

JQuery:

function make_sticky(id) {
    var e = $(id);
    var w = $(window);
    $('<div/>').insertBefore(id);
    $('<div/>').hide().css('height',e.outerHeight()).insertAfter(id);
    var n = e.next();
    var p = e.prev();
    function sticky_relocate() {
      var window_top = w.scrollTop();
      var div_top = p.offset().top;
      if (window_top > div_top) {
        e.addClass('sticky');
        n.show();
      } else {
        e.removeClass('sticky');
        n.hide();
      }
    }
    w.scroll(sticky_relocate);
    sticky_relocate();
}

To make an element sticky, do:

make_sticky('#sticky-elem-id');

When the element becomes sticky, the code manages the position of the remaining content to keep it from jumping into the gap left by the sticky element. It also returns the sticky element to its original non-sticky position when scrolling back above it.

Find size of object instance in bytes in c#

safe solution with some optimizations CyberSaving/MemoryUsage code. some case:

/* test nullable type */      
TestSize<int?>.SizeOf(null) //-> 4 B

/* test StringBuilder */    
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) sb.Append("??????????");
TestSize<StringBuilder>.SizeOf(sb ) //-> 3132 B

/* test Simple array */    
TestSize<int[]>.SizeOf(new int[100]); //-> 400 B

/* test Empty List<int>*/    
var list = new List<int>();  
TestSize<List<int>>.SizeOf(list); //-> 205 B

/* test List<int> with 100 items*/
for (int i = 0; i < 100; i++) list.Add(i);
TestSize<List<int>>.SizeOf(list); //-> 717 B

It works also with classes:

class twostring
{
    public string a { get; set; }
    public string b { get; set; }
}
TestSize<twostring>.SizeOf(new twostring() { a="0123456789", b="0123456789" } //-> 28 B

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

I had to do this in VB and prefer to split it out to a method that I placed in a Module. You can add the Fill column as another ByRef parameter if desired.

''' <summary>
''' Makes all columns in a DataGridView autosize based on displayed cells,
''' while leaving the column widths user-adjustable.
''' </summary>
''' <param name="dgv">A DataGridView to adjust</param>
Friend Sub MakeAdjustableAutoSizedGridCols(ByRef dgv As DataGridView)
    Dim width As Integer

    For Each col As DataGridViewColumn In dgv.Columns
        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
        width = col.Width
        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None
        col.Width = width
    Next
    dgv.AllowUserToResizeColumns = True
End Sub

Efficiency of Java "Double Brace Initialization"?

Taking the following test class:

public class Test {
  public void test() {
    Set<String> flavors = new HashSet<String>() {{
        add("vanilla");
        add("strawberry");
        add("chocolate");
        add("butter pecan");
    }};
  }
}

and then decompiling the class file, I see:

public class Test {
  public void test() {
    java.util.Set flavors = new HashSet() {

      final Test this$0;

      {
        this$0 = Test.this;
        super();
        add("vanilla");
        add("strawberry");
        add("chocolate");
        add("butter pecan");
      }
    };
  }
}

This doesn't look terribly inefficient to me. If I were worried about performance for something like this, I'd profile it. And your question #2 is answered by the above code: You're inside an implicit constructor (and instance initializer) for your inner class, so "this" refers to this inner class.

Yes, this syntax is obscure, but a comment can clarify obscure syntax usage. To clarify the syntax, most people are familiar with a static initializer block (JLS 8.7 Static Initializers):

public class Sample1 {
    private static final String someVar;
    static {
        String temp = null;
        ..... // block of code setting temp
        someVar = temp;
    }
}

You can also use a similar syntax (without the word "static") for constructor usage (JLS 8.6 Instance Initializers), although I have never seen this used in production code. This is much less commonly known.

public class Sample2 {
    private final String someVar;

    // This is an instance initializer
    {
        String temp = null;
        ..... // block of code setting temp
        someVar = temp;
    }
}

If you don't have a default constructor, then the block of code between { and } is turned into a constructor by the compiler. With this in mind, unravel the double brace code:

public void test() {
  Set<String> flavors = new HashSet<String>() {
      {
        add("vanilla");
        add("strawberry");
        add("chocolate");
        add("butter pecan");
      }
  };
}

The block of code between the inner-most braces is turned into a constructor by the compiler. The outer-most braces delimit the anonymous inner class. To take this the final step of making everything non-anonymous:

public void test() {
  Set<String> flavors = new MyHashSet();
}

class MyHashSet extends HashSet<String>() {
    public MyHashSet() {
        add("vanilla");
        add("strawberry");
        add("chocolate");
        add("butter pecan");
    }
}

For initialization purposes, I'd say there is no overhead whatsoever (or so small that it can be neglected). However, every use of flavors will go not against HashSet but instead against MyHashSet. There is probably a small (and quite possibly negligible) overhead to this. But again, before I worried about it, I would profile it.

Again, to your question #2, the above code is the logical and explicit equivalent of double brace initialization, and it makes it obvious where "this" refers: To the inner class that extends HashSet.

If you have questions about the details of instance initializers, check out the details in the JLS documentation.

Quickest way to convert a base 10 number to any base in .NET?

I had a similar need, except I needed to do math on the "numbers" as well. I took some of the suggestions here and created a class that will do all this fun stuff. It allows for any unicode character to be used to represent a number and it works with decimals too.

This class is pretty easy to use. Just create a number as a type of New BaseNumber, set a few properties, and your off. The routines take care of switching between base 10 and base x automatically and the value you set is preserved in the base you set it in, so no accuracy is lost (until conversion that is, but even then precision loss should be very minimal since this routine uses Double and Long where ever possible).

I can't command on the speed of this routine. It is probably quite slow, so I'm not sure if it will suit the needs of the one who asked the question, but it certain is flexible, so hopefully someone else can use this.

For anyone else that may need this code for calculating the next column in Excel, I will include the looping code I used that leverages this class.

Public Class BaseNumber

    Private _CharacterArray As List(Of Char)

    Private _BaseXNumber As String
    Private _Base10Number As Double?

    Private NumberBaseLow As Integer
    Private NumberBaseHigh As Integer

    Private DecimalSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
    Private GroupSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator

    Public Sub UseCapsLetters()
        'http://unicodelookup.com
        TrySetBaseSet(65, 90)
    End Sub

    Public Function GetCharacterArray() As List(Of Char)
        Return _CharacterArray
    End Function

    Public Sub SetCharacterArray(CharacterArray As String)
        _CharacterArray = New List(Of Char)
        _CharacterArray.AddRange(CharacterArray.ToList)

        TrySetBaseSet(_CharacterArray)
    End Sub

    Public Sub SetCharacterArray(CharacterArray As List(Of Char))
        _CharacterArray = CharacterArray
        TrySetBaseSet(_CharacterArray)
    End Sub

    Public Sub SetNumber(Value As String)
        _BaseXNumber = Value
        _Base10Number = Nothing
    End Sub

    Public Sub SetNumber(Value As Double)
        _Base10Number = Value
        _BaseXNumber = Nothing
    End Sub

    Public Function GetBaseXNumber() As String
        If _BaseXNumber IsNot Nothing Then
            Return _BaseXNumber
        Else
            Return ToBaseString()
        End If
    End Function

    Public Function GetBase10Number() As Double
        If _Base10Number IsNot Nothing Then
            Return _Base10Number
        Else
            Return ToBase10()
        End If
    End Function

    Private Sub TrySetBaseSet(Values As List(Of Char))
        For Each value As Char In _BaseXNumber
            If Not Values.Contains(value) Then
                Throw New ArgumentOutOfRangeException("The string has a value, " & value & ", not contained in the selected 'base' set.")
                _CharacterArray.Clear()
                DetermineNumberBase()
            End If
        Next

        _CharacterArray = Values

    End Sub

    Private Sub TrySetBaseSet(LowValue As Integer, HighValue As Integer)

        Dim HighLow As KeyValuePair(Of Integer, Integer) = GetHighLow()

        If HighLow.Key < LowValue OrElse HighLow.Value > HighValue Then
            Throw New ArgumentOutOfRangeException("The string has a value not contained in the selected 'base' set.")
            _CharacterArray.Clear()
            DetermineNumberBase()
        End If

        NumberBaseLow = LowValue
        NumberBaseHigh = HighValue

    End Sub

    Private Function GetHighLow(Optional Values As List(Of Char) = Nothing) As KeyValuePair(Of Integer, Integer)
        If Values Is Nothing Then
            Values = _BaseXNumber.ToList
        End If

        Dim lowestValue As Integer = Convert.ToInt32(Values(0))
        Dim highestValue As Integer = Convert.ToInt32(Values(0))

        Dim currentValue As Integer

        For Each value As Char In Values

            If value <> DecimalSeparator AndAlso value <> GroupSeparator Then
                currentValue = Convert.ToInt32(value)
                If currentValue > highestValue Then
                    highestValue = currentValue
                End If
                If currentValue < lowestValue Then
                    currentValue = lowestValue
                End If
            End If
        Next

        Return New KeyValuePair(Of Integer, Integer)(lowestValue, highestValue)

    End Function

    Public Sub New(BaseXNumber As String)
        _BaseXNumber = BaseXNumber
        DetermineNumberBase()
    End Sub

    Public Sub New(BaseXNumber As String, NumberBase As Integer)
        Me.New(BaseXNumber, Convert.ToInt32("0"c), NumberBase)
    End Sub

    Public Sub New(BaseXNumber As String, NumberBaseLow As Integer, NumberBaseHigh As Integer)
        _BaseXNumber = BaseXNumber
        Me.NumberBaseLow = NumberBaseLow
        Me.NumberBaseHigh = NumberBaseHigh
    End Sub

    Public Sub New(Base10Number As Double)
        _Base10Number = Base10Number
    End Sub

    Private Sub DetermineNumberBase()
        Dim highestValue As Integer

        Dim currentValue As Integer

        For Each value As Char In _BaseXNumber

            currentValue = Convert.ToInt32(value)
            If currentValue > highestValue Then
                highestValue = currentValue
            End If
        Next

        NumberBaseHigh = highestValue
        NumberBaseLow = Convert.ToInt32("0"c) 'assume 0 is the lowest

    End Sub

    Private Function ToBaseString() As String
        Dim Base10Number As Double = _Base10Number

        Dim intPart As Long = Math.Truncate(Base10Number)
        Dim fracPart As Long = (Base10Number - intPart).ToString.Replace(DecimalSeparator, "")

        Dim intPartString As String = ConvertIntToString(intPart)
        Dim fracPartString As String = If(fracPart <> 0, DecimalSeparator & ConvertIntToString(fracPart), "")

        Return intPartString & fracPartString

    End Function

    Private Function ToBase10() As Double
        Dim intPartString As String = _BaseXNumber.Split(DecimalSeparator)(0).Replace(GroupSeparator, "")
        Dim fracPartString As String = If(_BaseXNumber.Contains(DecimalSeparator), _BaseXNumber.Split(DecimalSeparator)(1), "")

        Dim intPart As Long = ConvertStringToInt(intPartString)
        Dim fracPartNumerator As Long = ConvertStringToInt(fracPartString)
        Dim fracPartDenominator As Long = ConvertStringToInt(GetEncodedChar(1) & String.Join("", Enumerable.Repeat(GetEncodedChar(0), fracPartString.ToString.Length)))

        Return Convert.ToDouble(intPart + fracPartNumerator / fracPartDenominator)

    End Function

    Private Function ConvertIntToString(ValueToConvert As Long) As String
        Dim result As String = String.Empty
        Dim targetBase As Long = GetEncodingCharsLength()

        Do
            result = GetEncodedChar(ValueToConvert Mod targetBase) & result
            ValueToConvert = ValueToConvert \ targetBase
        Loop While ValueToConvert > 0

        Return result
    End Function

    Private Function ConvertStringToInt(ValueToConvert As String) As Long
        Dim result As Long
        Dim targetBase As Integer = GetEncodingCharsLength()
        Dim startBase As Integer = GetEncodingCharsStartBase()

        Dim value As Char
        For x As Integer = 0 To ValueToConvert.Length - 1
            value = ValueToConvert(x)
            result += GetDecodedChar(value) * Convert.ToInt32(Math.Pow(GetEncodingCharsLength, ValueToConvert.Length - (x + 1)))
        Next

        Return result

    End Function

    Private Function GetEncodedChar(index As Integer) As Char
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray(index)
        Else
            Return Convert.ToChar(index + NumberBaseLow)
        End If
    End Function

    Private Function GetDecodedChar(character As Char) As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.IndexOf(character)
        Else
            Return Convert.ToInt32(character) - NumberBaseLow
        End If
    End Function

    Private Function GetEncodingCharsLength() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.Count
        Else
            Return NumberBaseHigh - NumberBaseLow + 1
        End If
    End Function

    Private Function GetEncodingCharsStartBase() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return GetHighLow.Key
        Else
            Return NumberBaseLow
        End If
    End Function
End Class

And now for the code to loop through Excel columns:

    Public Function GetColumnList(DataSheetID As String) As List(Of String)
        Dim workingColumn As New BaseNumber("A")
        workingColumn.SetCharacterArray("@ABCDEFGHIJKLMNOPQRSTUVWXYZ")

        Dim listOfPopulatedColumns As New List(Of String)
        Dim countOfEmptyColumns As Integer

        Dim colHasData As Boolean
        Dim cellHasData As Boolean

        Do
            colHasData = True
            cellHasData = False
            For r As Integer = 1 To GetMaxRow(DataSheetID)
                cellHasData = cellHasData Or XLGetCellValue(DataSheetID, workingColumn.GetBaseXNumber & r) <> ""
            Next
            colHasData = colHasData And cellHasData

            'keep trying until we get 4 empty columns in a row
            If colHasData Then
                listOfPopulatedColumns.Add(workingColumn.GetBaseXNumber)
                countOfEmptyColumns = 0
            Else
                countOfEmptyColumns += 1
            End If

            'we are already starting with column A, so increment after we check column A
            Do
                workingColumn.SetNumber(workingColumn.GetBase10Number + 1)
            Loop Until Not workingColumn.GetBaseXNumber.Contains("@")

        Loop Until countOfEmptyColumns > 3

        Return listOfPopulatedColumns

    End Function

You'll note the important part of the Excel part is that 0 is identified by a @ in the re-based number. So I just filter out all the numbers that have an @ in them and I get the proper sequence (A, B, C, ..., Z, AA, AB, AC, ...).

Neatest way to remove linebreaks in Perl

To extend Ted Cambron's answer above and something that hasn't been addressed here: If you remove all line breaks indiscriminately from a chunk of entered text, you will end up with paragraphs running into each other without spaces when you output that text later. This is what I use:

sub cleanLines{

    my $text = shift;

    $text =~ s/\r/ /; #replace \r with space
    $text =~ s/\n/ /; #replace \n with space
    $text =~ s/  / /g; #replace double-spaces with single space

    return $text;
}

The last substitution uses the g 'greedy' modifier so it continues to find double-spaces until it replaces them all. (Effectively substituting anything more that single space)

Drop shadow on a div container?

This works for me on all my browsers:

.shadow {
-moz-box-shadow: 0 0 30px 5px #999;
-webkit-box-shadow: 0 0 30px 5px #999;
}

then just give any div the shadow class, no jQuery required.

How do I check if an element is really visible with JavaScript?

Try element.getBoundingClientRect(). It will return an object with properties

  • bottom
  • top
  • right
  • left
  • width -- browser dependent
  • height -- browser dependent

Check that the width and height of the element's BoundingClientRect are not zero which is the value of hidden or non-visible elements. If the values are greater than zero the element should be visible in the body. Then check if the bottom property is less than screen.height which would imply that the element is withing the viewport. (Technically you would also have to account for the top of the browser window including the searchbar, buttons, etc.)

What's a standard way to do a no-op in python?

Use pass for no-op:

if x == 0:
  pass
else:
  print "x not equal 0"

And here's another example:

def f():
  pass

Or:

class c:
  pass

How do I concatenate multiple C++ strings on one line?

Your code can be written as1,

s = "Hello world," "nice to see you," "or not."

...but I doubt that's what you're looking for. In your case, you are probably looking for streams:

std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();

1 "can be written as" : This only works for string literals. The concatenation is done by the compiler.

using OR and NOT in solr query

I don't know why that doesn't work, but this one is logically equivalent and it does work:

-(myField:superneat AND -myOtherField:somethingElse)

Maybe it has something to do with defining the same field twice in the query...

Try asking in the solr-user group, then post back here the final answer!

Best way to concatenate List of String objects?

Use one of the the StringUtils.join methods in Apache Commons Lang.

import org.apache.commons.lang3.StringUtils;

String result = StringUtils.join(list, ", ");

If you are fortunate enough to be using Java 8, then it's even easier...just use String.join

String result = String.join(", ", list);

Can I add and remove elements of enumeration at runtime in Java

You can load a Java class from source at runtime. (Using JCI, BeanShell or JavaCompiler)

This would allow you to change the Enum values as you wish.

Note: this wouldn't change any classes which referred to these enums so this might not be very useful in reality.

How do you create a daemon in Python?

Probably not a direct answer to the question, but systemd can be used to run your application as a daemon. Here is an example:

[Unit]
Description=Python daemon
After=syslog.target
After=network.target

[Service]
Type=simple
User=<run as user>
Group=<run as group group>
ExecStart=/usr/bin/python <python script home>/script.py

# Give the script some time to startup
TimeoutSec=300

[Install]
WantedBy=multi-user.target

I prefer this method because a lot of the work is done for you, and then your daemon script behaves similarly to the rest of your system.

-Orby

How would you make two <div>s overlap?

Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.

#logo
{
    position: absolute:
    z-index: 2000;
    left: 100px;
    width: 100px;
    height: 50px;
}

Detecting when a div's height changes using jQuery

You can use the DOMSubtreeModified event

$(something).bind('DOMSubtreeModified' ...

But this will fire even if the dimensions don't change, and reassigning the position whenever it fires can take a performance hit. In my experience using this method, checking whether the dimensions have changed is less expensive and so you might consider combining the two.

Or if you are directly altering the div (rather than the div being altered by user input in unpredictable ways, like if it is contentEditable), you can simply fire a custom event whenever you do so.

Downside: IE and Opera don't implement this event.

How can I find the method that called the current method?

A quick recap of the 2 approaches with speed comparison being the important part.

http://geekswithblogs.net/BlackRabbitCoder/archive/2013/07/25/c.net-little-wonders-getting-caller-information.aspx

Determining the caller at compile-time

static void Log(object message, 
[CallerMemberName] string memberName = "",
[CallerFilePath] string fileName = "",
[CallerLineNumber] int lineNumber = 0)
{
    // we'll just use a simple Console write for now    
    Console.WriteLine("{0}({1}):{2} - {3}", fileName, lineNumber, memberName, message);
}

Determining the caller using the stack

static void Log(object message)
{
    // frame 1, true for source info
    StackFrame frame = new StackFrame(1, true);
    var method = frame.GetMethod();
    var fileName = frame.GetFileName();
    var lineNumber = frame.GetFileLineNumber();

    // we'll just use a simple Console write for now    
    Console.WriteLine("{0}({1}):{2} - {3}", fileName, lineNumber, method.Name, message);
}

Comparison of the 2 approaches

Time for 1,000,000 iterations with Attributes: 196 ms
Time for 1,000,000 iterations with StackTrace: 5096 ms

So you see, using the attributes is much, much faster! Nearly 25x faster in fact.

Make a div fill the height of the remaining screen space

CSS Grid Solution

Just defining the body with display:grid and the grid-template-rows using auto and the fr value property.

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
body {_x000D_
  min-height: 100%;_x000D_
  display: grid;_x000D_
  grid-template-rows: auto 1fr auto;_x000D_
}_x000D_
_x000D_
header {_x000D_
  padding: 1em;_x000D_
  background: pink;_x000D_
}_x000D_
_x000D_
main {_x000D_
  padding: 1em;_x000D_
  background: lightblue;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  padding: 2em;_x000D_
  background: lightgreen;_x000D_
}_x000D_
_x000D_
main:hover {_x000D_
  height: 2000px;_x000D_
  /* demos expansion of center element */_x000D_
}
_x000D_
<header>HEADER</header>_x000D_
<main>MAIN</main>_x000D_
<footer>FOOTER</footer>
_x000D_
_x000D_
_x000D_

A Complete Guide to Grids @ CSS-Tricks.com

How to find the mime type of a file in python?

in python 2.6:

import shlex
import subprocess
mime = subprocess.Popen("/usr/bin/file --mime " + shlex.quote(PATH), shell=True, \
    stdout=subprocess.PIPE).communicate()[0]

Java and SQLite

Typo: java -cp .:sqlitejdbc-v056.jar Test

should be: java -cp .:sqlitejdbc-v056.jar; Test

notice the semicolon after ".jar" i hope that helps people, could cause a lot of hassle

How to check if image exists with given url?

To handle the lazy loading with image existence check I followed this in jQuery-

$('[data-src]').each(function() {
  var $image_place_holder_element = $(this);
  var image_url = $(this).data('src');
  $("<div class='hidden-classe' />").load(image_url, function(response, status, xhr) {
    if (!(status == "error")) {
      $image_place_holder_element.removeClass('image-placeholder');
      $image_place_holder_element.attr('src', image_url);
    }
  }).remove();
});

Reason: if I am using $image_place_holder_element.load() method it will be adding the response to the element, so random div and removing it appeared me a good solution. Hope it works for someone trying to implement lazy loading along with url check.

Push local Git repo to new remote including all branches and tags

The manpage for git-push is worth a read. Combined with this website I wrote the following in my .git/config:

[remote "origin"]
    url = …
    fetch = …
    push = :
    push = refs/tags/*

The push = : means "push any 'matching' branches (i.e. branches that already exist in the remote repository and have a local counterpart)", while push = refs/tags/* means "push all tags".

So now I only have to run git push to push all matching branches and all tags.

Yes, this is not quite what the OP wanted (all of the branches to push must already exist on the remote side), but might be helpful for those who find this question while googling for "how do I push branches and tags at the same time".

Java substring: 'string index out of range'

When this is appropriate, I use matches instead of substring.

With substring:

if( myString.substring(1,17).equals("Someting I expect") ) {
    // Do stuff
}
// Does NOT work if myString is too short

With matches (must use Regex notation):

if( myString.matches("Someting I expect.*") ) {
    // Do stuff
}
// This works with all strings

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

$("#form1").validate is not a function

I had this same issue. It turned out that I was loading the jQuery JavaScript file more than once on the page. This was due to included pages (or JSPs, in my case). Once I removed the duplicate reference to the jQuery js file, this error went away.

How to condense if/else into one line in Python?

Python's if can be used as a ternary operator:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

How do I center a window onscreen in C#?

A single line:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);

ORA-01652 Unable to extend temp segment by in tablespace

I encountered the same error message but don't have any access to the table like "dba_free_space" because I am not a dba. I use some previous answers to check available space and I still have a lot of space. However, after reducing the full table scan as many as possible. The problem is solved. My guess is that Oracle uses temp table to store the full table scan data. It the data size exceeds the limit, it will show the error. Hope this helps someone with the same issue

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

Showing empty view when ListView is empty

I tried all the above solutions.I came up solving the issue.Here I am posting the full solution.

The xml file:

<RelativeLayout
    android:id="@+id/header_main_page_clist1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:paddingBottom="10dp"
    android:background="#ffffff" >

    <ListView
        android:id="@+id/lv_msglist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@color/divider_color"
        android:dividerHeight="1dp" />

    <TextView
        android:id="@+id/emptyElement"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="NO MESSAGES AVAILABLE!"
        android:textColor="#525252"
        android:textSize="19.0sp"
        android:visibility="gone" />
</RelativeLayout>

The textView ("@+id/emptyElement") is the placeholder for the empty listview.

Here is the code for java page:

lvmessage=(ListView)findViewById(R.id.lv_msglist);
lvmessage.setAdapter(adapter);
lvmessage.setEmptyView(findViewById(R.id.emptyElement));

Remember to place the emptyView after binding the adapter to listview.Mine was not working for first time and after I moved the setEmptyView after the setAdapter it is now working.

Output:

enter image description here

Convert 4 bytes to int

for (int i = 0; i < buffer.length; i++)
{
   a = (a << 8) | buffer[i];
   if (i % 3 == 0)
   {
      //a is ready
      a = 0;
   }       
}

How to activate "Share" button in android app?

Create a button with an id share and add the following code snippet.

share.setOnClickListener(new View.OnClickListener() {             
    @Override
    public void onClick(View v) {

        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = "Your body here";
        String shareSub = "Your subject here";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share using"));
    }
});

The above code snippet will open the share chooser on share button click action. However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.

Check if object is a jQuery object

You can use the instanceof operator:

if (obj instanceof jQuery){
    console.log('object is jQuery');
}

Explanation: the jQuery function (aka $) is implemented as a constructor function. Constructor functions are to be called with the new prefix.

When you call $(foo), internally jQuery translates this to new jQuery(foo)1. JavaScript proceeds to initialize this inside the constructor function to point to a new instance of jQuery, setting it's properties to those found on jQuery.prototype (aka jQuery.fn). Thus, you get a new object where instanceof jQuery is true.


1It's actually new jQuery.prototype.init(foo): the constructor logic has been offloaded to another constructor function called init, but the concept is the same.

How do I get which JRadioButton is selected from a ButtonGroup

I would just loop through your JRadioButtons and call isSelected(). If you really want to go from the ButtonGroup you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?

Difference between parameter and argument

Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).

double sqrt(double x)
{
    ...
    return x;
}

void other(void)
{
     double two = sqrt(2.0);
}

Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.

The terms are often used at least somewhat interchangeably.

Show/hide forms using buttons and JavaScript

There's something I bet you already heard about this! It's called jQuery.

$("#button1").click(function() {
    $("#form1").show();
};

It's really easy and you can use CSS-like selectors and you can add animations. It's really easy to learn.

Server.Mappath in C# classlibrary

You can get the base path by using the following code and append your needed path with that.

string  path = System.AppDomain.CurrentDomain.BaseDirectory;

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

After placing the jar file in desired location, you need to add the jar file by right click on

Project --> properties --> Java Build Path --> Libraries --> Add Jar.

Mockito verify order / sequence of method calls

Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.

Suppose I have two classes Foo and Bar:

public class Foo {
  public void first() {}
  public void second() {}
}

public class Bar {
  public void firstThenSecond(Foo foo) {
    foo.first();
    foo.second();
  }
}

I can then add a test class to test that Bar's firstThenSecond() method actually calls first(), then second(), and not second(), then first(). See the following test code:

public class BarTest {
  @Test
  public void testFirstThenSecond() {
    Bar bar = new Bar();
    Foo mockFoo = Mockito.mock(Foo.class);
    bar.firstThenSecond(mockFoo);

    InOrder orderVerifier = Mockito.inOrder(mockFoo);
    // These lines will PASS
    orderVerifier.verify(mockFoo).first();
    orderVerifier.verify(mockFoo).second();

    // These lines will FAIL
    // orderVerifier.verify(mockFoo).second();
    // orderVerifier.verify(mockFoo).first();
  }
}

How to request Location Permission at runtime

Google has created a library for easy Permissions management. Its called EasyPermissions

Here is a simple example on requesting Location permission using this library.

public class MainActivity extends AppCompatActivity {

    private final int REQUEST_LOCATION_PERMISSION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestLocationPermission();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
    public void requestLocationPermission() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
        if(EasyPermissions.hasPermissions(this, perms)) {
            Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
        }
        else {
            EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
        }
    }
}

@AfterPermissionsGranted(REQUEST_CODE) is used to indicate the method that needs to be executed after a permission request with the request code REQUEST_CODE has been granted.

This above case, the method requestLocationPermission() method is called if the user grants the permission to access location services. So, that method acts as both a callback and a method to request the permissions.

You can implement separate callbacks for permission granted and permission denied as well. It is explained in the github page.

What is the difference between __init__ and __call__?

Defining a custom __call__() method in the meta-class allows the class's instance to be called as a function, not always modifying the instance itself.

In [1]: class A:
   ...:     def __init__(self):
   ...:         print "init"
   ...:         
   ...:     def __call__(self):
   ...:         print "call"
   ...:         
   ...:         

In [2]: a = A()
init

In [3]: a()
call

Checking if a variable is defined?

defined?(your_var) will work. Depending on what you're doing you can also do something like your_var.nil?

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I suspect that you have two tables with the same name. One is owned by the schema 'dbo' (dbo.PerfDiag), and the other is owned by the default schema of the account used to connect to SQL Server (something like userid.PerfDiag).

When you have an unqualified reference to a schema object (such as a table) — one not qualified by schema name — the object reference must be resolved. Name resolution occurs by searching in the following sequence for an object of the appropriate type (table) with the specified name. The name resolves to the first match:

  • Under the default schema of the user.
  • Under the schema 'dbo'.

The unqualified reference is bound to the first match in the above sequence.

As a general recommended practice, one should always qualify references to schema objects, for performance reasons:

  • An unqualified reference may invalidate a cached execution plan for the stored procedure or query, since the schema to which the reference was bound may change depending on the credentials executing the stored procedure or query. This results in recompilation of the query/stored procedure, a performance hit. Recompilations cause compile locks to be taken out, blocking others from accessing the needed resource(s).

  • Name resolution slows down query execution as two probes must be made to resolve to the likely version of the object (that owned by 'dbo'). This is the usual case. The only time a single probe will resolve the name is if the current user owns an object of the specified name and type.

[Edited to further note]

The other possibilities are (in no particular order):

  • You aren't connected to the database you think you are.
  • You aren't connected to the SQL Server instance you think you are.

Double check your connect strings and ensure that they explicitly specify the SQL Server instance name and the database name.

trim left characters in sql server?

You can use LEN in combination with SUBSTRING:

SELECT SUBSTRING(myColumn, 7, LEN(myColumn)) from myTable

Elegant solution for line-breaks (PHP)

I ended up writing a function that has worked for me well so far:

// pretty print data
function out($data, $label = NULL) {

  $CLI = (php_sapi_name() === 'cli') ? 'cli' : '';

  $gettype = gettype($data);

  if (isset($label)) {
    if ($CLI) { $label = $label . ': '; }
    else { $label = '<b>'.$label.'</b>: '; }
  }

  if ($gettype == 'string' || $gettype == 'integer' || $gettype == 'double' || $gettype == 'boolean') {
    if ($CLI) { echo $label . $data . "\n"; }
    else { echo $label . $data . "<br/>"; }
  }
  else {
    if ($CLI) { echo $label . print_r($data,1) . "\n"; } 
    else { echo $label . "<pre>".print_r($data,1)."</pre>"; }
  }
}


// Usage

out('Hello world!');

$var = 'Hello Stackoverflow!';
out($var, 'Label');

Check OS version in Swift?

I made this Singleton for simple use, created an IOSVersion.swift file and added this code :

import UIKit

public class IOSVersion {
    class func SYSTEM_VERSION_EQUAL_TO(version: NSString) -> Bool {
        return UIDevice.currentDevice().systemVersion.compare(version,
            options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedSame
    }

    class func SYSTEM_VERSION_GREATER_THAN(version: NSString) -> Bool {
        return UIDevice.currentDevice().systemVersion.compare(version as String,
            options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending
    }

    class func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: NSString) -> Bool {
        return UIDevice.currentDevice().systemVersion.compare(version as String,
            options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedAscending
    }

    class func SYSTEM_VERSION_LESS_THAN(version: NSString) -> Bool {
        return UIDevice.currentDevice().systemVersion.compare(version as String,
            options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending
    }

    class func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(version: NSString) -> Bool {
        return UIDevice.currentDevice().systemVersion.compare(version as String,
            options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedDescending
    }
}

USE :

IOSVersion.SYSTEM_VERSION_EQUAL_TO("8.0")
IOSVersion.SYSTEM_VERSION_LESS_THAN("8.0")

Thanks @KVISH

Edit Swift 2 :

if #available(iOS 9.0, *) {
    //  
} else {
    // 
}

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

You are using prettyfaces too? Then set dispatcher to FORWARD:

<filter-mapping>
   <filter-name>PrimeFaces FileUpload Filter</filter-name>
   <servlet-name>Faces Servlet</servlet-name>
   <dispatcher>FORWARD</dispatcher>
</filter-mapping>

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

When I have come across this problem it is to do with the Fact that the project I am trying to build is set as the Startup project in the solution making the .exe in the obj folder locked ( it also appears in your task manager,) right click another project in your solution and choose set startup project. This will release the lock, remove it from task manager and should let you build.

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

MessageBox.Show(
  "your message",
  "window title", 
  MessageBoxButtons.OK, 
  MessageBoxIcon.Asterisk //For Info Asterisk
  MessageBoxIcon.Exclamation //For triangle Warning 
)

Programmatically select a row in JTable

You can do it calling setRowSelectionInterval :

table.setRowSelectionInterval(0, 0);

to select the first row.

There is no argument given that corresponds to the required formal parameter - .NET Error

In the constructor of

 public class ErrorEventArg : EventArgs

You have to add "base" as follows:

    public ErrorEventArg(string errorMsg, string lastQuery) : base (string errorMsg, string lastQuery)
    {
        ErrorMsg = errorMsg;
        LastQuery = lastQuery;
    }

That solved it for me

How to trace the path in a Breadth-First Search?

I thought I'd try code this up for fun:

graph = {
        '1': ['2', '3', '4'],
        '2': ['5', '6'],
        '5': ['9', '10'],
        '4': ['7', '8'],
        '7': ['11', '12']
        }

def bfs(graph, forefront, end):
    # assumes no cycles

    next_forefront = [(node, path + ',' + node) for i, path in forefront if i in graph for node in graph[i]]

    for node,path in next_forefront:
        if node==end:
            return path
    else:
        return bfs(graph,next_forefront,end)

print bfs(graph,[('1','1')],'11')

# >>>
# 1, 4, 7, 11

If you want cycles you could add this:

for i, j in for_front: # allow cycles, add this code
    if i in graph:
        del graph[i]

How do I truncate a .NET string?

You can create a Truncate extension method that compares the max length relative to the string length and calls Substring if needed.

If you want null handling behavior that parallels that of Substring, don't include a null check. That way, just as str.Substring(0, 10) throws a NullReferenceException if str is null, so will str.Truncate(10).

public static class StringExtensions
{
    public static string Truncate(this string value, int maxLength) =>
        value.Length <= maxLength ? value : value.Substring(0, maxLength); 
}

jQuery and TinyMCE: textarea value doesn't submit

I had this problem for a while and triggerSave() didn't work, nor did any of the other methods.

So I found a way that worked for me ( I'm adding this here because other people may have already tried triggerSave and etc... ):

tinyMCE.init({
   selector: '.tinymce', // This is my <textarea> class
   setup : function(ed) {
                  ed.on('change', function(e) {
                     // This will print out all your content in the tinyMce box
                     console.log('the content '+ed.getContent());
                     // Your text from the tinyMce box will now be passed to your  text area ... 
                     $(".tinymce").text(ed.getContent()); 
                  });
            }
   ... Your other tinyMce settings ...
});

When you're submitting your form or whatever all you have to do is grab the data from your selector ( In my case: .tinymce ) using $('.tinymce').text().

Vim delete blank lines

I tried a few of the answers on this page, but a lot of them didn't work for me. Maybe because I'm using Vim on Windows 7 (don't mock, just have pity on me :p)?

Here's the easiest one that I found that works on Vim in Windows 7:

:v/\S/d

Here's a longer answer on the Vim Wikia: http://vim.wikia.com/wiki/Remove_unwanted_empty_lines

Using String Format to show decimal up to 2 places or simple integer

A recent project has a similar requirement. I wrote this decimal extension method, which uses the currency ("C") Format Specifier. In addition to removing zeros, it also has options for decimal digits precision, currency symbol, separator and culture.

public static DecimalExtension{

     public static string ToCurrency(this decimal val, 
                                     int precision = 2, 
                                     bool currencySymbol = false, 
                                     bool separator = false, 
                                     CultureInfo culture = null)
      {     
         if(culture == null) culture = new CultureInfo("en-US");
                                                   
         NumberFormatInfo nfi = culture.NumberFormat;
         nfi.CurrencyDecimalDigits = precision;
            
         string zeros = new String('0', precision);       
                    
         //Remove zeros
         var result = val.ToString("C",fi).Replace(nfi.CurrencyDecimalSeparator + zeros,"");
                     
         if(!separator) result = result.Replace(nfi.CurrencyGroupSeparator,"");
                    
         return currencySymbol? result: result.Replace(nfi.CurrencySymbol,"");      
        }   
}

Examples:

decimal Total = 123.00M;
Console.WriteLine(Total.ToCurrency());  
//output: 123

decimal Total = 1123.12M;
Console.WriteLine(Total.ToCurrency()); 
//Output:  1123.12

Console.WriteLine(Total.ToCurrency(4));
//Output:  1123.1200

Console.WriteLine(Total.ToCurrency(2,true,true));
//output:  $1,123.12
 
CultureInfo culture = new CultureInfo("pt-BR")  //Brazil
Console.WriteLine(Total.ToCurrency(2,true,true, culture));
//output:  R$ 1.123,12

Convert a 1D array to a 2D array in numpy

You can useflatten() from the numpy package.

import numpy as np
a = np.array([[1, 2],
       [3, 4],
       [5, 6]])
a_flat = a.flatten()
print(f"original array: {a} \nflattened array = {a_flat}")

Output:

original array: [[1 2]
 [3 4]
 [5 6]] 
flattened array = [1 2 3 4 5 6]

How to check if an NSDictionary or NSMutableDictionary contains a key?

if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
   //do something if doesn't exist
}

This is for nested dictionary structure

Change One Cell's Data in mysql

Some of the columns in MySQL have an "on update" clause, see:

mysql> SHOW COLUMNS FROM your_table_name;

I'm not sure how to update this but will post an edit when I find out.

Make EditText ReadOnly

I had no problem making EditTextPreference read-only, by using:

editTextPref.setSelectable(false);

This works well when coupled with using the 'summary' field to display read-only fields (useful for displaying account info, for example). Updating the summary fields dynamically snatched from http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html

private static final List<String> keyList;

static {
    keyList = new ArrayList<String>();
    keyList.add("field1");
    keyList.add("field2");
    keyList.add("field3");
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
        initSummary(getPreferenceScreen().getPreference(i));
    }
}

private void initSummary(Preference p) {
    if (p instanceof PreferenceCategory) {
        PreferenceCategory pCat = (PreferenceCategory) p;
        for (int i = 0; i < pCat.getPreferenceCount(); i++) {
            initSummary(pCat.getPreference(i));
        }
    } else {
        updatePrefSummary(p);
    }
}

private void updatePrefSummary(Preference p) {
    if (p instanceof ListPreference) {
        ListPreference listPref = (ListPreference) p;
        p.setSummary(listPref.getEntry());
    }
    if (p instanceof EditTextPreference) {
        EditTextPreference editTextPref = (EditTextPreference) p;
        //editTextPref.setEnabled(false); // this can be used to 'gray out' as well
        editTextPref.setSelectable(false);
        if (keyList.contains(p.getKey())) {
            p.setSummary(editTextPref.getText());
        }
    }
}

convert ArrayList<MyCustomClass> to JSONArray

As somebody figures out that the OP wants to convert custom List to org.json.JSONArray not the com.google.gson.JsonArray,the CORRECT answer should be like this:

Gson gson = new Gson();

String listString = gson.toJson(
                    targetList,
           new TypeToken<ArrayList<targetListItem>>() {}.getType());

 JSONArray jsonArray =  new JSONArray(listString);

How to set shadows in React Native for android?

The elevation style property on Android does not work unless backgroundColor has been specified for the element.

Android - elevation style property does not work without backgroundColor

Example:

{
  shadowColor: 'black',
  shadowOpacity: 0.26,
  shadowOffset: { width: 0, height: 2},
  shadowRadius: 10,
  elevation: 3,
  backgroundColor: 'white'
}

Unable to verify leaf signature

It's not an issue with the application, but with the certificate which is signed by an intermediary CA. If you accept that fact and still want to proceed, add the following to request options:

rejectUnauthorized: false

Full request:

request({
    "rejectUnauthorized": false,
    "url": domain+"/api/orders/originator/"+id,
    "method": "GET",
    "headers":{
        "X-API-VERSION": 1,
        "X-API-KEY": key
    },
}, function(err, response, body){
    console.log(err);
    console.log(response);
    console.log(body);
});

How to get span tag inside a div in jQuery and assign a text?

function Errormessage(txt) {
    $("#message").fadeIn("slow");
    $("#message span:first").text(txt);
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

DO NOT USE the Atom platformio-atom-ide-terminal Plugin to do this. USE THE TERMINAL OF YOUR DISTRO DIRECTLY.

I kept getting this error while rebasing/squishing commits and didn't know why because I had done it before several times.

Didn't matter how many times I would delete the index.lock file, every time it would fail.

Turns out it was because I was using the ATOM EDITOR terminal plugin. Once I used the terminal that ships with Ubuntu it worked like a charm.

MAC addresses in JavaScript

No you cannot get the MAC address in JavaScript, mainly because the MAC address uniquely identifies the running computer so it would be a security vulnerability.

Now if all you need is a unique identifier, I suggest you create one yourself using some cryptographic algorithm and store it in a cookie.

If you really need to know the MAC address of the computer AND you are developing for internal applications, then I suggest you use an external component to do that: ActiveX for IE, XPCOM for Firefox (installed as an extension).

Interface/enum listing standard mime-type constants

I solved this with a static class:

@SuppressWarnings("serial")
public class MimeTypes {

    private static final HashMap<String, String> mimeTypes;

    static {
        mimeTypes = new HashMap<String, String>() {
            {
                put(".323", "text/h323");
                put(".3g2", "video/3gpp2");
                put(".3gp", "video/3gpp");
                put(".3gp2", "video/3gpp2");
                put(".3gpp", "video/3gpp");
                put(".7z", "application/x-7z-compressed");
                put(".aa", "audio/audible");
                put(".AAC", "audio/aac");
                put(".aaf", "application/octet-stream");
                put(".aax", "audio/vnd.audible.aax");
                put(".ac3", "audio/ac3");
                put(".aca", "application/octet-stream");
                put(".accda", "application/msaccess.addin");
                put(".accdb", "application/msaccess");
                put(".accdc", "application/msaccess.cab");
                put(".accde", "application/msaccess");
                put(".accdr", "application/msaccess.runtime");
                put(".accdt", "application/msaccess");
                put(".accdw", "application/msaccess.webapplication");
                put(".accft", "application/msaccess.ftemplate");
                put(".acx", "application/internet-property-stream");
                put(".AddIn", "text/xml");
                put(".ade", "application/msaccess");
                put(".adobebridge", "application/x-bridge-url");
                put(".adp", "application/msaccess");
                put(".ADT", "audio/vnd.dlna.adts");
                put(".ADTS", "audio/aac");
                put(".afm", "application/octet-stream");
                put(".ai", "application/postscript");
                put(".aif", "audio/x-aiff");
                put(".aifc", "audio/aiff");
                put(".aiff", "audio/aiff");
                put(".air", "application/vnd.adobe.air-application-installer-package+zip");
                put(".amc", "application/x-mpeg");
                put(".application", "application/x-ms-application");
                put(".art", "image/x-jg");
                put(".asa", "application/xml");
                put(".asax", "application/xml");
                put(".ascx", "application/xml");
                put(".asd", "application/octet-stream");
                put(".asf", "video/x-ms-asf");
                put(".ashx", "application/xml");
                put(".asi", "application/octet-stream");
                put(".asm", "text/plain");
                put(".asmx", "application/xml");
                put(".aspx", "application/xml");
                put(".asr", "video/x-ms-asf");
                put(".asx", "video/x-ms-asf");
                put(".atom", "application/atom+xml");
                put(".au", "audio/basic");
                put(".avi", "video/x-msvideo");
                put(".axs", "application/olescript");
                put(".bas", "text/plain");
                put(".bcpio", "application/x-bcpio");
                put(".bin", "application/octet-stream");
                put(".bmp", "image/bmp");
                put(".c", "text/plain");
                put(".cab", "application/octet-stream");
                put(".caf", "audio/x-caf");
                put(".calx", "application/vnd.ms-office.calx");
                put(".cat", "application/vnd.ms-pki.seccat");
                put(".cc", "text/plain");
                put(".cd", "text/plain");
                put(".cdda", "audio/aiff");
                put(".cdf", "application/x-cdf");
                put(".cer", "application/x-x509-ca-cert");
                put(".chm", "application/octet-stream");
                put(".class", "application/x-java-applet");
                put(".clp", "application/x-msclip");
                put(".cmx", "image/x-cmx");
                put(".cnf", "text/plain");
                put(".cod", "image/cis-cod");
                put(".config", "application/xml");
                put(".contact", "text/x-ms-contact");
                put(".coverage", "application/xml");
                put(".cpio", "application/x-cpio");
                put(".cpp", "text/plain");
                put(".crd", "application/x-mscardfile");
                put(".crl", "application/pkix-crl");
                put(".crt", "application/x-x509-ca-cert");
                put(".cs", "text/plain");
                put(".csdproj", "text/plain");
                put(".csh", "application/x-csh");
                put(".csproj", "text/plain");
                put(".css", "text/css");
                put(".csv", "text/csv");
                put(".cur", "application/octet-stream");
                put(".cxx", "text/plain");
                put(".dat", "application/octet-stream");
                put(".datasource", "application/xml");
                put(".dbproj", "text/plain");
                put(".dcr", "application/x-director");
                put(".def", "text/plain");
                put(".deploy", "application/octet-stream");
                put(".der", "application/x-x509-ca-cert");
                put(".dgml", "application/xml");
                put(".dib", "image/bmp");
                put(".dif", "video/x-dv");
                put(".dir", "application/x-director");
                put(".disco", "text/xml");
                put(".dll", "application/x-msdownload");
                put(".dll.config", "text/xml");
                put(".dlm", "text/dlm");
                put(".doc", "application/msword");
                put(".docm", "application/vnd.ms-word.document.macroEnabled.12");
                put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                put(".dot", "application/msword");
                put(".dotm", "application/vnd.ms-word.template.macroEnabled.12");
                put(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
                put(".dsp", "application/octet-stream");
                put(".dsw", "text/plain");
                put(".dtd", "text/xml");
                put(".dtsConfig", "text/xml");
                put(".dv", "video/x-dv");
                put(".dvi", "application/x-dvi");
                put(".dwf", "drawing/x-dwf");
                put(".dwp", "application/octet-stream");
                put(".dxr", "application/x-director");
                put(".eml", "message/rfc822");
                put(".emz", "application/octet-stream");
                put(".eot", "application/octet-stream");
                put(".eps", "application/postscript");
                put(".etl", "application/etl");
                put(".etx", "text/x-setext");
                put(".evy", "application/envoy");
                put(".exe", "application/octet-stream");
                put(".exe.config", "text/xml");
                put(".fdf", "application/vnd.fdf");
                put(".fif", "application/fractals");
                put(".filters", "Application/xml");
                put(".fla", "application/octet-stream");
                put(".flr", "x-world/x-vrml");
                put(".flv", "video/x-flv");
                put(".fsscript", "application/fsharp-script");
                put(".fsx", "application/fsharp-script");
                put(".generictest", "application/xml");
                put(".gif", "image/gif");
                put(".group", "text/x-ms-group");
                put(".gsm", "audio/x-gsm");
                put(".gtar", "application/x-gtar");
                put(".gz", "application/x-gzip");
                put(".h", "text/plain");
                put(".hdf", "application/x-hdf");
                put(".hdml", "text/x-hdml");
                put(".hhc", "application/x-oleobject");
                put(".hhk", "application/octet-stream");
                put(".hhp", "application/octet-stream");
                put(".hlp", "application/winhlp");
                put(".hpp", "text/plain");
                put(".hqx", "application/mac-binhex40");
                put(".hta", "application/hta");
                put(".htc", "text/x-component");
                put(".htm", "text/html");
                put(".html", "text/html");
                put(".htt", "text/webviewhtml");
                put(".hxa", "application/xml");
                put(".hxc", "application/xml");
                put(".hxd", "application/octet-stream");
                put(".hxe", "application/xml");
                put(".hxf", "application/xml");
                put(".hxh", "application/octet-stream");
                put(".hxi", "application/octet-stream");
                put(".hxk", "application/xml");
                put(".hxq", "application/octet-stream");
                put(".hxr", "application/octet-stream");
                put(".hxs", "application/octet-stream");
                put(".hxt", "text/html");
                put(".hxv", "application/xml");
                put(".hxw", "application/octet-stream");
                put(".hxx", "text/plain");
                put(".i", "text/plain");
                put(".ico", "image/x-icon");
                put(".ics", "application/octet-stream");
                put(".idl", "text/plain");
                put(".ief", "image/ief");
                put(".iii", "application/x-iphone");
                put(".inc", "text/plain");
                put(".inf", "application/octet-stream");
                put(".inl", "text/plain");
                put(".ins", "application/x-internet-signup");
                put(".ipa", "application/x-itunes-ipa");
                put(".ipg", "application/x-itunes-ipg");
                put(".ipproj", "text/plain");
                put(".ipsw", "application/x-itunes-ipsw");
                put(".iqy", "text/x-ms-iqy");
                put(".isp", "application/x-internet-signup");
                put(".ite", "application/x-itunes-ite");
                put(".itlp", "application/x-itunes-itlp");
                put(".itms", "application/x-itunes-itms");
                put(".itpc", "application/x-itunes-itpc");
                put(".IVF", "video/x-ivf");
                put(".jar", "application/java-archive");
                put(".java", "application/octet-stream");
                put(".jck", "application/liquidmotion");
                put(".jcz", "application/liquidmotion");
                put(".jfif", "image/pjpeg");
                put(".jnlp", "application/x-java-jnlp-file");
                put(".jpb", "application/octet-stream");
                put(".jpe", "image/jpeg");
                put(".jpeg", "image/jpeg");
                put(".jpg", "image/jpeg");
                put(".js", "application/x-javascript");
                put(".json", "application/json");
                put(".jsx", "text/jscript");
                put(".jsxbin", "text/plain");
                put(".latex", "application/x-latex");
                put(".library-ms", "application/windows-library+xml");
                put(".lit", "application/x-ms-reader");
                put(".loadtest", "application/xml");
                put(".lpk", "application/octet-stream");
                put(".lsf", "video/x-la-asf");
                put(".lst", "text/plain");
                put(".lsx", "video/x-la-asf");
                put(".lzh", "application/octet-stream");
                put(".m13", "application/x-msmediaview");
                put(".m14", "application/x-msmediaview");
                put(".m1v", "video/mpeg");
                put(".m2t", "video/vnd.dlna.mpeg-tts");
                put(".m2ts", "video/vnd.dlna.mpeg-tts");
                put(".m2v", "video/mpeg");
                put(".m3u", "audio/x-mpegurl");
                put(".m3u8", "audio/x-mpegurl");
                put(".m4a", "audio/m4a");
                put(".m4b", "audio/m4b");
                put(".m4p", "audio/m4p");
                put(".m4r", "audio/x-m4r");
                put(".m4v", "video/x-m4v");
                put(".mac", "image/x-macpaint");
                put(".mak", "text/plain");
                put(".man", "application/x-troff-man");
                put(".manifest", "application/x-ms-manifest");
                put(".map", "text/plain");
                put(".master", "application/xml");
                put(".mda", "application/msaccess");
                put(".mdb", "application/x-msaccess");
                put(".mde", "application/msaccess");
                put(".mdp", "application/octet-stream");
                put(".me", "application/x-troff-me");
                put(".mfp", "application/x-shockwave-flash");
                put(".mht", "message/rfc822");
                put(".mhtml", "message/rfc822");
                put(".mid", "audio/mid");
                put(".midi", "audio/mid");
                put(".mix", "application/octet-stream");
                put(".mk", "text/plain");
                put(".mmf", "application/x-smaf");
                put(".mno", "text/xml");
                put(".mny", "application/x-msmoney");
                put(".mod", "video/mpeg");
                put(".mov", "video/quicktime");
                put(".movie", "video/x-sgi-movie");
                put(".mp2", "video/mpeg");
                put(".mp2v", "video/mpeg");
                put(".mp3", "audio/mpeg");
                put(".mp4", "video/mp4");
                put(".mp4v", "video/mp4");
                put(".mpa", "video/mpeg");
                put(".mpe", "video/mpeg");
                put(".mpeg", "video/mpeg");
                put(".mpf", "application/vnd.ms-mediapackage");
                put(".mpg", "video/mpeg");
                put(".mpp", "application/vnd.ms-project");
                put(".mpv2", "video/mpeg");
                put(".mqv", "video/quicktime");
                put(".ms", "application/x-troff-ms");
                put(".msi", "application/octet-stream");
                put(".mso", "application/octet-stream");
                put(".mts", "video/vnd.dlna.mpeg-tts");
                put(".mtx", "application/xml");
                put(".mvb", "application/x-msmediaview");
                put(".mvc", "application/x-miva-compiled");
                put(".mxp", "application/x-mmxp");
                put(".nc", "application/x-netcdf");
                put(".nsc", "video/x-ms-asf");
                put(".nws", "message/rfc822");
                put(".ocx", "application/octet-stream");
                put(".oda", "application/oda");
                put(".odc", "text/x-ms-odc");
                put(".odh", "text/plain");
                put(".odl", "text/plain");
                put(".odp", "application/vnd.oasis.opendocument.presentation");
                put(".ods", "application/oleobject");
                put(".odt", "application/vnd.oasis.opendocument.text");
                put(".one", "application/onenote");
                put(".onea", "application/onenote");
                put(".onepkg", "application/onenote");
                put(".onetmp", "application/onenote");
                put(".onetoc", "application/onenote");
                put(".onetoc2", "application/onenote");
                put(".orderedtest", "application/xml");
                put(".osdx", "application/opensearchdescription+xml");
                put(".p10", "application/pkcs10");
                put(".p12", "application/x-pkcs12");
                put(".p7b", "application/x-pkcs7-certificates");
                put(".p7c", "application/pkcs7-mime");
                put(".p7m", "application/pkcs7-mime");
                put(".p7r", "application/x-pkcs7-certreqresp");
                put(".p7s", "application/pkcs7-signature");
                put(".pbm", "image/x-portable-bitmap");
                put(".pcast", "application/x-podcast");
                put(".pct", "image/pict");
                put(".pcx", "application/octet-stream");
                put(".pcz", "application/octet-stream");
                put(".pdf", "application/pdf");
                put(".pfb", "application/octet-stream");
                put(".pfm", "application/octet-stream");
                put(".pfx", "application/x-pkcs12");
                put(".pgm", "image/x-portable-graymap");
                put(".pic", "image/pict");
                put(".pict", "image/pict");
                put(".pkgdef", "text/plain");
                put(".pkgundef", "text/plain");
                put(".pko", "application/vnd.ms-pki.pko");
                put(".pls", "audio/scpls");
                put(".pma", "application/x-perfmon");
                put(".pmc", "application/x-perfmon");
                put(".pml", "application/x-perfmon");
                put(".pmr", "application/x-perfmon");
                put(".pmw", "application/x-perfmon");
                put(".png", "image/png");
                put(".pnm", "image/x-portable-anymap");
                put(".pnt", "image/x-macpaint");
                put(".pntg", "image/x-macpaint");
                put(".pnz", "image/png");
                put(".pot", "application/vnd.ms-powerpoint");
                put(".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12");
                put(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
                put(".ppa", "application/vnd.ms-powerpoint");
                put(".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12");
                put(".ppm", "image/x-portable-pixmap");
                put(".pps", "application/vnd.ms-powerpoint");
                put(".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12");
                put(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
                put(".ppt", "application/vnd.ms-powerpoint");
                put(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
                put(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
                put(".prf", "application/pics-rules");
                put(".prm", "application/octet-stream");
                put(".prx", "application/octet-stream");
                put(".ps", "application/postscript");
                put(".psc1", "application/PowerShell");
                put(".psd", "application/octet-stream");
                put(".psess", "application/xml");
                put(".psm", "application/octet-stream");
                put(".psp", "application/octet-stream");
                put(".pub", "application/x-mspublisher");
                put(".pwz", "application/vnd.ms-powerpoint");
                put(".qht", "text/x-html-insertion");
                put(".qhtm", "text/x-html-insertion");
                put(".qt", "video/quicktime");
                put(".qti", "image/x-quicktime");
                put(".qtif", "image/x-quicktime");
                put(".qtl", "application/x-quicktimeplayer");
                put(".qxd", "application/octet-stream");
                put(".ra", "audio/x-pn-realaudio");
                put(".ram", "audio/x-pn-realaudio");
                put(".rar", "application/octet-stream");
                put(".ras", "image/x-cmu-raster");
                put(".rat", "application/rat-file");
                put(".rc", "text/plain");
                put(".rc2", "text/plain");
                put(".rct", "text/plain");
                put(".rdlc", "application/xml");
                put(".resx", "application/xml");
                put(".rf", "image/vnd.rn-realflash");
                put(".rgb", "image/x-rgb");
                put(".rgs", "text/plain");
                put(".rm", "application/vnd.rn-realmedia");
                put(".rmi", "audio/mid");
                put(".rmp", "application/vnd.rn-rn_music_package");
                put(".roff", "application/x-troff");
                put(".rpm", "audio/x-pn-realaudio-plugin");
                put(".rqy", "text/x-ms-rqy");
                put(".rtf", "application/rtf");
                put(".rtx", "text/richtext");
                put(".ruleset", "application/xml");
                put(".s", "text/plain");
                put(".safariextz", "application/x-safari-safariextz");
                put(".scd", "application/x-msschedule");
                put(".sct", "text/scriptlet");
                put(".sd2", "audio/x-sd2");
                put(".sdp", "application/sdp");
                put(".sea", "application/octet-stream");
                put(".searchConnector-ms", "application/windows-search-connector+xml");
                put(".setpay", "application/set-payment-initiation");
                put(".setreg", "application/set-registration-initiation");
                put(".settings", "application/xml");
                put(".sgimb", "application/x-sgimb");
                put(".sgml", "text/sgml");
                put(".sh", "application/x-sh");
                put(".shar", "application/x-shar");
                put(".shtml", "text/html");
                put(".sit", "application/x-stuffit");
                put(".sitemap", "application/xml");
                put(".skin", "application/xml");
                put(".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12");
                put(".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide");
                put(".slk", "application/vnd.ms-excel");
                put(".sln", "text/plain");
                put(".slupkg-ms", "application/x-ms-license");
                put(".smd", "audio/x-smd");
                put(".smi", "application/octet-stream");
                put(".smx", "audio/x-smd");
                put(".smz", "audio/x-smd");
                put(".snd", "audio/basic");
                put(".snippet", "application/xml");
                put(".snp", "application/octet-stream");
                put(".sol", "text/plain");
                put(".sor", "text/plain");
                put(".spc", "application/x-pkcs7-certificates");
                put(".spl", "application/futuresplash");
                put(".src", "application/x-wais-source");
                put(".srf", "text/plain");
                put(".SSISDeploymentManifest", "text/xml");
                put(".ssm", "application/streamingmedia");
                put(".sst", "application/vnd.ms-pki.certstore");
                put(".stl", "application/vnd.ms-pki.stl");
                put(".sv4cpio", "application/x-sv4cpio");
                put(".sv4crc", "application/x-sv4crc");
                put(".svc", "application/xml");
                put(".swf", "application/x-shockwave-flash");
                put(".t", "application/x-troff");
                put(".tar", "application/x-tar");
                put(".tcl", "application/x-tcl");
                put(".testrunconfig", "application/xml");
                put(".testsettings", "application/xml");
                put(".tex", "application/x-tex");
                put(".texi", "application/x-texinfo");
                put(".texinfo", "application/x-texinfo");
                put(".tgz", "application/x-compressed");
                put(".thmx", "application/vnd.ms-officetheme");
                put(".thn", "application/octet-stream");
                put(".tif", "image/tiff");
                put(".tiff", "image/tiff");
                put(".tlh", "text/plain");
                put(".tli", "text/plain");
                put(".toc", "application/octet-stream");
                put(".tr", "application/x-troff");
                put(".trm", "application/x-msterminal");
                put(".trx", "application/xml");
                put(".ts", "video/vnd.dlna.mpeg-tts");
                put(".tsv", "text/tab-separated-values");
                put(".ttf", "application/octet-stream");
                put(".tts", "video/vnd.dlna.mpeg-tts");
                put(".txt", "text/plain");
                put(".u32", "application/octet-stream");
                put(".uls", "text/iuls");
                put(".user", "text/plain");
                put(".ustar", "application/x-ustar");
                put(".vb", "text/plain");
                put(".vbdproj", "text/plain");
                put(".vbk", "video/mpeg");
                put(".vbproj", "text/plain");
                put(".vbs", "text/vbscript");
                put(".vcf", "text/x-vcard");
                put(".vcproj", "Application/xml");
                put(".vcs", "text/plain");
                put(".vcxproj", "Application/xml");
                put(".vddproj", "text/plain");
                put(".vdp", "text/plain");
                put(".vdproj", "text/plain");
                put(".vdx", "application/vnd.ms-visio.viewer");
                put(".vml", "text/xml");
                put(".vscontent", "application/xml");
                put(".vsct", "text/xml");
                put(".vsd", "application/vnd.visio");
                put(".vsi", "application/ms-vsi");
                put(".vsix", "application/vsix");
                put(".vsixlangpack", "text/xml");
                put(".vsixmanifest", "text/xml");
                put(".vsmdi", "application/xml");
                put(".vspscc", "text/plain");
                put(".vss", "application/vnd.visio");
                put(".vsscc", "text/plain");
                put(".vssettings", "text/xml");
                put(".vssscc", "text/plain");
                put(".vst", "application/vnd.visio");
                put(".vstemplate", "text/xml");
                put(".vsto", "application/x-ms-vsto");
                put(".vsw", "application/vnd.visio");
                put(".vsx", "application/vnd.visio");
                put(".vtx", "application/vnd.visio");
                put(".wav", "audio/wav");
                put(".wave", "audio/wav");
                put(".wax", "audio/x-ms-wax");
                put(".wbk", "application/msword");
                put(".wbmp", "image/vnd.wap.wbmp");
                put(".wcm", "application/vnd.ms-works");
                put(".wdb", "application/vnd.ms-works");
                put(".wdp", "image/vnd.ms-photo");
                put(".webarchive", "application/x-safari-webarchive");
                put(".webtest", "application/xml");
                put(".wiq", "application/xml");
                put(".wiz", "application/msword");
                put(".wks", "application/vnd.ms-works");
                put(".WLMP", "application/wlmoviemaker");
                put(".wlpginstall", "application/x-wlpg-detect");
                put(".wlpginstall3", "application/x-wlpg3-detect");
                put(".wm", "video/x-ms-wm");
                put(".wma", "audio/x-ms-wma");
                put(".wmd", "application/x-ms-wmd");
                put(".wmf", "application/x-msmetafile");
                put(".wml", "text/vnd.wap.wml");
                put(".wmlc", "application/vnd.wap.wmlc");
                put(".wmls", "text/vnd.wap.wmlscript");
                put(".wmlsc", "application/vnd.wap.wmlscriptc");
                put(".wmp", "video/x-ms-wmp");
                put(".wmv", "video/x-ms-wmv");
                put(".wmx", "video/x-ms-wmx");
                put(".wmz", "application/x-ms-wmz");
                put(".wpl", "application/vnd.ms-wpl");
                put(".wps", "application/vnd.ms-works");
                put(".wri", "application/x-mswrite");
                put(".wrl", "x-world/x-vrml");
                put(".wrz", "x-world/x-vrml");
                put(".wsc", "text/scriptlet");
                put(".wsdl", "text/xml");
                put(".wvx", "video/x-ms-wvx");
                put(".x", "application/directx");
                put(".xaf", "x-world/x-vrml");
                put(".xaml", "application/xaml+xml");
                put(".xap", "application/x-silverlight-app");
                put(".xbap", "application/x-ms-xbap");
                put(".xbm", "image/x-xbitmap");
                put(".xdr", "text/plain");
                put(".xht", "application/xhtml+xml");
                put(".xhtml", "application/xhtml+xml");
                put(".xla", "application/vnd.ms-excel");
                put(".xlam", "application/vnd.ms-excel.addin.macroEnabled.12");
                put(".xlc", "application/vnd.ms-excel");
                put(".xld", "application/vnd.ms-excel");
                put(".xlk", "application/vnd.ms-excel");
                put(".xll", "application/vnd.ms-excel");
                put(".xlm", "application/vnd.ms-excel");
                put(".xls", "application/vnd.ms-excel");
                put(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12");
                put(".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12");
                put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                put(".xlt", "application/vnd.ms-excel");
                put(".xltm", "application/vnd.ms-excel.template.macroEnabled.12");
                put(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
                put(".xlw", "application/vnd.ms-excel");
                put(".xml", "text/xml");
                put(".xmta", "application/xml");
                put(".xof", "x-world/x-vrml");
                put(".XOML", "text/plain");
                put(".xpm", "image/x-xpixmap");
                put(".xps", "application/vnd.ms-xpsdocument");
                put(".xrm-ms", "text/xml");
                put(".xsc", "application/xml");
                put(".xsd", "text/xml");
                put(".xsf", "text/xml");
                put(".xsl", "text/xml");
                put(".xslt", "text/xml");
                put(".xsn", "application/octet-stream");
                put(".xss", "application/xml");
                put(".xtp", "application/octet-stream");
                put(".xwd", "image/x-xwindowdump");
                put(".z", "application/x-compress");
                put(".zip", "application/x-zip-compressed");
            }
        };
    }

    public static String getMimeType(String extension) {
        if (extension == null) {
            return null;
        }

        if (!extension.startsWith(".")) {
            extension = "." + extension.toLowerCase(Locale.getDefault());
        }

        String mime = mimeTypes.get(extension);

        return mime != null ? mime : "application/octet-stream";
    }
}

How to generate the JPA entity Metamodel?

For Hibernate as provider which is most common IMHO:

In case of build tools like Gradle, Maven you need to have Hibernate JPA 2 Metamodel Generator jar in the classpath and compiler level>=1.6 that is all you need build the project and metamodel will be generated automatically.

In case of IDE Eclipse 1. goto Project->Properties->Java Compiler->Annotation Processing and enable it. 2. Expand Annotation Processing->Factory Path-> Add External Jar add Hibernate JPA 2 Metamodel Generator jar check the newly added jar and say OK. Clean and Build done!

Link Hibernate JPA 2 Metamodel Generator jar link from maven repo https://mvnrepository.com/artifact/org.hibernate/hibernate-jpamodelgen

How unique is UUID?

For UUID4 I make it that there are approximately as many IDs as there are grains of sand in a cube-shaped box with sides 360,000km long. That's a box with sides ~2 1/2 times longer than Jupiter's diameter.

Working so someone can tell me if I've messed up units:

  • volume of grain of sand 0.00947mm^3 (Guardian)
  • UUID4 has 122 random bits -> 5.3e36 possible values (wikipedia)
  • volume of that many grains of sand = 5.0191e34 mm^3 or 5.0191e+25m^3
  • side length of cubic box with that volume = 3.69E8m or 369,000km
  • diameter of Jupiter: 139,820km (google)

invalid byte sequence for encoding "UTF8"

I had the same problem: my file was not encoded as UTF-8. I have solved it by opening the file with notepad++ and changing the encoding of the file.

Go to "Encoding" and select "Convert to UTF-8". Save changes and that's all!

How to enter newline character in Oracle?

According to the Oracle PLSQL language definition, a character literal can contain "any printable character in the character set". https://docs.oracle.com/cd/A97630_01/appdev.920/a96624/02_funds.htm#2876

@Robert Love's answer exhibits a best practice for readable code, but you can also just type in the linefeed character into the code. Here is an example from a Linux terminal using sqlplus:

SQL> set serveroutput on
SQL> begin   
  2  dbms_output.put_line( 'hello' || chr(10) || 'world' );
  3  end;
  4  /
hello
world

PL/SQL procedure successfully completed.

SQL> begin
  2  dbms_output.put_line( 'hello
  3  world' );
  4  end;
  5  /
hello
world

PL/SQL procedure successfully completed.

Instead of the CHR( NN ) function you can also use Unicode literal escape sequences like u'\0085' which I prefer because, well you know we are not living in 1970 anymore. See the equivalent example below:

SQL> begin
  2  dbms_output.put_line( 'hello' || u'\000A' || 'world' );
  3  end;
  4  /
hello
world

PL/SQL procedure successfully completed.

For fair coverage I guess it is worth noting that different operating systems use different characters/character sequences for end of line handling. You've got to have a think about the context in which your program output is going to be viewed or printed, in order to determine whether you are using the right technique.

  • Microsoft Windows: CR/LF or u'\000D\000A'
  • Unix (including Apple MacOS): LF or u'\000A'
  • IBM OS390: NEL or u'\0085'
  • HTML: '<BR>'
  • XHTML: '<br />'
  • etc. etc.

What is the difference between a var and val definition in Scala?

The difference is that a var can be re-assigned to whereas a val cannot. The mutability, or otherwise of whatever is actually assigned, is a side issue:

import collection.immutable
import collection.mutable
var m = immutable.Set("London", "Paris")
m = immutable.Set("New York") //Reassignment - I have change the "value" at m.

Whereas:

val n = immutable.Set("London", "Paris")
n = immutable.Set("New York") //Will not compile as n is a val.

And hence:

val n = mutable.Set("London", "Paris")
n = mutable.Set("New York") //Will not compile, even though the type of n is mutable.

If you are building a data structure and all of its fields are vals, then that data structure is therefore immutable, as its state cannot change.

Relation between CommonJS, AMD and RequireJS?

CommonJS is more than that - it's a project to define a common API and ecosystem for JavaScript. One part of CommonJS is the Module specification. Node.js and RingoJS are server-side JavaScript runtimes, and yes, both of them implement modules based on the CommonJS Module spec.

AMD (Asynchronous Module Definition) is another specification for modules. RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.

AMD is generally more used in client-side (in-browser) JavaScript development due to this, and CommonJS Modules are generally used server-side. However, you can use either module spec in either environment - for example, RequireJS offers directions for running in Node.js and browserify is a CommonJS Module implementation that can run in the browser.

Pagination on a list using ng-repeat

Here is a demo code where there is pagination + Filtering with AngularJS :

https://codepen.io/lamjaguar/pen/yOrVym

JS :

var app=angular.module('myApp', []);

// alternate - https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
// alternate - http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html

app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.currentPage = 0;
    $scope.pageSize = 10;
    $scope.data = [];
    $scope.q = '';

    $scope.getData = function () {
      // needed for the pagination calc
      // https://docs.angularjs.org/api/ng/filter/filter
      return $filter('filter')($scope.data, $scope.q)
     /* 
       // manual filter
       // if u used this, remove the filter from html, remove above line and replace data with getData()

        var arr = [];
        if($scope.q == '') {
            arr = $scope.data;
        } else {
            for(var ea in $scope.data) {
                if($scope.data[ea].indexOf($scope.q) > -1) {
                    arr.push( $scope.data[ea] );
                }
            }
        }
        return arr;
       */
    }

    $scope.numberOfPages=function(){
        return Math.ceil($scope.getData().length/$scope.pageSize);                
    }

    for (var i=0; i<65; i++) {
        $scope.data.push("Item "+i);
    }
  // A watch to bring us back to the 
  // first pagination after each 
  // filtering
$scope.$watch('q', function(newValue,oldValue){             if(oldValue!=newValue){
      $scope.currentPage = 0;
  }
},true);
}]);

//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    }
});

HTML :

<div ng-app="myApp" ng-controller="MyCtrl">
  <input ng-model="q" id="search" class="form-control" placeholder="Filter text">
  <select ng-model="pageSize" id="pageSize" class="form-control">
        <option value="5">5</option>
        <option value="10">10</option>
        <option value="15">15</option>
        <option value="20">20</option>
     </select>
  <ul>
    <li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
      {{item}}
    </li>
  </ul>
  <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
        Previous
    </button> {{currentPage+1}}/{{numberOfPages()}}
  <button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="currentPage=currentPage+1">
        Next
    </button>
</div>

Event binding on dynamically created elements?

Use the .on() method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.

Also as of version 1.9 .live() method is removed.

How do I exit a WPF application programmatically?

Try

App.Current.Shutdown();

For me

Application.Current.Shutdown(); 

didn't work.

How to find out when a particular table was created in Oracle?

SELECT created
  FROM dba_objects
 WHERE object_name = <<your table name>>
   AND owner = <<owner of the table>>
   AND object_type = 'TABLE'

will tell you when a table was created (if you don't have access to DBA_OBJECTS, you could use ALL_OBJECTS instead assuming you have SELECT privileges on the table).

The general answer to getting timestamps from a row, though, is that you can only get that data if you have added columns to track that information (assuming, of course, that your application populates the columns as well). There are various special cases, however. If the DML happened relatively recently (most likely in the last couple hours), you should be able to get the timestamps from a flashback query. If the DML happened in the last few days (or however long you keep your archived logs), you could use LogMiner to extract the timestamps but that is going to be a very expensive operation particularly if you're getting timestamps for many rows. If you build the table with ROWDEPENDENCIES enabled (not the default), you can use

SELECT scn_to_timestamp( ora_rowscn ) last_modified_date,
       ora_rowscn last_modified_scn,
       <<other columns>>
  FROM <<your table>>

to get the last modification date and SCN (system change number) for the row. By default, though, without ROWDEPENDENCIES, the SCN is only at the block level. The SCN_TO_TIMESTAMP function also isn't going to be able to map SCN's to timestamps forever.

img src SVG changing the styles with CSS

Why not just using CSS's filter property to manipulate the color on :hover or whatever other state? I found it works over SVG images into img tags. At least, it's almost fully supported in 2020. It seams to me the simpliest solution. The only caveat is having to tweak the filter properties in order to find the target color. But you have also this very useful tool.

Button Listener for button in fragment in android

Your fragment class should implement OnClickListener

public class SmartTvControllerFragment extends Fragment implements View.OnClickListener

Then get view, link button and set onClickListener like in example below

 View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.smart_tv_controller_fragment, container, false);
    upButton = (Button) view.findViewById(R.id.smart_tv_controller_framgment_up_button);
    upButton.setOnClickListener(this);
    return view;
 }

And then add onClickListener method and do what you want.

@Override
public void onClick(View v) {
 //do what you want to do when button is clicked
    switch (v.getId()) {
        case R.id.textView_help:
            switchFragment(HelpFragment.TAG);
            break;
        case R.id.textView_settings:
            switchFragment(SettingsFragment.TAG);
            break;
    }
}

This is my example of code, but I hope you understood

How can I download a file from a URL and save it in Rails?

Here's possibly the simplest way:

IO.copy_stream(URI.open("https://i.pinimg.com/originals/24/17/d6/2417d6b3f3dc236b0b5b80fb00b3a791.png"), 'destination.png')

Java - Convert String to valid URI object

Well I tried using

String converted = URLDecoder.decode("toconvert","UTF-8");

I hope this is what you were actually looking for?

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

In my case running the bundle command did the trick. I trust they find each other then.

Failed to load resource: the server responded with a status of 404 (Not Found)

Please install App Script for Ionic 3 Solution npm i -D -E @ionic/app-scripts

How to create empty folder in java?

You can create folder using the following Java code:

File dir = new File("nameoffolder");
dir.mkdir();

By executing above you will have folder 'nameoffolder' in current folder.

VBA Count cells in column containing specified value

If you're looking to match non-blank values or empty cells and having difficulty with wildcard character, I found the solution below from here.

Dim n as Integer
n = Worksheets("Sheet1").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

Why is Tkinter Entry's get function returning nothing?

It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.

Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:

import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        print(self.entry.get())

app = SampleApp()
app.mainloop()

Run the program, type into the entry widget, then click on the button.

Format numbers to strings in Python

str() in python on an integer will not print any decimal places.

If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).

Perhaps the following code will demonstrate:

>>> str(5)
'5'
>>> int(8.7)
8

HTML5 Dynamically create Canvas

Via Jquery:

$('<canvas/>', { id: 'mycanvas', height: 500, width: 200});

http://jsfiddle.net/8DEsJ/736/

How to convert an entire MySQL database characterset and collation to UTF-8?

To change the character set encoding to UTF-8 for the database itself, type the following command at the mysql> prompt. Replace DBNAME with the database name:

ALTER DATABASE DBNAME CHARACTER SET utf8 COLLATE utf8_general_ci;

Make one div visible and another invisible

You can use the display property of style. Intialy set the result section style as

style = "display:none"

Then the div will not be visible and there won't be any white space.

Once the search results are being populated change the display property using the java script like

document.getElementById("someObj").style.display = "block"

Using java script you can make the div invisible

document.getElementById("someObj").style.display = "none"

Sequence contains more than one element

SingleOrDefault method throws an Exception if there is more than one element in the sequence.

Apparently, your query in GetCustomer is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.

Running unittest with typical test directory structure

From the article you linked to:

Create a test_modulename.py file and put your unittest tests in it. Since the test modules are in a separate directory from your code, you may need to add your module’s parent directory to your PYTHONPATH in order to run them:

$ cd /path/to/googlemaps

$ export PYTHONPATH=$PYTHONPATH:/path/to/googlemaps/googlemaps

$ python test/test_googlemaps.py

Finally, there is one more popular unit testing framework for Python (it’s that important!), nose. nose helps simplify and extend the builtin unittest framework (it can, for example, automagically find your test code and setup your PYTHONPATH for you), but it is not included with the standard Python distribution.

Perhaps you should look at nose as it suggests?

SQL Server - boolean literal?

I hope this answers the intent of the question. Although there are no Booleans in SQL Server, if you have a database that had Boolean types that was translated from Access, the phrase which works in Access was "...WHERE Foo" (Foo is the Boolean column name). It can be replaced by "...WHERE Foo<>0" ... and this works. Good luck!

How to round up integer division and have int result in Java?

To round up an integer division you can use

import static java.lang.Math.abs;

public static long roundUp(long num, long divisor) {
    int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
    return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}

or if both numbers are positive

public static long roundUp(long num, long divisor) {
    return (num + divisor - 1) / divisor;
}

Using jQuery to center a DIV on the screen

No need jquery for this

I used this to center Div element. Css Style,

.black_overlay{
    display: none;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}

.white_content {
    display: none;
    position: absolute;
    top: 25%;
    left: 25%;
    width: 50%;
    height: 50%;
    padding: 16px;
    border: 16px solid orange;
    background-color: white;
    z-index:1002;
    overflow: auto;
}

Open element

$(document).ready(function(){
    $(".open").click(function(e){
      $(".black_overlay").fadeIn(200);
    });

});

How to execute only one test spec with angular-cli

Adding to this for people like me who were searching for a way to run a single spec in Angular and found this SO.

According to the latest Angular docs (v9.0.6 at time of writing), the ng test command has an --include option where you can specify a directory of *.spec.(ts|tsx) files or just a single .spec.(ts|tsx) file itself.

https://angular.io/cli/test

Select max value of each group

select name, value 
from( select name, value, ROW_NUMBER() OVER(PARTITION BY name ORDER BY value desc) as rn
from out_pumptable ) as a
where rn = 1

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Handy for linux virtual machines; Use 75% of your total system memory for Tomcat. Yay AWK.

Put at start of "{tomcat}/bin/startup.sh"

export CATALINA_OPTS="-Xmx`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`k"

CASE IN statement with multiple values

If you have more numbers or if you intend to add new test numbers for CASE then you can use a more flexible approach:

DECLARE @Numbers TABLE
(
    Number VARCHAR(50) PRIMARY KEY
    ,Class TINYINT NOT NULL
);
INSERT @Numbers
VALUES ('1121231',1);
INSERT @Numbers
VALUES ('31242323',1);
INSERT @Numbers
VALUES ('234523',2);
INSERT @Numbers
VALUES ('2342423',2);

SELECT c.*, n.Class
FROM   tblClient c  
LEFT OUTER JOIN   @Numbers n ON c.Number = n.Number;

Also, instead of table variable you can use a regular table.

How to verify if nginx is running or not?

The modern (systemctl) way of doing it:

systemctl is-active nginx

You can use the exit value in your shell scripts as follows:

systemctl -q is-active nginx && echo "It is active, do something"

Android: textview hyperlink

I hit on the same problem and finally find the working solution.

  1. in the string.xml file, define:

    <string name="textWithHtml">The URL link is &lt;a href="http://www.google.com">Google&lt;/a></string>
    

Replace the "<" less than character with HTML escaped character.

  1. In Java code:

    String text = v.getContext().getString(R.string.textWithHtml);
    textView.setText(Html.fromHtml(text));
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    

And the TextBox will correctly display the text with clickable anchor link

Loading .sql files from within PHP

I use this all the time:

$sql = explode(";",file_get_contents('[your dump file].sql'));// 

foreach($sql as $query)
 mysql_query($query);

An error when I add a variable to a string

You have empty $entry_database variable. As you see in error: ListEmail, Title FROM WHERE ID bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:

SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]

which in your way should become:

SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'

batch file Copy files with certain extensions from multiple directories into one directory

In a batch file solution

for /R c:\source %%f in (*.xml) do copy %%f x:\destination\

The code works as such;

for each file for in directory c:\source and subdirectories /R that match pattern (\*.xml) put the file name in variable %%f, then for each file do copy file copy %%f to destination x:\\destination\\

Just tested it here on my Windows XP computer and it worked like a treat for me. But I typed it into command prompt so I used the single %f variable name version, as described in the linked question above.

URL.Action() including route values

outgoing url in mvc generated based on the current routing schema.

because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.

to solve this problem you should use UrlParameter.Optional:

 <a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>

Jenkins / Hudson environment variables

Solution that worked for me

source ~/.bashrc

Explanation

I first verified Jenkins was running BASH, with echo $SHELL and echo $BASH (note I'm explicitly putting #!/bin/bash atop the textarea in Jenkins, I'm not sure if that's a requirement to get BASH). sourceing /etc/profile as others suggested was not working.

Looking at /etc/profile I found

if [ "$PS1" ]; then
...

and inspecting "$PS1" found it null. I tried spoofing $PS1 to no avail like so

export PS1=1
bash -c 'echo $PATH'

however this did not produce the desired result (add the rest of the $PATH I expect to see). But if I tell bash to be interactive

export PS1=1
bash -ci 'echo $PATH'

the $PATH was altered as I expected.

I was trying to figure out how to properly spoof an interactive shell to get /etc/bash.bashrc to load, however it turns out all I needed was down in ~/.bashrc, so simply sourceing it solved the problem.

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

How to make readonly all inputs in some div in Angular2?

You can do like this. Open a ts file ad there make an interface with inputs you want and in the page you want to show under export class write

readonly yourinterface = yourinterface
readonly level: number[] = [];

and in your template do like this *ngFor="let yourtype of yourinterface"

How can I tell which button was clicked in a PHP form submit?

In HTML:

<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" name="btnDelete" value="Delete" />

In PHP:

if (isset($_POST["btnSubmit"])){
  // "Save Changes" clicked
} else if (isset($_POST["btnDelete"])){
  // "Delete" clicked
}

SELECT with LIMIT in Codeigniter

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

To execute more Maven builds from one script you shall use the Windows call function in the following way:

call mvn install:install-file -DgroupId=gdata -DartifactId=base -Dversion=1.0 -Dfile=gdata-base-1.0.jar  -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger -Dversion=2.0 -Dfile=gdata-blogger-2.0.jar  -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger-meta -Dversion=2.0 -Dfile=gdata-blogger-meta-2.0.jar  -Dpackaging=jar -DgeneratePom=true

Form Submit Execute JavaScript Best Practice?

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.

For example:

<script>
function doSomething() {
    alert('Form submitted!');
    return false;
}
</script>

<form onsubmit="return doSomething();" class="my-form">
    <input type="submit" value="Submit">
</form>

This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

<script>
$('.my-form').on('submit', function () {
    alert('Form submitted!');
    return false;
});
</script>

<form class="my-form">
    <input type="submit" value="Submit">
</form>

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

What it is telling you is - the 2nd guard let or the if let check is not happening on an Optional Int or Optional String. You already have a non-optional value, so guarding or if-letting is not needed anymore

Checking if a number is an Integer in Java

With Z I assume you mean Integers , i.e 3,-5,77 not 3.14, 4.02 etc.

A regular expression may help:

Pattern isInteger = Pattern.compile("\\d+");

How to update RecyclerView Adapter Data?

The best and the coolest way to add new data to the present data is

 ArrayList<String> newItems = new ArrayList<String>();
 newItems = getList();
 int oldListItemscount = alcontainerDetails.size();
 alcontainerDetails.addAll(newItems);           
 recyclerview.getAdapter().notifyItemChanged(oldListItemscount+1, al_containerDetails);

How do I request and process JSON with python?

For anything with requests to URLs you might want to check out requests. For JSON in particular:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

How does Python manage int and long?

Just to continue to all the answers that were given here, especially @James Lanes

the size of the integer type can be expressed by this formula:

total range = (2 ^ bit system)

lower limit = -(2 ^ bit system)*0.5 upper limit = ((2 ^ bit system)*0.5) - 1

Scroll Element into View with Selenium

def scrollToElement(element: WebElement) = {
  val location = element.getLocation
  driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}

How to find top three highest salary in emp table in oracle?

SELECT salary,first_name||' '||last_name "Name of the employee" 
FROM hr.employees 
WHERE rownum <= 3 
ORDER BY salary desc ;

multiple packages in context:component-scan, spring config

A delayed response but to give multiple packages using annotation based approach we can use as below:

@ComponentScan({"com.my.package.one","com.my.package.subpackage.two","com.your.package.supersubpackage.two"})

Declaring variables inside or outside of a loop

One solution to this problem could be to provide a variable scope encapsulating the while loop:

{
  // all tmp loop variables here ....
  // ....
  String str;
  while(condition){
      str = calculateStr();
      .....
  }
}

They would be automatically de-reference when the outer scope ends.

How to change the new TabLayout indicator color and height

from xml :

app:tabIndicatorColor="#fff"

from java :

tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));
tabLayout.setSelectedTabIndicatorHeight((int) (2 * getResources().getDisplayMetrics().density));

Case insensitive searching in Oracle

Since 10gR2, Oracle allows to fine-tune the behaviour of string comparisons by setting the NLS_COMP and NLS_SORT session parameters:

SQL> SET HEADING OFF
SQL> SELECT *
  2  FROM NLS_SESSION_PARAMETERS
  3  WHERE PARAMETER IN ('NLS_COMP', 'NLS_SORT');

NLS_SORT
BINARY

NLS_COMP
BINARY


SQL>
SQL> SELECT CASE WHEN 'abc'='ABC' THEN 1 ELSE 0 END AS GOT_MATCH
  2  FROM DUAL;

         0

SQL>
SQL> ALTER SESSION SET NLS_COMP=LINGUISTIC;

Session altered.

SQL> ALTER SESSION SET NLS_SORT=BINARY_CI;

Session altered.

SQL>
SQL> SELECT *
  2  FROM NLS_SESSION_PARAMETERS
  3  WHERE PARAMETER IN ('NLS_COMP', 'NLS_SORT');

NLS_SORT
BINARY_CI

NLS_COMP
LINGUISTIC


SQL>
SQL> SELECT CASE WHEN 'abc'='ABC' THEN 1 ELSE 0 END AS GOT_MATCH
  2  FROM DUAL;

         1

You can also create case insensitive indexes:

create index
   nlsci1_gen_person
on
   MY_PERSON
   (NLSSORT
      (PERSON_LAST_NAME, 'NLS_SORT=BINARY_CI')
   )
;

This information was taken from Oracle case insensitive searches. The article mentions REGEXP_LIKE but it seems to work with good old = as well.


In versions older than 10gR2 it can't really be done and the usual approach, if you don't need accent-insensitive search, is to just UPPER() both the column and the search expression.

jquery, find next element by class

To find the next element with the same class:

$(".class").eq( $(".class").index( $(element) ) + 1 )

How to open the second form?

On any click event (or other one):

Form2 frm2 = new Form2();
frm2.Show();

Post-increment and pre-increment within a 'for' loop produce same output

If you wrote it like this then it would matter :

for(i=0; i<5; i=j++) {
    printf("%d",i);
}

Would iterate once more than if written like this :

for(i=0; i<5; i=++j) {
    printf("%d",i);
}

"query function not defined for Select2 undefined error"

It seems that your selector returns an undefined element (Therefore undefined error is returned)

In case the element really exists, you are calling select2 on an input element without supplying anything to select2, where it should fetch the data from. Typically, one calls .select2({data: [{id:"firstid", text:"firsttext"}]).

pip install - locale.Error: unsupported locale setting

Run the following command (it will work):

export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales

Python function attributes - uses and abuses

I've created this helper decorator to easily set function attributes:

def with_attrs(**func_attrs):
    """Set attributes in the decorated function, at definition time.
    Only accepts keyword arguments.
    E.g.:
        @with_attrs(counter=0, something='boing')
        def count_it():
            count_it.counter += 1
        print count_it.counter
        print count_it.something
        # Out:
        # >>> 0
        # >>> 'boing'
    """
    def attr_decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            return fn(*args, **kwargs)

        for attr, value in func_attrs.iteritems():
            setattr(wrapper, attr, value)

        return wrapper

    return attr_decorator

A use case is to create a collection of factories and query the data type they can create at a function meta level.
For example (very dumb one):

@with_attrs(datatype=list)
def factory1():
    return [1, 2, 3]

@with_attrs(datatype=SomeClass)
def factory2():
    return SomeClass()

factories = [factory1, factory2]

def create(datatype):
    for f in factories:
        if f.datatype == datatype:
            return f()
    return None

PostgreSQL visual interface similar to phpMyAdmin?

phpPgAdmin might work for you, if you're already familiar with phpMyAdmin.

Please note that development of phpPgAdmin has moved to github per this notice but the SourceForge link above is for historical / documentation purposes.

But really there are dozens of tools that can do this.

How to hide element using Twitter Bootstrap and show it using jQuery?

Based on the above answers, I have just added my own functions and this further doesn't conflict with the available jquery functions like .hide(), .show(), .toggle(). Hope it helps.

    /*
     * .hideElement()
     * Hide the matched elements. 
     */
    $.fn.hideElement = function(){
        $(this).addClass('hidden');
        return this;
    };

    /*
     * .showElement()
     * Show the matched elements.
     */
    $.fn.showElement = function(){
        $(this).removeClass('hidden');
        return this;
    };

    /*
     * .toggleElement()
     * Toggle the matched elements.
     */
    $.fn.toggleElement = function(){
        $(this).toggleClass('hidden');
        return this;
    };

Command output redirect to file and terminal

In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :

ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt

Question mark and colon in JavaScript

It is called the Conditional Operator (which is a ternary operator).

It has the form of: condition ? value-if-true : value-if-false
Think of the ? as "then" and : as "else".

Your code is equivalent to

if (max != 0)
  hsb.s = 255 * delta / max;
else
  hsb.s = 0;

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

This isn't a direct answer, but I think it is a pretty sweet alternative.

http://www.s3auth.com/

It allows you to host your pages behind basic auth. Great for things like api docs in your private github repo. just ad a s3 put as part of your api build.

From ND to 1D arrays

One of the simplest way is to use flatten(), like this example :

 import numpy as np

 batch_y =train_output.iloc[sample, :]
 batch_y = np.array(batch_y).flatten()

My array it was like this :

    0
0   6
1   6
2   5
3   4
4   3
.
.
.

After using flatten():

array([6, 6, 5, ..., 5, 3, 6])

It's also the solution of errors of this type :

Cannot feed value of shape (100, 1) for Tensor 'input/Y:0', which has shape '(?,)' 

How to use phpexcel to read data and insert into database?

Using the PHPExcel library, the following code will do.

require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';    
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true); //optional

$objPHPExcel = $objReader->load(__DIR__.'/YourExcelFile.xlsx');
$objWorksheet = $objPHPExcel->getActiveSheet();

$i=1;
foreach ($objWorksheet->getRowIterator() as $row) {

    $column_A_Value = $objPHPExcel->getActiveSheet()->getCell("A$i")->getValue();//column A
    //you can add your own columns B, C, D etc.

    //inset $column_A_Value value in DB query here

    $i++;
}

Replace a string in shell script using a variable

Single quotes are very strong. Once inside, there's nothing you can do to invoke variable substitution, until you leave. Use double quotes instead:

echo $LINE | sed -e "s/12345678/$replace/g"

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

I tried everything above, but saw no results until I got a hint from here: https://superuser.com/questions/159486/how-to-kill-process-in-mac-os-x-and-not-have-it-restart-on-its-own

I eventually went over to the activity monitor in my Mac, force Quit the PID, and ran the command:

sudo /usr/local/mysql/support-files/mysql.server restart

The magic was done!!!

Submit form using a button outside the <form> tag

Try this:

<input type="submit" onclick="document.forms[0].submit();" />

Although I would suggest adding an id to the form and accessing by that instead of document.forms[index].

How can I add a column that doesn't allow nulls in a Postgresql database?

Or, create a new table as temp with the extra column, copy the data to this new table while manipulating it as necessary to fill the non-nullable new column, and then swap the table via a two-step name change.

Yes, it is more complicated, but you may need to do it this way if you don't want a big UPDATE on a live table.

Why can't DateTime.Parse parse UTC date

To correctly parse the string given in the question without changing it, use the following:

using System.Globalization;

string dateString = "Tue, 1 Jan 2008 00:00:00 UTC";
DateTime parsedDate = DateTime.ParseExact(dateString, "ddd, d MMM yyyy hh:mm:ss UTC", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);

This implementation uses a string to specify the exact format of the date string that is being parsed. The DateTimeStyles parameter is used to specify that the given string is a coordinated universal time string.

Convert XML String to Object

You need to use the xsd.exe tool which gets installed with the Windows SDK into a directory something similar to:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

And on 64-bit computers:

C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\bin

And on Windows 10 computers:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin

On the first run, you use xsd.exe and you convert your sample XML into a XSD file (XML schema file):

xsd yourfile.xml

This gives you yourfile.xsd, which in a second step, you can convert again using xsd.exe into a C# class:

xsd yourfile.xsd /c

This should give you a file yourfile.cs which will contain a C# class that you can use to deserialize the XML file you're getting - something like:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
msg resultingMessage = (msg)serializer.Deserialize(new XmlTextReader("yourfile.xml"));

Should work pretty well for most cases.

Update: the XML serializer will take any stream as its input - either a file or a memory stream will be fine:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));
msg resultingMessage = (msg)serializer.Deserialize(memStream);

or use a StringReader:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
StringReader rdr = new StringReader(inputString);
msg resultingMessage = (msg)serializer.Deserialize(rdr);

ImageView - have height match width?

Update: Sep 14 2017

According to a comment below, the percent support library is deprecated as of Android Support Library 26.0.0. This is the new way to do it:

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1" />

</android.support.constraint.ConstraintLayout>

See here

Deprecated:

According to this post by Android Developers, all you need to do now is to wrap whatever you want within a PercentRelativeLayout or a PercentFrameLayout, and then specify its ratios, like so

<android.support.percent.PercentRelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        app:layout_widthPercent="100%"
        app:layout_aspectRatio="100%"/>

</android.support.percent.PercentRelativeLayout>

Printing 2D array in matrix format

you can do like this also

        long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 }};

        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(1); j++)
            {
                Console.Write(arr[i,j]+" ");
            }
            Console.WriteLine();
        }

CSS @media print issues with background-color;

Tested and Working over Chrome, Firefox, Opera and Edge by 2016/10. Should work on any browser and should always look as expected.

Ok, I did a little cross-browser experiment for printing background colors. Just copy, paste & enjoy!

Here it is a full printable HTML page for bootstrap:

<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">

    /* Both z-index are resolving recursive element containment */
    [background-color] {
        z-index: 0;
        position: relative;
        -webkit-print-color-adjust: exact !important;
    }

    [background-color] canvas {
        display: block;
        position:absolute;
        z-index: -1;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

</style>
</head>

<!-- CONTENT -->
<body>

    <!-- PRINT ROW BLOCK -->
    <div class="container">

    <div class="row">
        <div class="col-xs-6">
            <div background-color="#A400C1">
                <h4>
                Hey... this works !
                </h4>
                <div background-color="#0068C1">
                    <p>
                    Ohh... this works recursive too !!
                    <div background-color="green" style="width: 80px; height: 60px">
                        Any size !!
                    </div>
                    </p>
                </div>
            </div>
        </div>

        <div class="col-xs-6">
            <div background-color="#FFCB83" style="height: 200px">
                Some content...
            </div>
        </div>

    </div>


<script>
    var containers = document.querySelectorAll("[background-color]");

    for (i = 0; i < containers.length; i++)
    {
        // Element
        var container = containers[i];
        container.insertAdjacentHTML('beforeend', '<canvas id="canvas-' + i + '"></canvas>');

        // Color
        var color = container.getAttribute("background-color");
        container.style.backgroundColor = color;

        // Inner Canvas
        var canvas = document.getElementById("canvas-" + i);
        canvas.width = container.offsetWidth;
        canvas.height = container.offsetHeight;
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = color;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    }

    window.print();
</script>


</body>

</html>

Using Powershell to stop a service remotely without WMI or remoting

As far as I know, and I cant verify it now, you cannot stop remote services with the Stop-Service cmdlet or with .Net, it is not supported.

Yes it works, but it stopes the service on your local machine, not on the remote computer.

Now, if the above is correct, without remoting or wmi enabled, you could set a scheduled job on the remote system, using AT, that runs Stop-Service locally.

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

Because I always struggle to remember, a quick summary of what each of these do:

>>> pd.Timestamp.now()  # naive local time
Timestamp('2019-10-07 10:30:19.428748')

>>> pd.Timestamp.utcnow()  # tz aware UTC
Timestamp('2019-10-07 08:30:19.428748+0000', tz='UTC')

>>> pd.Timestamp.now(tz='Europe/Brussels')  # tz aware local time
Timestamp('2019-10-07 10:30:19.428748+0200', tz='Europe/Brussels')

>>> pd.Timestamp.now(tz='Europe/Brussels').tz_localize(None)  # naive local time
Timestamp('2019-10-07 10:30:19.428748')

>>> pd.Timestamp.now(tz='Europe/Brussels').tz_convert(None)  # naive UTC
Timestamp('2019-10-07 08:30:19.428748')

>>> pd.Timestamp.utcnow().tz_localize(None)  # naive UTC
Timestamp('2019-10-07 08:30:19.428748')

>>> pd.Timestamp.utcnow().tz_convert(None)  # naive UTC
Timestamp('2019-10-07 08:30:19.428748')

How do I get LaTeX to hyphenate a word that contains a dash?

I had the same problem. I use hyphenat plus the following macro:

\RequirePackage{hyphenat}
\RequirePackage{expl3}


% The following defs make sure words that contain an explicit `-` (hyphen) are still hyphenated the normal way, and double- and triple hyphens keep working the way they should. Just don't use a `-` as the last token of your document. Also note that `-` is now a macro that is not fully expandable

\ExplSyntaxOn

% latex2e doesn't like commands starting with 'end', apparently expl3 doesn't have any problems with it
\cs_new:Npn \hyphenfix_emdash:c {---}
\cs_new:Npn \hyphenfix_endash:c {--}

\cs_new:Npn \hyphenfix_discardnext:NN #1#2{#1}


\catcode`\-=\active

\cs_new_protected:Npn -{
    \futurelet\hyphenfix_nexttok\hyphenfix_i:w
}

\cs_new:Npn \hyphenfix_i:w {
    \cs_if_eq:NNTF{\hyphenfix_nexttok}{-}{
        %discard the next `-` token
        \hyphenfix_discardnext:NN{\futurelet\hyphenfix_nexttok\hyphenfix_ii:w}
    }{
        % from package hyphenat
        \hyp
    }
}

\cs_new:Npn \hyphenfix_ii:w {
    \cs_if_eq:NNTF{\hyphenfix_nexttok}{-}{
        \hyphenfix_discardnext:NN{\hyphenfix_emdash:c}
    }{
        \hyphenfix_endash:c
    }
}


\ExplSyntaxOff

Note that this uses the expl3 package from latex3.

It makes the - an active character that scans forward to see if it is followed by more dashes. If so, it stays a -, to make sure -- and --- keep working. If not, it becomes the \hyp command from hyphenat, enabling word breaks in the rest of the word. This is a generic solution that makes all words that contain explicit hyphens hyphenate normally.

Note that - becomes a macro that is not fully expandable, so try to include this after loading other packages that may not expect - to be a macro

Edit: This is my second version, the first version was less robust when a { or } followed a hyphen. This one is not, but unlike the first version the - in this version is not fully expandable.

<SELECT multiple> - how to allow only one item selected?

You want only one option by default, but the user can select multiple options by pressing the CTRL key. This is (already) exactly how the SELECT multiple is meant to behave.

See this: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select_multiple

Can you please clarify your question?

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

The easiest way is to change imdb.py setting allow_pickle=True to np.load at the line where imdb.py throws error.

How do I change screen orientation in the Android emulator?

On Ubuntu none of the keys (Ctrl+F11/F12 or numpad 7/numpad 9) worked for me. But I can rotate the emulator sending the keys with xdotool.

For example for a VM named "Galaxy_Nexus" I can rotate the emulator with:

xdotool search --name "Galaxy" key "ctrl_L+F11"

How to scroll to the bottom of a UITableView on the iPhone before the view appears

Thanks Jacob for the answer. really helpfull if anyone interesting with monotouch c# version

private void SetScrollPositionDown() {
    if (tblShoppingListItem.ContentSize.Height > tblShoppingListItem.Frame.Size.Height) {
        PointF offset = new PointF(0, tblShoppingListItem.ContentSize.Height - tblShoppingListItem.Frame.Size.Height);
        tblShoppingListItem.SetContentOffset(offset,true );
    }
}

How to Parse JSON Array with Gson

I was looking for a way to parse object arrays in a more generic way; here is my contribution:

CollectionDeserializer.java:

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {

    @Override
    public Collection<?> deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
        Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];

        return parseAsArrayList(json, realType);
    }

    /**
     * @param serializedData
     * @param type
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
        ArrayList<T> newArray = new ArrayList<T>();
        Gson gson = new Gson();

        JsonArray array= json.getAsJsonArray();
        Iterator<JsonElement> iterator = array.iterator();

        while(iterator.hasNext()){
            JsonElement json2 = (JsonElement)iterator.next();
            T object = (T) gson.fromJson(json2, (Class<?>)type);
            newArray.add(object);
        }

        return newArray;
    }

}

JSONParsingTest.java:

public class JSONParsingTest {

    List<World> worlds;

    @Test
    public void grantThatDeserializerWorksAndParseObjectArrays(){

        String worldAsString = "{\"worlds\": [" +
            "{\"name\":\"name1\",\"id\":1}," +
            "{\"name\":\"name2\",\"id\":2}," +
            "{\"name\":\"name3\",\"id\":3}" +
        "]}";

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
        Gson gson = builder.create();
        Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);

        assertNotNull(decoded);
        assertTrue(JSONParsingTest.class.isInstance(decoded));

        JSONParsingTest decodedObject = (JSONParsingTest)decoded;
        assertEquals(3, decodedObject.worlds.size());
        assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
    }
}

World.java:

public class World {
    private String name;
    private Long id;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}

How to remove the bottom border of a box with CSS

You could just set the width to auto. Then the width of the div will equal 0 if it has no content.

width:auto;

How do you search an amazon s3 bucket?

Take a look at this documentation: http://docs.aws.amazon.com/AWSSDKforPHP/latest/index.html#m=amazons3/get_object_list

You can use a Perl-Compatible Regular Expression (PCRE) to filter the names.

How to break out of the IF statement

In this case, insert a single else:

public void Method()
{
    if(something)
    {
        // some code
        if(something2)
        {
            // now I should break from ifs and go to te code outside ifs
        }
        else return;
    }
    // The code i want to go if the second if is true
}

Generally: There is no break in an if/else sequence, simply arrange your code correctly in if / if else / else clauses.

Getting Date or Time only from a DateTime Object

You can also use DateTime.Now.ToString("yyyy-MM-dd") for the date, and DateTime.Now.ToString("hh:mm:ss") for the time.

unsigned APK can not be installed

You can test the unsigned-apk only on Emulator. And as its step of application deployment and distribution, you should read this article atleast once, i suggest: http://developer.android.com/guide/publishing/app-signing.html.

For your question, you can find the below line in above article:

All applications must be signed. The system will not install an application that is not signed.

so you have to have signed-apk before the distribution of your application.

To generate Signed-apk of your application, there is a simple wizard procedure, click on File -> Export -> Android -> Export Android application.

enter image description here

How To Upload Files on GitHub

Well, there really is a lot to this. I'm assuming you have an account on http://github.com/. If not, go get one.

After that, you really can just follow their guide, its very simple and easy and the explanation is much more clear than mine: http://help.github.com/ >> http://help.github.com/mac-set-up-git/

To answer your specific question: You upload files to github through the git push command after you have added your files you needed through git add 'files' and commmited them git commit -m "my commit messsage"

How to get the mouse position without events (without moving the mouse)?

I implemented a horizontal/vertical search, (first make a div full of vertical line links arranged horizontally, then make a div full of horizontal line links arranged vertically, and simply see which one has the hover state) like Tim Down's idea above, and it works pretty fast. Sadly, does not work on Chrome 32 on KDE.

jsfiddle.net/5XzeE/4/

Get integer value from string in swift

If you are able to use a NSString only.

It's pretty similar to objective-c. All the data type are there but require the as NSString addition

    var x = "400.0" as NSString 

    x.floatValue //string to float
    x.doubleValue // to double
    x.boolValue // to bool
    x.integerValue // to integer
    x.intValue // to int

Also we have an toInt() function added See Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l page 49

x.toInt()

Setting Environment Variables for Node to retrieve

I was getting undefined after setting a system env var. When I put APP_VERSION in the User env var, then I can display the value from node via process.env.APP_VERSION

Failed to resolve: com.android.support:appcompat-v7:28.0

in build.gradle , the version of bellow line should be same

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:design:28.0.0'

How can I read Chrome Cache files?

I've made short stupid script which extracts JPG and PNG files:

#!/usr/bin/php
<?php
 $dir="/home/user/.cache/chromium/Default/Cache/";//Chrome or chromium cache folder. 
 $ppl="/home/user/Desktop/temporary/"; // Place for extracted files 

 $list=scandir($dir);
 foreach ($list as $filename)
 {

 if (is_file($dir.$filename))
    {
        $cont=file_get_contents($dir.$filename);
        if  (strstr($cont,'JFIF'))
        {
            echo ($filename."  JPEG \n");
            $start=(strpos($cont,"JFIF",0)-6);
            $end=strpos($cont,"HTTP/1.1 200 OK",0);
            $cont=substr($cont,$start,$end-6);
            $wholename=$ppl.$filename.".jpg";
            file_put_contents($wholename,$cont);
            echo("Saving :".$wholename." \n" );


                }
        elseif  (strstr($cont,"\211PNG"))
        {
            echo ($filename."  PNG \n");
            $start=(strpos($cont,"PNG",0)-1);
            $end=strpos($cont,"HTTP/1.1 200 OK",0);
            $cont=substr($cont,$start,$end-1);
            $wholename=$ppl.$filename.".png";
            file_put_contents($wholename,$cont);
            echo("Saving :".$wholename." \n" );


                }
        else
        {
            echo ($filename."  UNKNOWN \n");
        }
    }
 }
?>

Stateless vs Stateful

I had the same doubt about stateful v/s stateless class design and did some research. Just completed and my findings has been posted in my blog

  • Entity classes needs to be stateful
  • The helper / worker classes should not be stateful.

How to track down a "double free or corruption" error

There are at least two possible situations:

  1. you are deleting the same entity twice
  2. you are deleting something that wasn't allocated

For the first one I strongly suggest NULL-ing all deleted pointers.

You have three options:

  1. overload new and delete and track the allocations
  2. yes, use gdb -- then you'll get a backtrace from your crash, and that'll probably be very helpful
  3. as suggested -- use Valgrind -- it isn't easy to get into, but it will save you time thousandfold in the future...

Typescript interface default values

You could use two separate configs. One as the input with optional properties (that will have default values), and another with only the required properties. This can be made convenient with & and Required:

interface DefaultedFuncConfig {
  b?: boolean;
}

interface MandatoryFuncConfig {
  a: boolean;
}

export type FuncConfig = MandatoryFuncConfig & DefaultedFuncConfig;
 
export const func = (config: FuncConfig): Required<FuncConfig> => ({
  b: true,
  ...config
});

// will compile
func({ a: true });
func({ a: true, b: true });

// will error
func({ b: true });
func({});

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I installed Oracle Express Edition and I have the same error. One of the possible reason that is maybe your user does not have permission to open this shortcut. Here is how I solved the problem.

1. Right-click the shortcut and select the properties. enter image description here

2. Now click the Open File Location. Now you will see there is a Get_Started shortcut. enter image description here

3. Now right-click the Get_Started and select the properties. Then select your user and give permission to your user in the security tab. enter image description here

Jquery UI tooltip does not support html content

Replacing the \n or the escaped <br/> does the trick while keeping the rest of the HTML escaped:

$(document).tooltip({
    content: function() {
        var title = $(this).attr("title") || "";
        return $("<a>").text(title).html().replace(/&lt;br *\/?&gt;/, "<br/>");
    },
});

How to vertically align a html radio button to it's label?

I like putting the inputs inside the labels (added bonus: now you don't need the for attribute on the label), and put vertical-align: middle on the input.

_x000D_
_x000D_
label > input[type=radio] {_x000D_
    vertical-align: middle;_x000D_
    margin-top: -2px;_x000D_
}_x000D_
_x000D_
#d2 {  _x000D_
    font-size: 30px;_x000D_
}
_x000D_
<div>_x000D_
 <label><input type="radio" name="radio" value="1">Good</label>_x000D_
 <label><input type="radio" name="radio" value="2">Excellent</label>_x000D_
<div>_x000D_
<br>_x000D_
<div id="d2">_x000D_
 <label><input type="radio" name="radio2" value="1">Good</label>_x000D_
 <label><input type="radio" name="radio2" value="2">Excellent</label>_x000D_
<div>
_x000D_
_x000D_
_x000D_

(The -2px margin-top is a matter of taste.)

Another option I really like is using a table. (Hold your pitch forks! It's really nice!) It does mean you need to add the for attribute to all your labels and ids to your inputs. I'd recommended this option for labels with long text content, over multiple lines.

_x000D_
_x000D_
<table><tr><td>_x000D_
    <input id="radioOption" name="radioOption" type="radio" />_x000D_
    </td><td>_x000D_
    <label for="radioOption">                     _x000D_
        Really good option_x000D_
    </label>_x000D_
</td></tr></table>
_x000D_
_x000D_
_x000D_

How does collections.defaultdict work?

Usually, a Python dictionary throws a KeyError if you try to get an item with a key that is not currently in the dictionary. The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int(), which will return the integer object 0. For the second example, default items are created using list(), which returns a new empty list object.

How to get database structure in MySQL via query

using this:

SHOW CREATE TABLE `users`;

will give you the DDL for that table

DESCRIBE `users`

will list the columns in that table

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

In Java, what is the best way to determine the size of an object?

Back when I worked at Twitter, I wrote a utility for calculating deep object size. It takes into account different memory models (32-bit, compressed oops, 64-bit), padding, subclass padding, works correctly on circular data structures and arrays. You can just compile this one .java file; it has no external dependencies:

https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/objectsize/ObjectSizeCalculator.java

How do I perform a Perl substitution on a string while keeping the original?

The one-liner solution is more useful as a shibboleth than good code; good Perl coders will know it and understand it, but it's much less transparent and readable than the two-line copy-and-modify couplet you're starting with.

In other words, a good way to do this is the way you're already doing it. Unnecessary concision at the cost of readability isn't a win.

Make the current Git branch a master branch

For me, i wanted my devl to be back to the master after it was ahead.

While on develop:

git checkout master
git pull

git checkout develop
git pull

git reset --hard origin/master
git push -f

jQuery append() - return appended elements

There's a simpler way to do this:

$(newHtml).appendTo('#myDiv').effects(...);

This turns things around by first creating newHtml with jQuery(html [, ownerDocument ]), and then using appendTo(target) (note the "To" bit) to add that it to the end of #mydiv.

Because you now start with $(newHtml) the end result of appendTo('#myDiv') is that new bit of html, and the .effects(...) call will be on that new bit of html too.

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

Appending a byte[] to the end of another byte[]

You need to declare out as a byte array with a length equal to the lengths of ciphertext and mac added together, and then copy ciphertext over the beginning of out and mac over the end, using arraycopy.

byte[] concatenateByteArrays(byte[] a, byte[] b) {
    byte[] result = new byte[a.length + b.length]; 
    System.arraycopy(a, 0, result, 0, a.length); 
    System.arraycopy(b, 0, result, a.length, b.length); 
    return result;
} 

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

A simple thing but I figured it out is: I missed adding @Log to the class.

@Log
public class YourClassName {


}

It may help someone.

SQL "IF", "BEGIN", "END", "END IF"?

If I remember correctly, and more often then not I do ... there is no END IF support in Transact-Sql. The BEGIN and END should do the job. Are you getting errors?

HTTP Basic Authentication - what's the expected web browser experience?

You can use Postman a plugin for chrome. It gives the ability to choose the authentication type you need for each of the requests. In that menu you can configure user and password. Postman will automatically translate the config to a authentication header that will be sent with your request.

Java unsupported major minor version 52.0

I noticed that in netbeans Apache configuration in the servers tab. you can state the platform for your web application. I changed to 1.8 and it worked fine. (I am targeting java 8 platform in my application). Hope that might t help.

jQuery: Selecting by class and input type

Just in case any dummies like me tried the suggestions here with a button and found nothing worked, you probably want this:

$(':button.myclass')

-bash: export: `=': not a valid identifier

Try to surround the path with quotes, and remove the spaces

export PYTHONPATH="/home/user/my_project":$PYTHONPATH

And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)

Execute the following command to check everything is configured correctly:

echo $PYTHONPATH

How to list files in a directory in a C program?

An example, available for POSIX compliant systems :

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h> 
#include <stdio.h> 

int main(void) {
  DIR *d;
  struct dirent *dir;
  d = opendir(".");
  if (d) {
    while ((dir = readdir(d)) != NULL) {
      printf("%s\n", dir->d_name);
    }
    closedir(d);
  }
  return(0);
}

Beware that such an operation is platform dependant in C.

Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

How to get the current taxonomy term ID (not the slug) in WordPress?

<?php 
$terms = get_the_terms( $post->ID, 'taxonomy');
foreach ( $terms as $term ) {
    $termID[] = $term->term_id;
}
echo $termID[0]; 
?>

Failed to authenticate on SMTP server error using gmail

If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"

You may try one of these methods:

Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.

Use double quote for your password: like - "Abc@%$67eSDu"

Apache Spark: map vs mapPartitions?

What's the difference between an RDD's map and mapPartitions method?

The method map converts each element of the source RDD into a single element of the result RDD by applying a function. mapPartitions converts each partition of the source RDD into multiple elements of the result (possibly none).

And does flatMap behave like map or like mapPartitions?

Neither, flatMap works on a single element (as map) and produces multiple elements of the result (as mapPartitions).

Maven skip tests

I have another approach for Intellij users, and it is working very fine for me:

  1. Click on the "Skip Test" button

enter image description here

  1. Hold the "CTRL" button
  2. Select "clean" and "install"

enter image description here

  1. Click on the "Run" button in the maven pannel

enter image description here

Wait for shell command to complete

Use the WScript.Shell instead, because it has a waitOnReturn option:

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

(Idea copied from Wait for Shell to finish, then format cells - synchronously execute a command)

Disable html5 video autoplay

Indeed setting autoplay to false doesn't help some videos will play anyway. See this case in fiddle.

You might want to do by code something in the line of if you want to pause all the videos:

videos = document.querySelectorAll("video"); 
for(video of videos) {
  video.pause(); 
}

Of course the above case will not work if the video tag is in a shadow root element, but then hardly any general solution will work with shadow roots elements. There you will need a custom approach and expand first the shadow roots.

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?

Ternary operation in CoffeeScript

You may also write it in two statements if it mostly is true use:

a = 5
a = 10 if false

Or use a switch statement if you need more possibilities:

a = switch x
  when true then 5
  when false then 10

With a boolean it may be oversized but i find it very readable.

How to copy selected lines to clipboard in vim

set guioptions+=a

will, ... uhmm, in short, whenever you select/yank something put it in the clipboard as well (not Vim's, but the global keyboard of the window system). That way you don't have to think about yanking things into a special register.

How to get the CUDA version?

If you run

nvidia-smi

You should find the CUDA Version on the top right corner of the comand's output. At least I found that output for CUDA version 10.0 e.g., enter image description here

Changing default startup directory for command prompt in Windows 7

"start in directory" command

cmd /K cd C:\WorkSpace

but if WorkSpace happens to be on different than C drive, console will be launched in default folder and then you still need to put D: to change drive To avoid this use cd with -d parameter

cmd /K cd -d D:\WorkSpace

create a shortcut and your fixed ;)

How can you detect the version of a browser?

Look at navigator.userAgent - Firefox/xxx.xxx.xxx is specified right at the end.

How to redirect to logon page when session State time out is completed in asp.net mvc

There is a generic solution:

Lets say you have a controller named Admin where you put content for authorized users.

Then, you can override the Initialize or OnAuthorization methods of Admin controller and write redirect to login page logic on session timeout in these methods as described:

protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        //lets say you set session value to a positive integer
        AdminLoginType = Convert.ToInt32(filterContext.HttpContext.Session["AdminLoginType"]);
        if (AdminLoginType == 0)
        {
            filterContext.HttpContext.Response.Redirect("~/login");
        }

        base.OnAuthorization(filterContext);
    }

Serialize and Deserialize Json and Json Array in Unity

IF you are using Vector3 this is what i did

1- I create a class Name it Player

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Player
{
    public Vector3[] Position;

}

2- then i call it like this

if ( _ispressed == true)
        {
            Player playerInstance = new Player();
            playerInstance.Position = newPos;
            string jsonData = JsonUtility.ToJson(playerInstance);

            reference.Child("Position" + Random.Range(0, 1000000)).SetRawJsonValueAsync(jsonData);
            Debug.Log(jsonData);
            _ispressed = false;
        }

3- and this is the result

"Position":[ {"x":-2.8567452430725099,"y":-2.4323320388793947,"z":0.0}]}

Get string between two strings in a string

Perhaps, a good way is just to cut out a substring:

String St = "super exemple of string key : text I want to keep - end of my string";

int pFrom = St.IndexOf("key : ") + "key : ".Length;
int pTo = St.LastIndexOf(" - ");

String result = St.Substring(pFrom, pTo - pFrom);

Get value (String) of ArrayList<ArrayList<String>>(); in Java

A cleaner way of iterating the lists is:

// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
    for (String string : innerList) {
        // do stuff with string
    }
}

for loop in Python

Here are some example to iterate over integer range and string:

#(initial,final but not included,gap)
for i in range(1,10,2): 
  print(i); 
1,3,5,7,9

# (initial, final but not included)  
# note: 4 not included
for i in range (1,4): 
   print(i);
1,2,3 

#note: 5 not included
for i in range (5):
  print (i);
0,1,2,3,4 

# you can also iterate over strings
myList = ["ml","ai","dl"];  

for i in myList:
  print(i);
output:  ml,ai,dl

How do you connect to multiple MySQL databases on a single webpage?

If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.

You would connect through PDO, like this:

try {
  $db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}

(Of course replace databasename, username and password above)

You can then query the database like this:

$result = $db->query("select * from tablename");
foreach ($result as $row) {
  echo $row['foo'] . "\n";
}

Or, if you have variables:

$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();

If you need multiple connections open at once, you can simply create multiple instances of PDO:

try {
  $db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
  $db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

Structs in Javascript

I use objects JSON style for dumb structs (no member functions).

How do I plot in real-time in a while loop using matplotlib?

show is probably not the best choice for this. What I would do is use pyplot.draw() instead. You also might want to include a small time delay (e.g., time.sleep(0.05)) in the loop so that you can see the plots happening. If I make these changes to your example it works for me and I see each point appearing one at a time.

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

Cannot deserialize the current JSON array (e.g. [1,2,3])

You have an array, convert it to an object, something like:

data: [{"id": 3636, "is_default": true, "name": "Unit", "quantity": 1, "stock": "100000.00", "unit_cost": "0"}, {"id": 4592, "is_default": false, "name": "Bundle", "quantity": 5, "stock": "100000.00", "unit_cost": "0"}]

How to delete multiple files at once in Bash on Linux?

Bash supports all sorts of wildcards and expansions.

Your exact case would be handled by brace expansion, like so:

$ rm -rf abc.log.2012-03-{14,27,28}

The above would expand to a single command with all three arguments, and be equivalent to typing:

$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28

It's important to note that this expansion is done by the shell, before rm is even loaded.

How to resolve the error on 'react-native start'

This is caused by node v12.11.0 due to the way it deals regular location there two ways to solve this problem

Method I

You can downgrade to node v12.10.0 this will apply the correct way to deal with parsing error

Method II

You can correctly terminate the regular expression in you case by changing the file located a:

\node_modules\metro-config\src\defaults\blacklist.js

From:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

To:

 var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

Multiple cases in switch statement

One lesser known facet of switch in C# is that it relies on the operator= and since it can be overriden you could have something like this:


string s = foo();

switch (s) {
  case "abc": /*...*/ break;
  case "def": /*...*/ break;
}

How to include file in a bash shell script

Simply put inside your script :

source FILE

Or

. FILE # POSIX compliant

$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.

Javascript - check array for value

This should do it:

for (var i = 0; i < bank_holidays.length; i++) {
    if (bank_holidays[i] === '06/04/2012') {
        alert('LOL');
    }
}

jsFiddle

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

Simply use the "utf-8-sig" codec:

fp = open("file.txt")
s = fp.read()
u = s.decode("utf-8-sig")

That gives you a unicode string without the BOM. You can then use

s = u.encode("utf-8")

to get a normal UTF-8 encoded string back in s. If your files are big, then you should avoid reading them all into memory. The BOM is simply three bytes at the beginning of the file, so you can use this code to strip them out of the file:

import os, sys, codecs

BUFSIZE = 4096
BOMLEN = len(codecs.BOM_UTF8)

path = sys.argv[1]
with open(path, "r+b") as fp:
    chunk = fp.read(BUFSIZE)
    if chunk.startswith(codecs.BOM_UTF8):
        i = 0
        chunk = chunk[BOMLEN:]
        while chunk:
            fp.seek(i)
            fp.write(chunk)
            i += len(chunk)
            fp.seek(BOMLEN, os.SEEK_CUR)
            chunk = fp.read(BUFSIZE)
        fp.seek(-BOMLEN, os.SEEK_CUR)
        fp.truncate()

It opens the file, reads a chunk, and writes it out to the file 3 bytes earlier than where it read it. The file is rewritten in-place. As easier solution is to write the shorter file to a new file like newtover's answer. That would be simpler, but use twice the disk space for a short period.

As for guessing the encoding, then you can just loop through the encoding from most to least specific:

def decode(s):
    for encoding in "utf-8-sig", "utf-16":
        try:
            return s.decode(encoding)
        except UnicodeDecodeError:
            continue
    return s.decode("latin-1") # will always work

An UTF-16 encoded file wont decode as UTF-8, so we try with UTF-8 first. If that fails, then we try with UTF-16. Finally, we use Latin-1 — this will always work since all 256 bytes are legal values in Latin-1. You may want to return None instead in this case since it's really a fallback and your code might want to handle this more carefully (if it can).

hadoop copy a local file system folder to HDFS

You can use :

1.LOADING DATA FROM LOCAL FILE TO HDFS

Syntax:$hadoop fs –copyFromLocal

EX: $hadoop fs –copyFromLocal localfile1 HDIR

2. Copying data From HDFS to Local

Sys: $hadoop fs –copyToLocal < new file name>

EX: $hadoop fs –copyToLocal hdfs/filename myunx;

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

Countercheck if boostrap/cache/config.php database details are correct. That should give you an hint if they are.

If they are not, then you need to clear the cache using the following steps :

  1. rm -fr bootstrap/cache/*
  2. php artisan optimize