Programs & Examples On #Jayrock

Jayrock is a JSON and JSON-RPC implementation for the Microsoft .NET framework. It aids the development of JSON services that can be invoked by Javascript client through proxies.

Storing a Key Value Array into a compact JSON string

So why don't you simply use a key-value literal?

var params = {
    'slide0001.html': 'Looking Ahead',
    'slide0002.html': 'Forecase',
    ...
};

return params['slide0001.html']; // returns: Looking Ahead

Python JSON serialize a Decimal object

I would like to let everyone know that I tried Michal Marczyk's answer on my web server that was running Python 2.6.5 and it worked fine. However, I upgraded to Python 2.7 and it stopped working. I tried to think of some sort of way to encode Decimal objects and this is what I came up with:

import decimal

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return str(o)
        return super(DecimalEncoder, self).default(o)

Note that this will convert the decimal to its string representation (e.g.; "1.2300") to a. not lose significant digits and b. prevent rounding errors.

This should hopefully help anyone who is having problems with Python 2.7. I tested it and it seems to work fine. If anyone notices any bugs in my solution or comes up with a better way, please let me know.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How to insert a value that contains an apostrophe (single quote)?

Because a single quote is used for indicating the start and end of a string; you need to escape it.

The short answer is to use two single quotes - '' - in order for an SQL database to store the value as '.

Look at using REPLACE to sanitize incoming values:

You want to check for '''', and replace them if they exist in the string with '''''' in order to escape the lone single quote.

Tomcat manager/html is not available?

You have to check if you have the folder with name manager inside the folder webapps in your tomcat.

Rubens-MacBook-Pro:tomcat rfanjul$ ls -la webapps/
total 16
drwxr-xr-x   8 rfanjul  staff   272 21 May 12:20 .
drwxr-xr-x  14 rfanjul  staff   476 21 May 12:22 ..
-rw-r--r--@  1 rfanjul  staff  6148 21 May 12:20 .DS_Store
drwxr-xr-x  19 rfanjul  staff   646 17 Feb 15:13 ROOT
drwxr-xr-x  51 rfanjul  staff  1734 17 Feb 15:13 docs
drwxr-xr-x   6 rfanjul  staff   204 17 Feb 15:13 examples
drwxr-xr-x   7 rfanjul  staff   238 17 Feb 15:13 host-manager
drwxr-xr-x   8 rfanjul  staff   272 17 Feb 15:13 manager

After that you will be sure that you have this permmint for you user in the file conf/tomcat-users.xml:

<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="test" password="test" roles="admin-gui,manager-gui"/>

restart tomcat and stat tomcat again.

sh bin/shutdown.sh 
sh bin/startup.sh

I hope that will works fine for you.

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

If a reboot does not correct the problem (as suggested by Greg Hegwill's answer) then check your PATH for conflicting installation(s) of the msys-1.0.dll (and possibly other related DLLs).

In my particular situation MinGW's installation of msys has a copy of that DLL in its bin directory (<MinGW_Install_Path>\msys\1.0\bin), and it was listed in the PATH. Git's cmd directory was listed in the PATH, but its bin was not. (Git's version of msys-1.0.dll is in the bin directory. Apparently the default installation of MSys-Git does not add its bin to the PATH.)

A temporary fix was to add Git's bin directory to the PATH so that it appears before MinGW's paths. (A more permanent fix will likely involve sorting out the path conflicts between MinGW's msys and Git's and/or removing the duplicate msys installations.)

load jquery after the page is fully loaded

You can try using your function and using a timeout waiting until the jQuery object is loaded

Code:

document.onload=function(){
    var fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
    document.getElementsByTagName("head")[0].appendChild(fileref);
    waitForjQuery();
}

function waitForjQuery() {
    if (typeof jQuery != 'undefined') {
        // do some stuff
    } else {
        window.setTimeout(function () { waitForjQuery(); }, 100);
    }
}

Extracting a parameter from a URL in WordPress

When passing parameters through the URL you're able to retrieve the values as GET parameters.

Use this:

$variable = $_GET['param_name'];

//Or as you have it
$ppc = $_GET['ppc'];

It is safer to check for the variable first though:

if (isset($_GET['ppc'])) {
  $ppc = $_GET['ppc'];
} else {
  //Handle the case where there is no parameter
}

Here's a bit of reading on GET/POST params you should look at: http://php.net/manual/en/reserved.variables.get.php

EDIT: I see this answer still gets a lot of traffic years after making it. Please read comments attached to this answer, especially input from @emc who details a WordPress function which accomplishes this goal securely.

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

How to use Git Revert

I reverted back a few commits by running 'git revert commit id' such as:

git revert b2cb7c248d416409f8eb42b561cbff91b0601712

Then i was prompted to commit the revert (just as you would when running 'git commit'). My default terminal program is Vim so i ran:

:wq 

Finally i pushed the change to the repository with:

git push

Passing arrays as parameters in bash

With a few tricks you can actually pass named parameters to functions, along with arrays.

The method I developed allows you to access parameters passed to a function like this:

testPassingParams() {

    @var hello
    l=4 @array anArrayWithFourElements
    l=2 @array anotherArrayWithTwo
    @var anotherSingle
    @reference table   # references only work in bash >=4.3
    @params anArrayOfVariedSize

    test "$hello" = "$1" && echo correct
    #
    test "${anArrayWithFourElements[0]}" = "$2" && echo correct
    test "${anArrayWithFourElements[1]}" = "$3" && echo correct
    test "${anArrayWithFourElements[2]}" = "$4" && echo correct
    # etc...
    #
    test "${anotherArrayWithTwo[0]}" = "$6" && echo correct
    test "${anotherArrayWithTwo[1]}" = "$7" && echo correct
    #
    test "$anotherSingle" = "$8" && echo correct
    #
    test "${table[test]}" = "works"
    table[inside]="adding a new value"
    #
    # I'm using * just in this example:
    test "${anArrayOfVariedSize[*]}" = "${*:10}" && echo correct
}

fourElements=( a1 a2 "a3 with spaces" a4 )
twoElements=( b1 b2 )
declare -A assocArray
assocArray[test]="works"

testPassingParams "first" "${fourElements[@]}" "${twoElements[@]}" "single with spaces" assocArray "and more... " "even more..."

test "${assocArray[inside]}" = "adding a new value"

In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1 (and others).

The code that makes this work is pretty light and works both in bash 3 and bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below was developed for that purpose.

Function.AssignParamLocally() {
    local commandWithArgs=( $1 )
    local command="${commandWithArgs[0]}"

    shift

    if [[ "$command" == "trap" || "$command" == "l="* || "$command" == "_type="* ]]
    then
        paramNo+=-1
        return 0
    fi

    if [[ "$command" != "local" ]]
    then
        assignNormalCodeStarted=true
    fi

    local varDeclaration="${commandWithArgs[1]}"
    if [[ $varDeclaration == '-n' ]]
    then
        varDeclaration="${commandWithArgs[2]}"
    fi
    local varName="${varDeclaration%%=*}"

    # var value is only important if making an object later on from it
    local varValue="${varDeclaration#*=}"

    if [[ ! -z $assignVarType ]]
    then
        local previousParamNo=$(expr $paramNo - 1)

        if [[ "$assignVarType" == "array" ]]
        then
            # passing array:
            execute="$assignVarName=( \"\${@:$previousParamNo:$assignArrLength}\" )"
            eval "$execute"
            paramNo+=$(expr $assignArrLength - 1)

            unset assignArrLength
        elif [[ "$assignVarType" == "params" ]]
        then
            execute="$assignVarName=( \"\${@:$previousParamNo}\" )"
            eval "$execute"
        elif [[ "$assignVarType" == "reference" ]]
        then
            execute="$assignVarName=\"\$$previousParamNo\""
            eval "$execute"
        elif [[ ! -z "${!previousParamNo}" ]]
        then
            execute="$assignVarName=\"\$$previousParamNo\""
            eval "$execute"
        fi
    fi

    assignVarType="$__capture_type"
    assignVarName="$varName"
    assignArrLength="$__capture_arrLength"
}

Function.CaptureParams() {
    __capture_type="$_type"
    __capture_arrLength="$l"
}

alias @trapAssign='Function.CaptureParams; trap "declare -i \"paramNo+=1\"; Function.AssignParamLocally \"\$BASH_COMMAND\" \"\$@\"; [[ \$assignNormalCodeStarted = true ]] && trap - DEBUG && unset assignVarType && unset assignVarName && unset assignNormalCodeStarted && unset paramNo" DEBUG; '
alias @param='@trapAssign local'
alias @reference='_type=reference @trapAssign local -n'
alias @var='_type=var @param'
alias @params='_type=params @param'
alias @array='_type=array @param'

How to create a list of objects?

Storing a list of object instances is very simple

class MyClass(object):
    def __init__(self, number):
        self.number = number

my_objects = []

for i in range(100):
    my_objects.append(MyClass(i))

# later

for obj in my_objects:
    print obj.number

matplotlib: plot multiple columns of pandas data frame on the bar chart

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

Instead, one can do

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")

.htaccess redirect all pages to new domain

I tried user968421's answer and the OP's solution but the browser popped up a security error for a checkout page. I can't tell you why exactly.

Our host (Site Ground) couldn't figure it out either.

The final solution was close, but a slight tweak to user968421's answer (side note: unlike the OP, I was trying to redirect to the corresponding page, not just to the homepage so I maintained the back reference [the $1 after the domain] from user968421's answer):

RewriteEngine on
RewriteRule (.*) https://newdomain.com/$1 [R=301,L]

Got the tweak from this htaccess redirect generator recommended by a Host Gator article (desperate times, desperate measures, amiright?).

IndentationError: unexpected unindent WHY?

This error could actually be in the code preceding where the error is reported. See the For example, if you have a syntax error as below, you'll get the indentation error. The syntax error is actually next to the "except" because it should contain a ":" right after it.

try:
    #do something
except
    print 'error/exception'


def printError(e):
    print e

If you change "except" above to "except:", the error will go away.

Good luck.

How to import multiple .csv files at once?

Using plyr::ldply there is roughly a 50% speed increase by enabling the .parallel option while reading 400 csv files roughly 30-40 MB each. Example includes a text progress bar.

library(plyr)
library(data.table)
library(doSNOW)

csv.list <- list.files(path="t:/data", pattern=".csv$", full.names=TRUE)

cl <- makeCluster(4)
registerDoSNOW(cl)

pb <- txtProgressBar(max=length(csv.list), style=3)
pbu <- function(i) setTxtProgressBar(pb, i)
dt <- setDT(ldply(csv.list, fread, .parallel=TRUE, .paropts=list(.options.snow=list(progress=pbu))))

stopCluster(cl)

JS map return object

You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
  return {_x000D_
    country: elem.country,_x000D_
    launches: elem.launches+10,_x000D_
  } _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
_x000D_
_x000D_

How do I make a matrix from a list of vectors in R?

Not straightforward, but it works:

> t(sapply(a, unlist))
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

python replace single backslash with double backslash

Use:

string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\")

Escape the \ character.

How can I debug javascript on Android?

I use Weinre, part of Apache Cordova.

With Weinre, I get Google Chrome's debug console in my desktop browser, and can connect Android to that debug console, and debug HTML and CSS. I can execute Javascript commands in the console, and they affect the Web page in the Android browser. Log messages from Android appear in the desktop debug console.

However I think it's not possible to view or step through the actual Javascript code. So I combine Weinre with log messages.

(I don't know much about JConsole but it seems to me that HTML and CSS inspection isn't possible with JConsole, only Javascript commands and logging (?).)

Installing Apache Maven Plugin for Eclipse

Ubuntu 12.04's Eclipse was so broken for me I couldn't get M2E to install. The only way to fixed it was by using the official tar archive from the eclipse download page after purging all the ubuntu eclipse packages. - Cheers

Format in kotlin string templates

Kotlin's String class has a format function now, which internally uses Java's String.format method:

/**
 * Uses this string as a format string and returns a string obtained by substituting the specified arguments,
 * using the default locale.
 */
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)

Usage

val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14

HTTP Content-Type Header and JSON

The Content-Type header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.

The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json then parse it as JSON.

This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-Type to detect what to do with it.

Python executable not finding libpython shared library

Try the following:

LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/python

Replace /usr/local/lib with the folder where you have installed libpython2.7.so.1.0 if it is not in /usr/local/lib.

If this works and you want to make the changes permanent, you have two options:

  1. Add export LD_LIBRARY_PATH=/usr/local/lib to your .profile in your home directory (this works only if you are using a shell which loads this file when a new shell instance is started). This setting will affect your user only.

  2. Add /usr/local/lib to /etc/ld.so.conf and run ldconfig. This is a system-wide setting of course.

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

This is a pretty common proof. One way to prove this is to use mathematical induction. Here is a link: http://zimmer.csufresno.edu/~larryc/proofs/proofs.mathinduction.html

how to make a div to wrap two float divs inside?

Here i show you a snippet where your problem is solved (i know, it's been too long since you posted it, but i think this is cleaner than de "clear" fix)

_x000D_
_x000D_
#nav_x000D_
        {_x000D_
            float: left;_x000D_
            width: 25%;_x000D_
            height: 150px;_x000D_
            background-color: #999;_x000D_
            margin-bottom: 10px;_x000D_
        }_x000D_
_x000D_
        #content_x000D_
        {_x000D_
            float: left;_x000D_
            margin-left: 1%;_x000D_
            width: 65%;_x000D_
            height: 150px;_x000D_
            background-color: #999;_x000D_
            margin-bottom: 10px;_x000D_
        }       _x000D_
        #wrap_x000D_
        {_x000D_
          background-color:#DDD;_x000D_
          overflow: hidden_x000D_
        }
_x000D_
    <div id="wrap">_x000D_
    <h1>wrap1 </h1>_x000D_
    <div id="nav"></div>_x000D_
    <div id="content"><a href="index.htm">&lt; Back to article</a></div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:.

You can convert between the two like this:

NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease]; 

Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):

BOOL success = [dict writeToFile:@"/file/path" atomically:YES];

To read a dictionary from a file, there's a corresponding method:

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];

If you want to read the file as an NSMutableDictionary, simply use:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

AngularJs - ng-model in a SELECT

You can use the ng-selected directive on the option elements. It takes expression that if truthy will set the selected property.

In this case:

<option ng-selected="data.unit == item.id" 
        ng-repeat="item in units" 
        ng-value="item.id">{{item.label}}</option>

Demo

_x000D_
_x000D_
angular.module("app",[]).controller("myCtrl",function($scope) {_x000D_
    $scope.units = [_x000D_
        {'id': 10, 'label': 'test1'},_x000D_
        {'id': 27, 'label': 'test2'},_x000D_
        {'id': 39, 'label': 'test3'},_x000D_
    ]_x000D_
_x000D_
        $scope.data = {_x000D_
        'id': 1,_x000D_
        'unit': 27_x000D_
        }_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="myCtrl">_x000D_
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">_x000D_
         <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>_x000D_
    </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Credentials for the SQL Server Agent service are invalid

In my case it was more of a Microsoft bug, than an actual issue. I installed under the Administrator login and used strong password btw but I was still getting this error constantly.

I tried to install with Windows credential without entering the password, but that did not go through either. Was getting the same error.

Then I cleared all password textboxes manually and copies the correct password in each text box. Hit enter, and it went through.

The error was most likely misleading.

How to support UTF-8 encoding in Eclipse

You can set an explicit Java default character encoding operating system-wide by setting the environment variable JAVA_TOOL_OPTIONS with the value -Dfile.encoding="UTF-8". Next time you start Eclipse, it should adhere to UTF-8 as the default character set.

See https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/envvars002.html

Make a table fill the entire window

Below line helped me to fix the issue of scroll bar for a table; the issue was awkward 2 scroll bars in a page. Below style when applied to table worked fine for me.
<table Style="position: absolute; height: 100%; width: 100%";/>

Wait until ActiveWorkbook.RefreshAll finishes - VBA

I have had a similar requirement. After a lot of testing I found a simple but not very elegant solution (not sure if it will work for you?)...

After my macro refresh's the data that Excel is getting, I added into my macro the line "Calculate" (normally used to recalculate the workbook if you have set calculation to manual).

While I don't need to do do this, it appears by adding this in, Excel waits while the data is refreshed before continuing with the rest of my macro.

Cloning an Object in Node.js

There is another library lodash, it has clone and cloneDeep.

clone will clone your object but not create a new instance for non-primitive values, instead it will use the referrence to the original object

cloneDeep will create literally new objects without having any referrence to the original object, so it more safe when you have to change the object afterwards.

Generate unique random numbers between 1 and 100

For example: To generate 8 unique random numbers and store them to an array, you can simply do this:

_x000D_
_x000D_
var arr = [];_x000D_
while(arr.length < 8){_x000D_
    var r = Math.floor(Math.random() * 100) + 1;_x000D_
    if(arr.indexOf(r) === -1) arr.push(r);_x000D_
}_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Rendering a template variable as HTML

You can render a template in your code like so:

from django.template import Context, Template
t = Template('This is your <span>{{ message }}</span>.')

c = Context({'message': 'Your message'})
html = t.render(c)

See the Django docs for further information.

Right pad a string with variable number of spaces

Based on KMier's answer, addresses the comment that this method poses a problem when the field to be padded is not a field, but the outcome of a (possibly complicated) function; the entire function has to be repeated.

Also, this allows for padding a field to the maximum length of its contents.

WITH
cte AS (
  SELECT 'foo' AS value_to_be_padded
  UNION SELECT 'foobar'
),
cte_max AS (
  SELECT MAX(LEN(value_to_be_padded)) AS max_len
)
SELECT
  CONCAT(SPACE(max_len - LEN(value_to_be_padded)), value_to_be_padded AS left_padded,
  CONCAT(value_to_be_padded, SPACE(max_len - LEN(value_to_be_padded)) AS right_padded;

SQL Server 2008 - Help writing simple INSERT Trigger

You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)

So to insert Employee / Department pairs that do not currently exist you might try something like the following.

CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
    Insert into Employee (Name, Department) 
    Select Distinct i.Name, i.Department 
    from Inserted i
    Left Join Employee e
    on i.Name = e.Name and i.Department = e.Department
    where e.Name is null
End

Node.js fs.readdir recursive directory search

just a simple walk

let pending = [baseFolderPath]
function walk () {
    pending.shift();
    // do stuffs width pending[0] and change pending items
    if (pending[0]) walk(pending[0])
}
walk(pending[0])

How to backup a local Git repository?

I started hacking away a bit on Yar's script and the result is on github, including man pages and install script:

https://github.com/najamelan/git-backup

Installation:

git clone "https://github.com/najamelan/git-backup.git"
cd git-backup
sudo ./install.sh

Welcoming all suggestions and pull request on github.

#!/usr/bin/env ruby
#
# For documentation please sea man git-backup(1)
#
# TODO:
# - make it a class rather than a function
# - check the standard format of git warnings to be conform
# - do better checking for git repo than calling git status
# - if multiple entries found in config file, specify which file
# - make it work with submodules
# - propose to make backup directory if it does not exists
# - depth feature in git config (eg. only keep 3 backups for a repo - like rotate...)
# - TESTING



# allow calling from other scripts
def git_backup


# constants:
git_dir_name    = '.git'          # just to avoid magic "strings"
filename_suffix = ".git.bundle"   # will be added to the filename of the created backup


# Test if we are inside a git repo
`git status 2>&1`

if $?.exitstatus != 0

   puts 'fatal: Not a git repository: .git or at least cannot get zero exit status from "git status"'
   exit 2


else # git status success

   until        File::directory?( Dir.pwd + '/' + git_dir_name )             \
            or  File::directory?( Dir.pwd                      ) == '/'


         Dir.chdir( '..' )
   end


   unless File::directory?( Dir.pwd + '/.git' )

      raise( 'fatal: Directory still not a git repo: ' + Dir.pwd )

   end

end


# git-config --get of version 1.7.10 does:
#
# if the key does not exist git config exits with 1
# if the key exists twice in the same file   with 2
# if the key exists exactly once             with 0
#
# if the key does not exist       , an empty string is send to stdin
# if the key exists multiple times, the last value  is send to stdin
# if exaclty one key is found once, it's value      is send to stdin
#


# get the setting for the backup directory
# ----------------------------------------

directory = `git config --get backup.directory`


# git config adds a newline, so remove it
directory.chomp!


# check exit status of git config
case $?.exitstatus

   when 1 : directory = Dir.pwd[ /(.+)\/[^\/]+/, 1]

            puts 'Warning: Could not find backup.directory in your git config file. Please set it. See "man git config" for more details on git configuration files. Defaulting to the same directroy your git repo is in: ' + directory

   when 2 : puts 'Warning: Multiple entries of backup.directory found in your git config file. Will use the last one: ' + directory

   else     unless $?.exitstatus == 0 then raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus ) end

end


# verify directory exists
unless File::directory?( directory )

   raise( 'fatal: backup directory does not exists: ' + directory )

end


# The date and time prefix
# ------------------------

prefix           = ''
prefix_date      = Time.now.strftime( '%F'       ) + ' - ' # %F = YYYY-MM-DD
prefix_time      = Time.now.strftime( '%H:%M:%S' ) + ' - '
add_date_default = true
add_time_default = false

prefix += prefix_date if git_config_bool( 'backup.prefix-date', add_date_default )
prefix += prefix_time if git_config_bool( 'backup.prefix-time', add_time_default )



# default bundle name is the name of the repo
bundle_name = Dir.pwd.split('/').last

# set the name of the file to the first command line argument if given
bundle_name = ARGV[0] if( ARGV[0] )


bundle_name = File::join( directory, prefix + bundle_name + filename_suffix )


puts "Backing up to bundle #{bundle_name.inspect}"


# git bundle will print it's own error messages if it fails
`git bundle create #{bundle_name.inspect} --all --remotes`


end # def git_backup



# helper function to call git config to retrieve a boolean setting
def git_config_bool( option, default_value )

   # get the setting for the prefix-time from git config
   config_value = `git config --get #{option.inspect}`

   # check exit status of git config
   case $?.exitstatus

      # when not set take default
      when 1 : return default_value

      when 0 : return true unless config_value =~ /(false|no|0)/i

      when 2 : puts 'Warning: Multiple entries of #{option.inspect} found in your git config file. Will use the last one: ' + config_value
               return true unless config_value =~ /(false|no|0)/i

      else     raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus )

   end
end

# function needs to be called if we are not included in another script
git_backup if __FILE__ == $0

Invalid default value for 'dateAdded'

I solved mine by changing DATE to DATETIME

How to change HTML Object element data attribute value in javascript

document.getElementById("PdfContentArea").setAttribute('data', path);

OR

var objectEl = document.getElementById("PdfContentArea")

objectEl.outerHTML = objectEl.outerHTML.replace(/data="(.+?)"/, 'data="' + path + '"');

Progress during large file copy (Copy-Item & Write-Progress?)

I haven't heard about progress with Copy-Item. If you don't want to use any external tool, you can experiment with streams. The size of buffer varies, you may try different values (from 2kb to 64kb).

function Copy-File {
    param( [string]$from, [string]$to)
    $ffile = [io.file]::OpenRead($from)
    $tofile = [io.file]::OpenWrite($to)
    Write-Progress -Activity "Copying file" -status "$from -> $to" -PercentComplete 0
    try {
        [byte[]]$buff = new-object byte[] 4096
        [long]$total = [int]$count = 0
        do {
            $count = $ffile.Read($buff, 0, $buff.Length)
            $tofile.Write($buff, 0, $count)
            $total += $count
            if ($total % 1mb -eq 0) {
                Write-Progress -Activity "Copying file" -status "$from -> $to" `
                   -PercentComplete ([long]($total * 100 / $ffile.Length))
            }
        } while ($count -gt 0)
    }
    finally {
        $ffile.Dispose()
        $tofile.Dispose()
        Write-Progress -Activity "Copying file" -Status "Ready" -Completed
    }
}

message box in jquery

If you don't wont use jquery.ui(that is highly recommended), you can take a look at Block.UI plugin.

Disable button in WPF?

This should do it:

<StackPanel>
    <TextBox x:Name="TheTextBox" />
    <Button Content="Click Me">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="IsEnabled" Value="True" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
                        <Setter Property="IsEnabled" Value="False" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</StackPanel>

When using a Settings.settings file in .NET, where is the config actually stored?

It is in a folder with your application's name in Application Data folder in User's home folder (C:\documents and settings\user on xp and c:\users\user on Windows Vista).

There is some information here also.

PS:- try accessing it by %appdata% in run box!

RadioGroup: How to check programmatically

it will work if you put your mOption.check(R.id.option1); into onAttachedToWindow method or like this:

view.post(new Runnable()
{
    public void run() 
    {
        // TODO Auto-generated method stub
        mOption.check(R.id.option1); 
    }
});

the reason may be that check method will only work when the radiogroup is actually rendered.

XAMPP on Windows - Apache not starting

I was able to fix this!

Had the same problems as stated above, made sure nothing was using port 80 and still not working and getting the message that Apache and Mysql were detected with the wrong path.

I did install XAMPP once before, uninstalled and reinstalled. I even manually uninstalled but still had issues.

The fix. Make sure you backup your system first!

  1. Start Services via Control Panel>Admin Tools (also with Ctrl+R and services.msc)

  2. Look for Apache and MySQL services. Look at the patch indicated in the description (right click on service then click on properties). Chances are that you have Apache listed twice, one from your correct install and one from a previous install. Even if you only see one, look at the path, chances are it's from a previous install and causing your install not to work. In either case, you need to delete those incorrect services.

    a. Got to command prompt (run as administrator): Start > all programs > Accessories > right click on Command Prompt > Select 'run as administrator'

    b. on command prompt type sc delete service, where service is the service you're wanting to delete, such as apache2.1 (or sc delete Apache2.4). It should be exactly as it appears in your services. If the service has spaces such as Apache 2.1 then enter it in quotes, i.e. sc delete "Apache 2.1"

    c. press enter. Now refresh or close/open your services window and you'll see it`s gone.

DO THIS for all services that XAMPP finds as running with an incorrect path.

Once you do this, go ahead and restart the XAMPP control panel (as administrator) and voila! all works. No conflicts

Spring: Why do we autowire the interface and not the implemented class?

How does spring know which polymorphic type to use.

As long as there is only a single implementation of the interface and that implementation is annotated with @Component with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).

Do I need @Qualifier or @Resource?

Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier annotation to inject the right implementation, along with @Autowired annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name attribute of this annotation.

Why do we autowire the interface and not the implemented class?

Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.

interface IA
{
  public void someFunction();
}


class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Your bean configuration should look like this:

<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />

Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component as follows:

interface IA
{
  public void someFunction();
}

@Component(value="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


@Component(value="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

@Component    
class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Then worker in MyRunner will be injected with an instance of type B.

How to convert a timezone aware string to datetime in Python without dateutil?

As of Python 3.7, datetime.datetime.fromisoformat() can handle your format:

>>> import datetime
>>> datetime.datetime.fromisoformat('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

In older Python versions you can't, not without a whole lot of painstaking manual timezone defining.

Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.

As a side-effect, this means that timezone parsing also needs to be an external library. If dateutil is too heavy-weight for you, use iso8601 instead, it'll parse your specific format just fine:

>>> import iso8601
>>> iso8601.parse_date('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=<FixedOffset '-04:00'>)

iso8601 is a whopping 4KB small. Compare that tot python-dateutil's 148KB.

As of Python 3.2 Python can handle simple offset-based timezones, and %z will parse -hhmm and +hhmm timezone offsets in a timestamp. That means that for a ISO 8601 timestamp you'd have to remove the : in the timezone:

>>> from datetime import datetime
>>> iso_ts = '2012-11-01T04:16:13-04:00'
>>> datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))

The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.

How do I load a file into the python console?

Open command prompt in the folder in which you files to be imported are present. when you type 'python', python terminal will be opened. Now you can use

import script_name
Note: no .py extension to be used while importing.
How can I open a cmd window in a specific location?

Chrome doesn't delete session cookies

I just had this problem of Chrome storing a Session ID but I do not like the idea of disabling the option to continue where I left off. I looked at the cookies for the website and found a Session ID cookie for the login page. Deleting that did not correct my problem. I search for the domain and found there was another Session ID cookie on the domain. Deleting both Session ID cookies manually fixed the problem and I did not close and reopen the browser which could have restored the cookies.

How to get different colored lines for different plots in a single figure?

TL;DR No, it can't be done automatically. Yes, it is possible.

import matplotlib.pyplot as plt
my_colors = plt.rcParams['axes.prop_cycle']() # <<< note that we CALL the prop_cycle
fig, axes = plt.subplots(2,3)
for ax in axes.flatten(): ax.plot((0,1), (0,1), **next(my_colors))

enter image description here Each plot (axes) in a figure (figure) has its own cycle of colors — if you don't force a different color for each plot, all the plots share the same order of colors but, if we stretch a bit what "automatically" means, it can be done.


The OP wrote

[...] I have to identify each plot with a different color which should be automatically generated by [Matplotlib].

But... Matplotlib automatically generates different colors for each different curve

In [10]: import numpy as np
    ...: import matplotlib.pyplot as plt

In [11]: plt.plot((0,1), (0,1), (1,2), (1,0));
Out[11]:

enter image description here

So why the OP request? If we continue to read, we have

Can you please give me a method to put different colors for different plots in the same figure?

and it make sense, because each plot (each axes in Matplotlib's parlance) has its own color_cycle (or rather, in 2018, its prop_cycle) and each plot (axes) reuses the same colors in the same order.

In [12]: fig, axes = plt.subplots(2,3)

In [13]: for ax in axes.flatten():
    ...:     ax.plot((0,1), (0,1))

enter image description here

If this is the meaning of the original question, one possibility is to explicitly name a different color for each plot.

If the plots (as it often happens) are generated in a loop we must have an additional loop variable to override the color automatically chosen by Matplotlib.

In [14]: fig, axes = plt.subplots(2,3)

In [15]: for ax, short_color_name in zip(axes.flatten(), 'brgkyc'):
    ...:     ax.plot((0,1), (0,1), short_color_name)

enter image description here

Another possibility is to instantiate a cycler object

from cycler import cycler
my_cycler = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
actual_cycler = my_cycler()

fig, axes = plt.subplots(2,3)
for ax in axes.flat:
    ax.plot((0,1), (0,1), **next(actual_cycler))

enter image description here

Note that type(my_cycler) is cycler.Cycler but type(actual_cycler) is itertools.cycle.

json and empty array

"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

Finding the indices of matching elements in list in Python

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

Window vs Page vs UserControl for WPF navigation?

A Window object is just what it sounds like: its a new Window for your application. You should use it when you want to pop up an entirely new window. I don't often use more than one Window in WPF because I prefer to put dynamic content in my main Window that changes based on user action.

A Page is a page inside your Window. It is mostly used for web-based systems like an XBAP, where you have a single browser window and different pages can be hosted in that window. It can also be used in Navigation Applications like sellmeadog said.

A UserControl is a reusable user-created control that you can add to your UI the same way you would add any other control. Usually I create a UserControl when I want to build in some custom functionality (for example, a CalendarControl), or when I have a large amount of related XAML code, such as a View when using the MVVM design pattern.

When navigating between windows, you could simply create a new Window object and show it

var NewWindow = new MyWindow();
newWindow.Show();

but like I said at the beginning of this answer, I prefer not to manage multiple windows if possible.

My preferred method of navigation is to create some dynamic content area using a ContentControl, and populate that with a UserControl containing whatever the current view is.

<Window x:Class="MyNamespace.MainWindow" ...>
    <DockPanel>
        <ContentControl x:Name="ContentArea" />
    </DockPanel>
</Window>

and in your navigate event you can simply set it using

ContentArea.Content = new MyUserControl();

But if you're working with WPF, I'd highly recommend the MVVM design pattern. I have a very basic example on my blog that illustrates how you'd navigate using MVVM, using this pattern:

<Window x:Class="SimpleMVVMExample.ApplicationView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SimpleMVVMExample"
        Title="Simple MVVM Example" Height="350" Width="525">

   <Window.Resources>
      <DataTemplate DataType="{x:Type local:HomeViewModel}">
         <local:HomeView /> <!-- This is a UserControl -->
      </DataTemplate>
      <DataTemplate DataType="{x:Type local:ProductsViewModel}">
         <local:ProductsView /> <!-- This is a UserControl -->
      </DataTemplate>
   </Window.Resources>

   <DockPanel>
      <!-- Navigation Buttons -->
      <Border DockPanel.Dock="Left" BorderBrush="Black"
                                    BorderThickness="0,0,1,0">
         <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
               <DataTemplate>
                  <Button Content="{Binding Name}"
                          Command="{Binding DataContext.ChangePageCommand,
                             RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                          CommandParameter="{Binding }"
                          Margin="2,5"/>
               </DataTemplate>
            </ItemsControl.ItemTemplate>
         </ItemsControl>
      </Border>

      <!-- Content Area -->
      <ContentControl Content="{Binding CurrentPageViewModel}" />
   </DockPanel>
</Window>

Screenshot1 Screenshot2

Alternative for frames in html5 using iframes

While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.

Is there a “not in” operator in JavaScript for checking object properties?

Two quick possibilities:

if(!('foo' in myObj)) { ... }

or

if(myObj['foo'] === undefined) { ... }

Add Keypair to existing EC2 instance

Once an instance has been started, there is no way to change the keypair associated with the instance at a meta data level, but you can change what ssh key you use to connect to the instance.

stackoverflow.com/questions/7881469/change-key-pair-for-ec2-instance

Putting an if-elif-else statement on one line?

It also depends on the nature of your expressions. The general advice on the other answers of "not doing it" is quite valid for generic statements and generic expressions.

But if all you need is a "dispatch" table, like, calling a different function depending on the value of a given option, you can put the functions to call inside a dictionary.

Something like:

def save(): 
   ...
def edit():
   ...
options = {"save": save, "edit": edit, "remove": lambda : "Not Implemented"}

option = get_input()
result = options[option]()

Instead of an if-else:

if option=="save":
    save()
...

.gitignore and "The following untracked working tree files would be overwritten by checkout"

There is a command for this delicate task (permanently deleting untracked files)

git clean -i

Then git pull will do.

What is the correct way to declare a boolean variable in Java?

You don't have to, but some people like to explicitly initialize all variables (I do too). Especially those who program in a variety of languages, it's just easier to have the rule of always initializing your variables rather than deciding case-by-case/language-by-language.

For instance Java has default values for Boolean, int etc .. C on the other hand doesn't automatically give initial values, whatever happens to be in memory is what you end up with unless you assign a value explicitly yourself.

In your case above, as you discovered, the code works just as well without the initialization, esp since the variable is set in the next line which makes it appear particularly redundant. Sometimes you can combine both of those lines (declaration and initialization - as shown in some of the other posts) and get the best of both approaches, i.e., initialize the your variable with the result of the email1.equals (email2); operation.

Windows equivalent of OS X Keychain?

It is year 2018, and Windows 10 has a "Credential Manager" that can be found in "Control Panel"

How to declare strings in C

This link should satisfy your curiosity.

Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.

But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.

Is it safe to delete the "InetPub" folder?

IIS will create it again AFAIK.

The remote end hung up unexpectedly while git cloning

The tricks above did not help me, as the repo was larger than the max push size allowed at github. What did work was a recommendation from https://github.com/git-lfs/git-lfs/issues/3758 which suggested pushing a bit at a time:

If your branch has a long history, you can try pushing a smaller number of commits at a time (say, 2000) with something like this:

git rev-list --reverse master | ruby -ne 'i ||= 0; i += 1; puts $_ if i % 2000 == 0' | xargs -I{} git push origin +{}:refs/heads/master

That will walk through the history of master, pushing objects 2000 at a time. (You can, of course, substitute a different branch in both places if you like.) When that's done, you should be able to push master one final time, and things should be up to date. If 2000 is too many and you hit the problem again, you can adjust the number so it's smaller.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

http://jsfiddle.net/Hx7B9/299/

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>
    </div>
</div>

java: HashMap<String, int> not working

You can use reference type in generic arguments, not primitive type. So here you should use

Map<String, Integer> myMap = new HashMap<String, Integer>();

and store value as

myMap.put("abc", 5);

What's the best way to generate a UML diagram from Python source code?

Certain classes of well-behaved programs may be diagrammable, but in the general case, it can't be done. Python objects can be extended at run time, and objects of any type can be assigned to any instance variable. Figuring out what classes an object can contain pointers to (composition) would require a full understanding of the runtime behavior of the program.

Python's metaclass capabilities mean that reasoning about the inheritance structure would also require a full understanding of the runtime behavior of the program.

To prove that these are impossible, you argue that if such a UML diagrammer existed, then you could take an arbitrary program, convert "halt" statements into statements that would impact the UML diagram, and use the UML diagrammer to solve the halting problem, which as we know is impossible.

Dynamic WHERE clause in LINQ

A simple Approach can be if your Columns are of Simple Type like String

public static IEnumerable<MyObject> WhereQuery(IEnumerable<MyObject> source, string columnName, string propertyValue)
{
   return source.Where(m => { return m.GetType().GetProperty(columnName).GetValue(m, null).ToString().StartsWith(propertyValue); });
}

Using Exit button to close a winform program

We can close every window using Application.Exit(); Using this method we can close hidden windows also.

private void btnExitProgram_Click(object sender, EventArgs e) { Application.Exit(); }

Is it possible to get element from HashMap by its position?

Another working approach is transforming map values into an array and then retrieve element at index. Test run of 100 000 element by index searches in LinkedHashMap of 100 000 objects using following approaches led to following results:

//My answer:
public Particle getElementByIndex(LinkedHashMap<Point, Particle> map,int index){
    return map.values().toArray(new Particle[map.values().size()])[index];
} //68 965 ms

//Syd Lambert's answer:
public Particle getElementByIndex(LinkedHashMap<Point, Particle> map,int index){
    return map.get( (map.keySet().toArray())[ index ] );
} //80 700 ms

All in all retrieving element by index from LinkedHashMap seems to be pretty heavy operation.

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

For me the code:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

throws error, but I added name attribute to input:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

and it started to work.

Hive: Filtering Data between Specified Dates when Date is a String

Try this:

select * from your_table
where date >= '2020-10-01'  

Integrity constraint violation: 1452 Cannot add or update a child row:

I just exported the table deleted and then imported it again and it worked for me. This was because i deleted the parent table(users) and then recreated it and child table(likes) has the foreign key to parent table(users).

remove kernel on jupyter notebook

jupyter kernelspec remove now exists, see #7934.

So you can just.

# List all kernels and grap the name of the kernel you want to remove
jupyter kernelspec list
# Remove it
jupyter kernelspec remove <kernel_name>

That's it.

Regular expressions in C: examples?

It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.

How to sort an array of objects with jquery or javascript

Well, it appears that instead of creating a true multidimensional array, you've created an array of (almost) JavaScript Objects. Try defining your arrays like this ->

var array = [ [id,name,value], [id,name,value] ]

Hopefully that helps!

Can Console.Clear be used to only clear a line instead of whole console?

Description

You can use the Console.SetCursorPosition function to go to a specific line number. Than you can use this function to clear the line

public static void ClearCurrentConsoleLine()
{
    int currentLineCursor = Console.CursorTop;
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth)); 
    Console.SetCursorPosition(0, currentLineCursor);
}

Sample

Console.WriteLine("Test");
Console.SetCursorPosition(0, Console.CursorTop - 1);
ClearCurrentConsoleLine();

More Information

jQuery: serialize() form and other parameters

I fix the problem with under statement ; send data with url same GET methode

$.ajax({
    url: 'includes/get_ajax_function.php?value=jack&id='+id,
    type: 'post',
    data: $('#b-info1').serializeArray(),

and get value with $_REQUEST['value'] OR $_GET['id']

Can someone explain mappedBy in JPA and Hibernate?

You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).

How to get "GET" request parameters in JavaScript?

Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.

With an example:

// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else

var _GET = (function() {
    var _get = {};
    var re = /[?&]([^=&]+)(=?)([^&]*)/g;
    while (m = re.exec(location.search))
        _get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
    return _get;
})();

console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123

2 "style" inline css img tags?

You should use :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="25"/>

That should work!!

If you want to create class then :

.size {
width:100px;
height:100px;
}

and then apply it like :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" class="size" alt="25"/>

by creating a class you can use it at multiple places.

If you want to use only at one place then use inline CSS. Also Inline CSS overrides other CSS.

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

How to initialize static variables

Instead of finding a way to get static variables working, I prefer to simply create a getter function. Also helpful if you need arrays belonging to a specific class, and a lot simpler to implement.

class MyClass
{
   public static function getTypeList()
   {
       return array(
           "type_a"=>"Type A",
           "type_b"=>"Type B",
           //... etc.
       );
   }
}

Wherever you need the list, simply call the getter method. For example:

if (array_key_exists($type, MyClass::getTypeList()) {
     // do something important...
}

How to calculate cumulative normal distribution?

It may be too late to answer the question but since Google still leads people here, I decide to write my solution here.

That is, since Python 2.7, the math library has integrated the error function math.erf(x)

The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution:

from math import *
def phi(x):
    #'Cumulative distribution function for the standard normal distribution'
    return (1.0 + erf(x / sqrt(2.0))) / 2.0

Ref:

https://docs.python.org/2/library/math.html

https://docs.python.org/3/library/math.html

How are the Error Function and Standard Normal distribution function related?

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

In my case eclipse.ini entry for --launcher.library was :

--launcher.library C:\Users\UserName\.p2\pool\plugins\org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.551.v20171108-1834

and on my machine 'C:\Users\UserName\.p2\' folder was missing hence installed the eclipse again which created the .p2 folder structure at required location and now I am able to login successfully.

VB.NET: Clear DataGridView

I found that setting the datasource to null removes the columns. This is what works for me:

c#:

((DataTable)myDataGrid.DataSource).Rows.Clear();

VB:

Call CType(myDataGrid.DataSource, DataTable).Rows.Clear()

Trigger css hover with JS

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually.


Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.

How to give the background-image path in CSS?

The solution (http://expressjs.com/en/starter/static-files.html).

once done this the image folder no longer shalt put it. only be

background-image: url ( "/ image.png");

carpera that the image is already in the static files

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

How do you tell if a checkbox is selected in Selenium for Java?

If you are using Webdriver then the item you are looking for is Selected.

Often times in the render of the checkbox doesn't actually apply the attribute checked unless specified.

So what you would look for in Selenium Webdriver is this

isChecked = e.findElement(By.tagName("input")).Selected;

As there is no Selected in WebDriver Java API, the above code should be as follows:

isChecked = e.findElement(By.tagName("input")).isSelected();

Math functions in AngularJS bindings

Either bind the global Math object onto the scope (remember to use $window not window)

$scope.abs = $window.Math.abs;

Use the binding in your HTML:

<p>Distance from zero: {{abs(distance)}}</p>

Or create a filter for the specific Math function you're after:

module.filter('abs', ['$window', function($window) {
  return function(n) {
    return $window.Math.abs($window.parseInt(n));
  };
});

Use the filter in your HTML:

<p>Distance from zero: {{distance | abs}}</p>

Get Image Height and Width as integer values?

PHP's getimagesize() returns an array of data. The first two items in the array are the two items you're interested in: the width and height. To get these, you would simply request the first two indexes in the returned array:

var $imagedata = getimagesize("someimage.jpg");

print "Image width  is: " . $imagedata[0];
print "Image height is: " . $imagedata[1];

For further information, see the documentation.

data.frame rows to a list

Eureka!

xy.list <- as.list(as.data.frame(t(xy.df)))

How to use XMLReader in PHP?

This Works Better and Faster For Me


<html>
<head>
<script>
function showRSS(str) {
  if (str.length==0) {
    document.getElementById("rssOutput").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("rssOutput").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","getrss.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="ZDN">ZDNet News</option>
<option value="job">Job</option>
</select>
</form>
<br>
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html> 

**The Backend File **


<?php
//get the q parameter from URL
$q=$_GET["q"];

//find out which feed was selected
if($q=="Google") {
  $xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
} elseif($q=="ZDN") {
  $xml=("https://www.zdnet.com/news/rss.xml");
}elseif($q == "job"){
  $xml=("https://ngcareers.com/feed");
}

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;

//output elements from "<channel>"
echo("<p><a href='" . $channel_link
  . "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");

//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');

$count = $x->length;

// print_r( $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue);
// return;

for ($i=0; $i <= $count; $i++) {
  //Title
  $item_title = $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue;
  //Link
  $item_link = $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue;
  //Description
  $item_desc = $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue;
  //Category
  $item_cat = $x->item(0)->getElementsByTagName('category')->item(0)->nodeValue;


  echo ("<p>Title: <a href='" . $item_link
  . "'>" . $item_title . "</a>");
  echo ("<br>");
  echo ("Desc: ".$item_desc);
   echo ("<br>");
  echo ("Category: ".$item_cat . "</p>");
}
?> 

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

This may also happen if you have a faulty or accidental equation in your csv file. i.e - One of the cells in your csv file starts with an equals sign (=) (An excel equation) which will, in turn throw an error. If you fix, or remove this equation by getting rid of the equals sign, it should solve the ORA-06502 error.

How can I suppress the newline after a print statement?

Code for Python 3.6.1

print("This first text and " , end="")

print("second text will be on the same line")

print("Unlike this text which will be on a newline")

Output

>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline

Selected value for JSP drop down using JSTL

Below is Example of simple dropdown using jstl tag

 <form:select path="cityFrom">  
    <form:option value="Ghaziabad" label="Ghaziabad"/>  
    <form:option value="Modinagar" label="Modinagar"/>  
    <form:option value="Meerut" label="Meerut"/>  
    <form:option value="Amristar" label="Amristar"/>  
 </form:select>

How to determine the Boost version on a system?

#include <boost/version.hpp>
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "Boost version: " 
          << BOOST_VERSION / 100000
          << "."
          << BOOST_VERSION / 100 % 1000
          << "."
          << BOOST_VERSION % 100 
          << std::endl;
    return 0;
}

Update: the answer has been fixed.

How to format DateTime columns in DataGridView?

You can set the format you want:

dataGridViewCellStyle.Format = "dd/MM/yyyy";
this.date.DefaultCellStyle = dataGridViewCellStyle;
// date being a System.Windows.Forms.DataGridViewTextBoxColumn

Why is Spring's ApplicationContext.getBean considered bad?

It's true that including the class in application-context.xml avoids the need to use getBean. However, even that is actually unnecessary. If you are writing a standalone application and you DON'T want to include your driver class in application-context.xml, you can use the following code to have Spring autowire the driver's dependencies:

public class AutowireThisDriver {

    private MySpringBean mySpringBean;    

    public static void main(String[] args) {
       AutowireThisDriver atd = new AutowireThisDriver(); //get instance

       ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
                  "/WEB-INF/applicationContext.xml"); //get Spring context 

       //the magic: auto-wire the instance with all its dependencies:
       ctx.getAutowireCapableBeanFactory().autowireBeanProperties(atd,
                  AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);        

       // code that uses mySpringBean ...
       mySpringBean.doStuff() // no need to instantiate - thanks to Spring
    }

    public void setMySpringBean(MySpringBean bean) {
       this.mySpringBean = bean;    
    }
}

I've needed to do this a couple of times when I have some sort of standalone class that needs to use some aspect of my app (eg for testing) but I don't want to include it in application-context because it is not actually part of the app. Note also that this avoids the need to look up the bean using a String name, which I've always thought was ugly.

best way to get the key of a key/value javascript object

A one liner for you:

const OBJECT = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
    'key4': 'value4'
};

const value = 'value2';

const key = Object.keys(OBJECT)[Object.values(OBJECT).indexOf(value)];

window.console.log(key); // = key2

jQuery ajax request being block because Cross-Origin

Try with cURL request for cross-domain.

If you are working through third party APIs or getting data through CROSS-DOMAIN, it is always recommended to use cURL script (server side) which is more secure.

I always prefer cURL script.

Display a loading bar before the entire page is loaded

Whenever you try to load any data in this window this gif will load.

HTML

Make a Div

<div class="loader"></div>

CSS .

.loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('https://lkp.dispendik.surabaya.go.id/assets/loading.gif') 50% 50% no-repeat rgb(249,249,249);

jQuery

$(window).load(function() {
        $(".loader").fadeOut("slow");
});
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

enter image description here

Does JSON syntax allow duplicate keys in an object?

The JSON spec says this:

An object is an unordered set of name/value pairs.

The important part here is "unordered": it implies uniqueness of keys, because the only thing you can use to refer to a specific pair is its key.

In addition, most JSON libs will deserialize JSON objects to hash maps/dictionaries, where keys are guaranteed unique. What happens when you deserialize a JSON object with duplicate keys depends on the library: in most cases, you'll either get an error, or only the last value for each duplicate key will be taken into account.

For example, in Python, json.loads('{"a": 1, "a": 2}') returns {"a": 2}.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

Deleting specific rows from DataTable

To remove entire row from DataTable , do like this

DataTable dt = new DataTable();  //User DataTable
DataRow[] rows;
rows = dt.Select("UserName = 'KarthiK'");  //'UserName' is ColumnName
foreach (DataRow row in rows)
     dt.Rows.Remove(row);

Open fancybox from function

Here is working code as per the author's Tips & Tricks blog post, put it in document ready:

  $("#mybutton").click(function(){
    $(".fancybox").trigger('click');  
  })

This triggers the smaller version of the currently displayed image or content, as if you had clicked on it manually. It avoids initializing the Fancybox again, but instead keeps the parameters you initialized it with on document ready. If you need to do something different when opening the box with a separate button compared to clicking on the box, you will need the parameters, but for many, this will be what they were looking for.

How to call a function in shell Scripting?

Example of using a function() in bash:

#!/bin/bash
# file.sh: a sample shell script to demonstrate the concept of Bash shell functions
# define usage function
usage(){
    echo "Usage: $0 filename"
    exit 1
}

# define is_file_exists function
# $f -> store argument passed to the script
is_file_exists(){
    local f="$1"
    [[ -f "$f" ]] && return 0 || return 1
}
# invoke  usage
# call usage() function if filename not supplied
[[ $# -eq 0 ]] && usage

# Invoke is_file_exits
if ( is_file_exists "$1" )
then
 echo "File found: $1"
else
 echo "File not found: $1"
fi

stop service in android

To stop the service we must use the method stopService():

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  //startService(myService);
  stopService(myService);

then the method onDestroy() in the service is called:

  @Override
    public void onDestroy() {

        Log.i(TAG, "onCreate() , service stopped...");
    }

Here is a complete example including how to stop the service.

How to list all files in a directory and its subdirectories in hadoop hdfs

/**
 * @param filePath
 * @param fs
 * @return list of absolute file path present in given path
 * @throws FileNotFoundException
 * @throws IOException
 */
public static List<String> getAllFilePath(Path filePath, FileSystem fs) throws FileNotFoundException, IOException {
    List<String> fileList = new ArrayList<String>();
    FileStatus[] fileStatus = fs.listStatus(filePath);
    for (FileStatus fileStat : fileStatus) {
        if (fileStat.isDirectory()) {
            fileList.addAll(getAllFilePath(fileStat.getPath(), fs));
        } else {
            fileList.add(fileStat.getPath().toString());
        }
    }
    return fileList;
}

Quick Example : Suppose you have the following file structure:

a  ->  b
   ->  c  -> d
          -> e 
   ->  d  -> f

Using the code above, you get:

a/b
a/c/d
a/c/e
a/d/f

If you want only the leaf (i.e. fileNames), use the following code in else block :

 ...
    } else {
        String fileName = fileStat.getPath().toString(); 
        fileList.add(fileName.substring(fileName.lastIndexOf("/") + 1));
    }

This will give:

b
d
e
f

Removing spaces from string

I also had this problem. To sort out the problem of spaces in the middle of the string this line of code always works:

String field = field.replaceAll("\\s+", "");

How can I build for release/distribution on the Xcode 4?

That part is now located under Schemes. If you edit your schemes you will see that you can set the debug/release/adhoc/distribution build config for each scheme.

How do I find the absolute position of an element using jQuery?

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 }

You can use this return value to position other elements at the same spot:

$(anotherElement).css(position)

Fade In Fade Out Android Animation in Java

Another alternative:

No need to define 2 animation for fadeIn and fadeOut. fadeOut is reverse of fadeIn.

So you can do this with Animation.REVERSE like this:

AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);

then onAnimationEnd:

alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
    @Override
        public void onAnimationStart(Animation animation) {
            //TODO: Run when animation start
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //TODO: Run when animation end
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            //TODO: Run when animation repeat
        }
    });

RunAs A different user when debugging in Visual Studio

I'm using the following method based on @Watki02's answer:

  1. Shift r-click the application to debug
  2. Run as different user
  3. Attach the debugger to the application

That way you can keep your visual studio instance as your own user whilst debugging from the other.

C# Select elements in list as List of string

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

Alternatively in Linq syntax (head compiled):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));

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

If you need a function that behaves as a nop, try

nop = lambda *a, **k: None
nop()

Sometimes I do stuff like this when I'm making dependencies optional:

try:
    import foo
    bar=foo.bar
    baz=foo.baz
except:
    bar=nop
    baz=nop

# Doesn't break when foo is missing:
bar()
baz()

array of string with unknown size

I think you may be looking for the StringBuilder class. If not, then the generic List class in string form:

List<string> myStringList = new List<string();
myStringList.Add("Test 1");
myStringList.Add("Test 2");

Or, if you need to be absolutely sure that the strings remain in order:

Queue<string> myStringInOriginalOrder = new Queue<string();
myStringInOriginalOrder.Enqueue("Testing...");
myStringInOriginalOrder.Enqueue("1...");
myStringInOriginalOrder.Enqueue("2...");
myStringInOriginalOrder.Enqueue("3...");

Remember, with the List class, the order of the items is an implementation detail and you are not guaranteed that they will stay in the same order you put them in.

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

yet another solution which uses the fact that np.nan != np.nan:

In [149]: df.query("EPS == EPS")
Out[149]:
                 STK_ID  EPS  cash
STK_ID RPT_Date
600016 20111231  600016  4.3   NaN
601939 20111231  601939  2.5   NaN

Why am I getting ImportError: No module named pip ' right after installing pip?

The ensurepip module was added in version 3.4 and then backported to 2.7.9.

So make sure your Python version is at least 2.7.9 if using Python 2, and at least 3.4 if using Python 3.

port forwarding in windows

I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm

The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.

How can I loop through all rows of a table? (MySQL)

Mr Purple's example I used in mysql trigger like that,

begin
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
Select COUNT(*) from user where deleted_at is null INTO n;
SET i=0;
WHILE i<n DO 
  INSERT INTO user_notification(notification_id,status,userId)values(new.notification_id,1,(Select userId FROM user LIMIT i,1)) ;
  SET i = i + 1;
END WHILE;
end

Forbidden You don't have permission to access / on this server

Found my solution on Apache/2.2.15 (Unix).

And Thanks for answer from @QuantumHive:

First: I finded all

Order allow,deny
Deny from all

instead of

Order allow,deny

Allow from all

and then:

I setted

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
#    AllowOverride FileInfo AuthConfig Limit
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
#    <Limit GET POST OPTIONS>
#        Order allow,deny
#        Allow from all
#    </Limit>
#    <LimitExcept GET POST OPTIONS>
#        Order deny,allow
#        Deny from all
#    </LimitExcept>
#</Directory>

Remove the previous "#" annotation to

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
    AllowOverride FileInfo AuthConfig Limit
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    <Limit GET POST OPTIONS>
        Order allow,deny
        Allow from all
    </Limit>
    <LimitExcept GET POST OPTIONS>
        Order deny,allow
        Deny from all
    </LimitExcept>
</Directory>

ps. my WebDir is: /var/www/html

What's the best UML diagramming tool?

For sequence diagrams, only, try websequencediagrams.com. It's a freemium (free for the basic tasks, paid for advanced features) product, and lets you quickly bang out a diagram without any fussing around with lines and stencils.

Alice->Bob: Authentication Request
note left of Bob: Bob thinks about it
Bob->Alice: Authentication Response

How do I add PHP code/file to HTML(.html) files?

Create an empty file using notepad and name it .htaccess ,Then copy that file in your project directory and add this line and save.

AddType application/x-httpd-php .htm .html

else save the .html file using .php as php can support html,and save it in computer/var/www/html path(linux)

Running .sh scripts in Git Bash

I had a similar problem, but I was getting an error message

cannot execute binary file

I discovered that the filename contained non-ASCII characters. When those were fixed, the script ran fine with ./script.sh.

Chrome not rendering SVG referenced via <img> tag

I exported my svg from Photoshop CC initially and had to manually add

version="1.1" into the <svg> tag

to get it showing on chrome.

React Native Change Default iOS Simulator Device

You can create an alias at your ~/.bash_profile file:

alias rn-ios="react-native run-ios --simulator \"iPhone 5s (10.0)\""

And then run react-native using the created alias:

$ rn-ios

How to properly seed random number generator

just to toss it out for posterity: it can sometimes be preferable to generate a random string using an initial character set string. This is useful if the string is supposed to be entered manually by a human; excluding 0, O, 1, and l can help reduce user error.

var alpha = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"

// generates a random string of fixed size
func srand(size int) string {
    buf := make([]byte, size)
    for i := 0; i < size; i++ {
        buf[i] = alpha[rand.Intn(len(alpha))]
    }
    return string(buf)
}

and I typically set the seed inside of an init() block. They're documented here: http://golang.org/doc/effective_go.html#init

Compare given date with today

You can use the DateTime class:

$past   = new DateTime("2010-01-01 00:00:00");
$now    = new DateTime();
$future = new DateTime("2021-01-01 00:00:00");

Comparison operators work*:

var_dump($past   < $now);         // bool(true)
var_dump($future < $now);         // bool(false)

var_dump($now == $past);          // bool(false)
var_dump($now == new DateTime()); // bool(true)
var_dump($now == $future);        // bool(false)

var_dump($past   > $now);         // bool(false)
var_dump($future > $now);         // bool(true)

It is also possible to grab the timestamp values from DateTime objects and compare them:

var_dump($past  ->getTimestamp());                        // int(1262286000)
var_dump($now   ->getTimestamp());                        // int(1431686228)
var_dump($future->getTimestamp());                        // int(1577818800)
var_dump($past  ->getTimestamp() < $now->getTimestamp()); // bool(true)
var_dump($future->getTimestamp() > $now->getTimestamp()); // bool(true)

* Note that === returns false when comparing two different DateTime objects even when they represent the same date.

How to generate a core dump in Linux on a segmentation fault?

As explained above the real question being asked here is how to enable core dumps on a system where they are not enabled. That question is answered here.

If you've come here hoping to learn how to generate a core dump for a hung process, the answer is

gcore <pid>

if gcore is not available on your system then

kill -ABRT <pid>

Don't use kill -SEGV as that will often invoke a signal handler making it harder to diagnose the stuck process

‘ant’ is not recognized as an internal or external command

When Environment variables are changed log off and log in again so that it will be applied.

Python - Extracting and Saving Video Frames

The previous answers have lost the first frame. And it will be nice to store the images in a folder.

# create a folder to store extracted images
import os
folder = 'test'  
os.mkdir(folder)
# use opencv to do the job
import cv2
print(cv2.__version__)  # my version is 3.1.0
vidcap = cv2.VideoCapture('test_video.mp4')
count = 0
while True:
    success,image = vidcap.read()
    if not success:
        break
    cv2.imwrite(os.path.join(folder,"frame{:d}.jpg".format(count)), image)     # save frame as JPEG file
    count += 1
print("{} images are extacted in {}.".format(count,folder))

By the way, you can check the frame rate by VLC. Go to windows -> media information -> codec details

CSS 3 slide-in from left transition

I liked @mate64's answer so I am going to reuse that with slight modifications to create a slide down and up animations below:

_x000D_
_x000D_
var $slider = document.getElementById('slider');_x000D_
var $toggle = document.getElementById('toggle');_x000D_
_x000D_
$toggle.addEventListener('click', function() {_x000D_
    var isOpen = $slider.classList.contains('slide-in');_x000D_
_x000D_
    $slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');_x000D_
});
_x000D_
#slider {_x000D_
    position: absolute;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background: blue;_x000D_
    transform: translateY(-100%);_x000D_
    -webkit-transform: translateY(-100%);_x000D_
}_x000D_
_x000D_
.slide-in {_x000D_
    animation: slide-in 0.5s forwards;_x000D_
    -webkit-animation: slide-in 0.5s forwards;_x000D_
}_x000D_
_x000D_
.slide-out {_x000D_
    animation: slide-out 0.5s forwards;_x000D_
    -webkit-animation: slide-out 0.5s forwards;_x000D_
}_x000D_
    _x000D_
@keyframes slide-in {_x000D_
    100% { transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-in {_x000D_
    100% { -webkit-transform: translateY(0%); }_x000D_
}_x000D_
    _x000D_
@keyframes slide-out {_x000D_
    0% { transform: translateY(0%); }_x000D_
    100% { transform: translateY(-100%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-out {_x000D_
    0% { -webkit-transform: translateY(0%); }_x000D_
    100% { -webkit-transform: translateY(-100%); }_x000D_
}
_x000D_
<div id="slider" class="slide-in">_x000D_
    <ul>_x000D_
        <li>Lorem</li>_x000D_
        <li>Ipsum</li>_x000D_
        <li>Dolor</li>_x000D_
    </ul>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
_x000D_
_x000D_

How do I disable and re-enable a button in with javascript?

true and false are not meant to be strings in this context.

You want the literal true and false Boolean values.

startButton.disabled = true;

startButton.disabled = false;

The reason it sort of works (disables the element) is because a non empty string is truthy. So assigning 'false' to the disabled property has the same effect of setting it to true.

How do I set the eclipse.ini -vm option?

I know that there exists a command line option, -vm, to specify the path to the executable of the Java runtime. This may be the same as in eclipse.ini.

jQuery: count number of rows in a table

I found this to work really well if you want to count rows without counting the th and any rows from tables inside of tables:

var rowCount = $("#tableData > tbody").children().length;

Pycharm does not show plot

With me the problem was the fact that matplotlib was using the wrong backend. I am using Debian Jessie.

In a console I did the following:

import matplotlib
matplotlib.get_backend()

The result was: 'agg', while this should be 'TkAgg'.

The solution was simple:

  1. Uninstall matplotlib via pip
  2. Install the appropriate libraries: sudo apt-get install tcl-dev tk-dev python-tk python3-tk
  3. Install matplotlib via pip again.

How to normalize a NumPy array to within a certain range?

You are trying to min-max scale the values of audio between -1 and +1 and image between 0 and 255.

Using sklearn.preprocessing.minmax_scale, should easily solve your problem.

e.g.:

audio_scaled = minmax_scale(audio, feature_range=(-1,1))

and

shape = image.shape
image_scaled = minmax_scale(image.ravel(), feature_range=(0,255)).reshape(shape)

note: Not to be confused with the operation that scales the norm (length) of a vector to a certain value (usually 1), which is also commonly referred to as normalization.

Bootstrap 4 Change Hamburger Toggler Color

If you downloaded bootstrap, go to bootstrap-4.4.1-dist/css/bootstrap.min.css

  1. find the .navbar-light .navbar-toggler-icon or the .navbar-dark .navbar-toggler-icon selector

  2. select the background-image attribute and its value. The snippet looks like this:

    .navbar-light .navbar-toggler-icon {
         background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
    }
    
  3. copy the snippet and paste it in your custom CSS

  4. change the stroke='rgba(0, 0, 0, 0.5)' value to your preferred rgba value

$_SERVER['HTTP_REFERER'] missing

From the documentation:

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

http://php.net/manual/en/reserved.variables.server.php

How to get the containing form of an input?

This example of a Javascript function is called by an event listener to identify the form

function submitUpdate(event) {
    trigger_field = document.getElementById(event.target.id);
    trigger_form = trigger_field.form;

Laravel 5 Carbon format datetime

Try that:

$createdAt = Carbon::parse(date_format($item['created_at'],'d/m/Y H:i:s');
$createdAt= $createdAt->format('M d Y');

Error while sending QUERY packet

If inserting 'too much data' fails due to the max_allowed_packet setting of the database server, the following warning is raised:

SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 
'max_allowed_packet' bytes

If this warning is catched as exception (due to the set error handler), the database connection is (probably) lost but the application doesn't know about this (failing inserts can have several causes). The next query in line, which can be as simple as:

SELECT 1 FROM DUAL

Will then fail with the error this SO-question started:

Error while sending QUERY packet. PID=18486

Simple test script to reproduce my explanation, try it with and without the error handler to see the difference in impact:

set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    // error was suppressed with the @-operator
    if (0 === error_reporting()) {
        return false;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

try
{
    // $oDb is instance of PDO
    var_dump($oDb->query('SELECT 1 FROM DUAL'));

    $oStatement = $oDb->prepare('INSERT INTO `test` (`id`, `message`) VALUES (NULL, :message);');
    $oStatement->bindParam(':message', $largetext, PDO::PARAM_STR);
    var_dump($oStatement->execute());
}
catch(Exception $e)
{
    $e->getMessage();
}
var_dump($oDb->query('SELECT 2 FROM DUAL'));

Set a cookie to never expire

All cookies expire as per the cookie specification, so this is not a PHP limitation.

Use a far future date. For example, set a cookie that expires in ten years:

setcookie(
  "CookieName",
  "CookieValue",
  time() + (10 * 365 * 24 * 60 * 60)
);

Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.

Convert form data to JavaScript object with jQuery

You can do this:

var frm = $(document.myform);
var data = JSON.stringify(frm.serializeArray());

See JSON.

Append integer to beginning of list in Python

Note that if you are trying to do that operation often, especially in loops, a list is the wrong data structure.

Lists are not optimized for modifications at the front, and somelist.insert(0, something) is an O(n) operation.

somelist.pop(0) and del somelist[0] are also O(n) operations.

The correct data structure to use is a deque from the collections module. deques expose an interface that is similar to those of lists, but are optimized for modifications from both endpoints. They have an appendleft method for insertions at the front.

Demo:

In [1]: lst = [0]*1000
In [2]: timeit -n1000 lst.insert(0, 1)
1000 loops, best of 3: 794 ns per loop
In [3]: from collections import deque
In [4]: deq = deque([0]*1000)
In [5]: timeit -n1000 deq.appendleft(1)
1000 loops, best of 3: 73 ns per loop

how to include js file in php?

Its more likely that the path to file.js from the page is what is wrong. as long as when you view the page, and view-source you see the tag, its working, now its time to debug whether or not your path is too relative, maybe you need a / in front of it.

The condition has length > 1 and only the first element will be used

You get the error because if can only evaluate a logical vector of length 1.

Maybe you miss the difference between & (|) and && (||). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:

c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE

# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE

You don't need the if statement at all:

mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"

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

Differences

  • KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.

  • UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.

    Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.

  • PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.

    Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.

  • FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).

    Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.

Similarities

  • All of these indexes may have more than one column in them.

  • With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)

How to create an Array with AngularJS's ng-model

It works fine for me: http://jsfiddle.net/qwertynl/htb9h/

My javascript:

var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
    $scope.telephone = []; // << remember to set this
}]);

How to pass command line argument to gnuplot?

@vagoberto's answer seems the best IMHO if you need positional arguments, and I have a small improvement to add.

vagoberto's suggestion:

#!/usr/local/bin/gnuplot --persist

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD 
print "number of arguments: ", ARGC 

which gets called by:

$ gnuplot -c script.gp one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

for those lazy typers like myself, one could make the script executable (chmod 755 script.gp)

then use the following:

#!/usr/bin/env gnuplot -c

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD
print "number of arguments: ", ARGC

and execute it as:

$ ./imb.plot a b c d
script name        : ./imb.plot
first argument     : a
third argument     : c
number of arguments: 4

Media query to detect if device is touchscreen

In 2017, CSS media query from second answer still doesn't work on Firefox. I found a soluton for that: -moz-touch-enabled


So, here is cross-browser media query:

@media (-moz-touch-enabled: 1), (pointer:coarse) {
    .something {
        its: working;
    }
}

Is there any way to call a function periodically in JavaScript?

yes - take a look at setInterval and setTimeout for executing code at certain times. setInterval would be the one to use to execute code periodically.

See a demo and answer here for usage

isset() and empty() - what to use

In your particular case: if ($var).

You need to use isset if you don't know whether the variable exists or not. Since you declared it on the very first line though, you know it exists, hence you don't need to, nay, should not use isset.

The same goes for empty, only that empty also combines a check for the truthiness of the value. empty is equivalent to !isset($var) || !$var and !empty is equivalent to isset($var) && $var, or isset($var) && $var == true.

If you only want to test a variable that should exist for truthiness, if ($var) is perfectly adequate and to the point.

Reverse the ordering of words in a string

I did solve the problem without using extra space used only the original string itself, but I couldn't solve the problem in O(n), the least I could get is O(n square) that's for the worst case scenario.

The way how I implemented -

  1. Reverse the whole sentence, char by char.
  2. Later iterate the whole sentence but this time reverse each word.

AND THAT'S WHY I GOT THE WORST TIME COMPLEXITY AS O(n sqaure)

Please find the code below in java, hope it helps someone.

class MainClass {
    public static void main(String args[]) {

        String str = "reverse me! also lets check";
        System.out.println("The initial string is  --->> " + str);

        for (int i = 0; i < str.length(); i++) {
            //Keep iterating each letter from one end to another.
            str = str.substring(1, str.length() - i)
                + str.substring(0, 1)
                + str.substring(str.length() - i, str.length());
        }
        System.out.println("The reversed string is ---->> " + str);

        for (int i = 0, j = 0; i < str.length(); i++) {
            if(str.charAt(i) == ' ' || i == (str.length() - 1)) {
                //Just to know the start of each word
                int k = j;

                //the below if condition is for considering the last word.
                if(i == (str.length() - 1)) i++;

                while(j < i) {
                    j++;
                    str = str.substring(0, k)
                        //(i-j) is the length of each word
                        + str.substring(k + 1, (k + 1) + i - j)
                        + str.substring(k, k + 1)
                        + str.substring((k + 1) + i - j, i)
                        + str.substring(i);
                    if(j == i) {
                        //Extra j++ for considering the empty white space
                        j++;
                    }
                }
            }
        }
        System.out.println("The reversed string but not the reversed words is ---->> " + str);

    }
}

How do I find the current machine's full hostname in C (hostname and domain information)?

My solution:

#ifdef WIN32
    #include <Windows.h>
    #include <tchar.h>
#else
    #include <unistd.h>
#endif

void GetMachineName(char machineName[150])
{
    char Name[150];
    int i=0;

    #ifdef WIN32
        TCHAR infoBuf[150];
        DWORD bufCharCount = 150;
        memset(Name, 0, 150);
        if( GetComputerName( infoBuf, &bufCharCount ) )
        {
            for(i=0; i<150; i++)
            {
                Name[i] = infoBuf[i];
            }
        }
        else
        {
            strcpy(Name, "Unknown_Host_Name");
        }
    #else
        memset(Name, 0, 150);
        gethostname(Name, 150);
    #endif
    strncpy(machineName,Name, 150);
}

How do I add target="_blank" to a link within a specified div?

Bear in mind that doing this is considered bad practice in general by web developers and usability experts. Jakob Nielson has this to say about removing control of the users browsing experience:

Avoid spawning multiple browser windows if at all possible — taking the "Back" button away from users can make their experience so painful that it usually far outweighs whatever benefit you're trying to provide. One common theory in favor of spawning the second window is that it keeps users from leaving your site, but ironically it may have just the opposite effect by preventing them from returning when they want to.

I believe this is the rationale for the target attribute being removed by the W3C from the XHTML 1.1 spec.

If you're dead set on taking this approach, Pim Jager's solution is good.

A nicer, more user friendly idea, would be to append a graphic to all of your external links, indicating to the user that following the link will take them externally.

You could do this with jquery:

$('a[href^="http://"]').each(function() {
    $('<img width="10px" height="10px" src="/images/skin/external.png" alt="External Link" />').appendTo(this)

});

Difference between ref and out parameters in .NET

They are subtly different.

An out parameter does not need to be initialized by the callee before being passed to the method. Therefore, any method with an out parameter

  • Cannot read the parameter before assigning a value to it
  • Must assign a value to it before returning

This is used for a method which needs to overwrite its argument regardless of its previous value.


A ref parameter must be initialized by the callee before passing it to the method. Therefore, any method with a ref parameter

  • Can inspect the value before assigning it
  • Can return the original value, untouched

This is used for a method which must (e.g.) inspect its value and validate it or normalize it.

Socket.IO handling disconnect event

You can also, if you like use socket id to manage your player list like this.

io.on('connection', function(socket){
  socket.on('disconnect', function() {
    console.log("disconnect")
    for(var i = 0; i < onlineplayers.length; i++ ){
      if(onlineplayers[i].socket === socket.id){
        console.log(onlineplayers[i].code + " just disconnected")
        onlineplayers.splice(i, 1)
      }
    }
    io.emit('players', onlineplayers)
  })

  socket.on('lobby_join', function(player) {
    if(player.available === false) return
    var exists = false
    for(var i = 0; i < onlineplayers.length; i++ ){
      if(onlineplayers[i].code === player.code){
        exists = true
      }
    }
    if(exists === false){
      onlineplayers.push({
        code: player.code,
        socket:socket.id
      })
    }
    io.emit('players', onlineplayers)
  })

  socket.on('lobby_leave', function(player) {
    var exists = false
    for(var i = 0; i < onlineplayers.length; i++ ){
      if(onlineplayers[i].code === player.code){
        onlineplayers.splice(i, 1)
      }
    }
    io.emit('players', onlineplayers)
  })
})

How to remove an HTML element using Javascript?

Try running this code in your script.

document.getElementById("dummy").remove();

And it will hopefully remove the element/button.

How do you perform address validation?

NAICS.com is coming out with an API that will add all kinds of key business data including street address. This would happen on the fly as your site's forms are processed. https://www.naics.com/business-intelligence-api/

Emulate a 403 error page

.htaccess

ErrorDocument 403     /403.html

There can be only one auto column

My MySQL says "Incorrect table definition; there can be only one auto column and it must be defined as a key" So when I added primary key as below it started working:

CREATE TABLE book (
   id INT AUTO_INCREMENT NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL,
   primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

MySQL Install: ERROR: Failed to build gem native extension

yum -y install gcc mysql-devel ruby-devel rubygems
gem install mysql2

How to convert list data into json in java

Using gson it is much simpler. Use following code snippet:

 // create a new Gson instance
 Gson gson = new Gson();
 // convert your list to json
 String jsonCartList = gson.toJson(cartList);
 // print your generated json
 System.out.println("jsonCartList: " + jsonCartList);

Converting back from JSON string to your Java object

 // Converts JSON string into a List of Product object
 Type type = new TypeToken<List<Product>>(){}.getType();
 List<Product> prodList = gson.fromJson(jsonCartList, type);

 // print your List<Product>
 System.out.println("prodList: " + prodList);

What is the best place for storing uploaded images, SQL database or disk file system?

Well, I have a similar project where users upload files onto the server. Under my point of view, option a) is the best solution due to it's more flexible. What you must do is storing images in a protected folder classified by subdirectories. The main directory must be set up by the administrator as the content must no run scripts (very important) and (read, write) protected for not be accesible in http request.

I hope this helps you.

Valid to use <a> (anchor tag) without href attribute?

It is valid. You can, for example, use it to show modals (or similar things that respond to data-toggle and data-target attributes).

Something like:

<a role="button" data-toggle="modal" data-target=".bs-example-modal-sm" aria-hidden="true"><i class="fa fa-phone"></i></a>

Here I use the font-awesome icon, which is better as a a tag rather than a button, to show a modal. Also, setting role="button" makes the pointer change to an action type. Without either href or role="button", the cursor pointer does not change.

How to list processes attached to a shared memory segment in linux?

Just in case someone is interest only in what kind of process created the shared moeries, call

ls -l /dev/shm

It lists the names that are associated with the shared memories - at least on Ubuntu. Usually the names are quite telling.

PostgreSQL visual interface similar to phpMyAdmin?

I would also highly recommend Adminer - http://www.adminer.org/

It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.

How could I put a border on my grid control in WPF?

I think your problem is that the margin should be specified in the border tag and not in the grid.

JavaScript ES6 promise for loop

If you are limited to ES6, the best option is Promise all. Promise.all(array) also returns an array of promises after successfully executing all the promises in array argument. Suppose, if you want to update many student records in the database, the following code demonstrates the concept of Promise.all in such case-

let promises = students.map((student, index) => {
//where students is a db object
student.rollNo = index + 1;
student.city = 'City Name';
//Update whatever information on student you want
return student.save();
});
Promise.all(promises).then(() => {
  //All the save queries will be executed when .then is executed
  //You can do further operations here after as all update operations are completed now
});

Map is just an example method for loop. You can also use for or forin or forEach loop. So the concept is pretty simple, start the loop in which you want to do bulk async operations. Push every such async operation statement in an array declared outside the scope of that loop. After the loop completes, execute the Promise all statement with the prepared array of such queries/promises as argument.

The basic concept is that the javascript loop is synchronous whereas database call is async and we use push method in loop that is also sync. So, the problem of asynchronous behavior doesn't occur inside the loop.

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

How to create jar file with package structure?

You want

$ jar cvf asd.jar .

to specify the directory (e.g. .) to jar from. That will maintain your folder structure within the jar file.

How do I add comments to package.json for npm install?

After wasting an hour on complex and hacky solutions, I've found both simple and valid solution for commenting my bulky dependencies section in package.json. Just like this:

{
  "name": "package name",
  "version": "1.0",
  "description": "package description",
  "scripts": {
    "start": "npm install && node server.js"
  },
  "scriptsComments": {
    "start": "Runs development build on a local server configured by server.js"
  },
  "dependencies": {
    "ajv": "^5.2.2"
  },
  "dependenciesComments": {
    "ajv": "JSON-Schema Validator for validation of API data"
  }
}

When sorted the same way, it's now very easy for me to track these pairs of dependencies/comments either in Git commit diffs or in an editor while working with file package.json.

And no extra tools are involved, just plain and valid JSON.

Sum values in a column based on date

Add a column to your existing data to get rid of the hour:minute:second time stamp on each row:

 =DATE(YEAR(A1), MONTH(A1), DAY(A1))

Extend this down the length of your data. Even easier: quit collecting the hh:mm:ss data if you don't need it. Assuming your date/time was in column A, and your value was in column B, you'd put the above formula in column C, and auto-extend it for all your data.

Now, in another column (let's say E), create a series of dates corresponding to each day of the specific month you're interested in. Just type the first date, (for example, 10/7/2016 in E1), and auto-extend. Then, in the cell next to the first date, F1, enter:

=SUMIF(C:C, E1, B:B )

autoextend the formula to cover every date in the month, and you're done. Begin at 1/1/2016, and auto-extend for the whole year if you like.

Checking the equality of two slices

And for now, here is https://github.com/google/go-cmp which

is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal.

package main

import (
    "fmt"

    "github.com/google/go-cmp/cmp"
)

func main() {
    a := []byte{1, 2, 3}
    b := []byte{1, 2, 3}

    fmt.Println(cmp.Equal(a, b)) // true
}

Is the Javascript date object always one day off?

This probably is not a good answer, but i just want to share my experience with this issue.

My app is globally use utc date with the format 'YYYY-MM-DD', while the datepicker plugin i use only accept js date, it's hard for me to consider both utc and js. So when i want to pass a 'YYYY-MM-DD' formatted date to my datepicker, i first convert it to 'MM/DD/YYYY' format using moment.js or whatever you like, and the date shows on datepicker is now correct. For your example

var d = new Date('2011-09-24'); // d will be 'Fri Sep 23 2011 20:00:00 GMT-0400 (EDT)' for my lacale
var d1 = new Date('09/24/2011'); // d1 will be 'Sat Sep 24 2011 00:00:00 GMT-0400 (EDT)' for my lacale

Apparently d1 is what i want. Hope this would be helpful for some people.

Identify if a string is a number

You can also use:

stringTest.All(char.IsDigit);

It will return true for all Numeric Digits (not float) and false if input string is any sort of alphanumeric.

Please note: stringTest should not be an empty string as this would pass the test of being numeric.

onclick open window and specific size

window.open('http://somelocation.com','mywin','width=500,height=500');

How do I connect to a MySQL Database in Python?

Also take a look at Storm. It is a simple SQL mapping tool which allows you to easily edit and create SQL entries without writing the queries.

Here is a simple example:

from storm.locals import *

# User will be the mapped object; you have to create the table before mapping it
class User(object):
        __storm_table__ = "user" # table name
        ID = Int(primary=True) #field ID
        name= Unicode() # field name

database = create_database("mysql://root:password@localhost:3306/databaseName")
store = Store(database)

user = User()
user.name = u"Mark"

print str(user.ID) # None

store.add(user)  
store.flush() # ID is AUTO_INCREMENT

print str(user.ID) # 1 (ID)

store.commit() # commit all changes to the database

To find and object use:

michael = store.find(User, User.name == u"Michael").one()
print str(user.ID) # 10

Find with primary key:

print store.get(User, 1).name #Mark

For further information see the tutorial.

Is there a "do ... while" loop in Ruby?

Here's another one:

people = []
1.times do
  info = gets.chomp
  unless info.empty? 
    people += [Person.new(info)]
    redo
  end
end

Keyword not supported: "data source" initializing Entity Framework Context

This appears to be missing the providerName="System.Data.EntityClient" bit. Sure you got the whole thing?

Get value from hashmap based on key to JSTL

if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:

<c:out value="${map['key']}"/>

where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Spring Data JPA Update @Query not updating?

The underlying problem here is the 1st level cache of JPA. From the JPA spec Version 2.2 section 3.1. emphasise is mine:

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance.

This is important because JPA tracks changes to that entity in order to flush them to the database. As a side effect it also means within a single persistence context an entity gets only loaded once. This why reloading the changed entity doesn't have any effect.

You have a couple of options how to handle this:

  1. Evict the entity from the EntityManager. This may be done by calling EntityManager.detach, annotating the updating method with @Modifying(clearAutomatically = true) which evicts all entities. Make sure changes to these entities get flushed first or you might end up loosing changes.

  2. Use EntityManager.refresh().

  3. Use a different persistence context to load the entity. The easiest way to do this is to do it in a separate transaction. With Spring this can be done by having separate methods annotated with @Transactional on beans called from a bean not annotated with @Transactional. Another way is to use a TransactionTemplate which works especially nicely in tests where it makes transaction boundaries very visible.

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

How do I set a JLabel's background color?

The JLabel background is transparent by default. Set the opacity at true like that:

label.setOpaque(true);

How to add multiple classes to a ReactJS Component?

clsx makes this simple!

"The clsx function can take any number of arguments, each of which can be an Object, Array, Boolean, or String."

-- clsx docs on npmjs.com

Import it:

import clsx from 'clsx'

Use it:

<li key={index} className={clsx(activeClass, data.class, "main-class")}></li>

npm install won't install devDependencies

So the way I got around this was in the command where i would normally run npm install or npm ci, i added NODE_ENV=build, and then NODE_ENV=production after the command, so my entire command came out to:

RUN NODE_ENV=build && npm ci && NODE_ENV=production

So far I haven't had any bad reactions, and my development dependencies which are used for building the application all worked / loaded correctly.

I find this to be a better solution than adding an additional command like npm install --only=dev because it takes less time, and enables me to use the npm ci command, which is faster and specifically designed to be run inside CI tools / build scripts. (See npi-ci documentation for more information on it)

How to get unique values in an array

If you want to leave the original array intact,

you need a second array to contain the uniqe elements of the first-

Most browsers have Array.prototype.filter:

var unique= array1.filter(function(itm, i){
    return array1.indexOf(itm)== i; 
    // returns true for only the first instance of itm
});


//if you need a 'shim':
Array.prototype.filter= Array.prototype.filter || function(fun, scope){
    var T= this, A= [], i= 0, itm, L= T.length;
    if(typeof fun== 'function'){
        while(i<L){
            if(i in T){
                itm= T[i];
                if(fun.call(scope, itm, i, T)) A[A.length]= itm;
            }
            ++i;
        }
    }
    return A;
}
 Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
        if(!i || typeof i!= 'number') i= 0;
        var L= this.length;
        while(i<L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

Simple Solution

If you are working with pure html/js/css files.

Install this small server(link) app in chrome. Open the app and point the file location to your project directory.

Goto the url shown in the app.

Edit: Smarter solution using Gulp

Step 1: To install Gulp. Run following command in your terminal.

npm install gulp-cli -g
npm install gulp -D

Step 2: Inside your project directory create a file named gulpfile.js. Copy the following content inside it.

var gulp        = require('gulp');
var bs          = require('browser-sync').create();   

gulp.task('serve', [], () => {
        bs.init({
            server: {
               baseDir: "./",
            },
            port: 5000,
            reloadOnRestart: true,
            browser: "google chrome"
        });
        gulp.watch('./**/*', ['', bs.reload]);
});

Step 3: Install browser sync gulp plugin. Inside the same directory where gulpfile.js is present, run the following command

npm install browser-sync gulp --save-dev

Step 4: Start the server. Inside the same directory where gulpfile.js is present, run the following command

gulp serve

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

In SQL Server, how to create while loop in select

You Could do something like this .....
Your Table

CREATE TABLE TestTable 
(
ID INT,
Data NVARCHAR(50)
)
GO

INSERT INTO TestTable
VALUES (1,'AABBCC'),
       (2,'FFDD'),
       (3,'TTHHJJKKLL')
GO

SELECT * FROM TestTable

My Suggestion

CREATE TABLE #DestinationTable
(
ID INT,
Data NVARCHAR(50)
)
GO  
    SELECT * INTO #Temp FROM TestTable

    DECLARE @String NVARCHAR(2)
    DECLARE @Data NVARCHAR(50)
    DECLARE @ID INT

    WHILE EXISTS (SELECT * FROM #Temp)
     BEGIN 
        SELECT TOP 1 @Data =  DATA, @ID = ID FROM  #Temp

          WHILE LEN(@Data) > 0
            BEGIN
                SET @String = LEFT(@Data, 2)

                INSERT INTO #DestinationTable (ID, Data)
                VALUES (@ID, @String)

                SET @Data = RIGHT(@Data, LEN(@Data) -2)
            END
        DELETE FROM #Temp WHERE ID = @ID
     END


SELECT * FROM #DestinationTable

Result Set

ID  Data
1   AA
1   BB
1   CC
2   FF
2   DD
3   TT
3   HH
3   JJ
3   KK
3   LL

DROP Temp Tables

DROP TABLE #Temp
DROP TABLE #DestinationTable

Drop data frame columns by name

Beyond select(-one_of(drop_col_names)) demonstrated in earlier answers, there are a couple other dplyr options for dropping columns using select() that do not involve defining all the specific column names (using the dplyr starwars sample data for some variety in column names):

library(dplyr)
starwars %>% 
  select(-(name:mass)) %>%        # the range of columns from 'name' to 'mass'
  select(-contains('color')) %>%  # any column name that contains 'color'
  select(-starts_with('bi')) %>%  # any column name that starts with 'bi'
  select(-ends_with('er')) %>%    # any column name that ends with 'er'
  select(-matches('^f.+s$')) %>%  # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%     # not by column name but by data type
  head(2)

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>  
1 Tatooine  Human  
2 Tatooine  Droid 

If you need to drop a column that may or may not exist in the data frame, here's a slight twist using select_if() that unlike using one_of() will not throw an Unknown columns: warning if the column name does not exist. In this example 'bad_column' is not a column in the data frame:

starwars %>% 
  select_if(!names(.) %in% c('height', 'mass', 'bad_column'))