Programs & Examples On #Sed

Sed (Stream EDitor) is a command line editor for POSIX environment. Sed processes one or more files according to an editing script and writes the results to standard output. Created at Bell Labs, it has been around since the mid-70s.

Replace whole line containing a string using Sed

All of the answers provided so far assume that you know something about the text to be replaced which makes sense, since that's what the OP asked. I'm providing an answer that assumes you know nothing about the text to be replaced and that there may be a separate line in the file with the same or similar content that you do not want to be replaced. Furthermore, I'm assuming you know the line number of the line to be replaced.

The following examples demonstrate the removing or changing of text by specific line numbers:

# replace line 17 with some replacement text and make changes in file (-i switch)
# the "-i" switch indicates that we want to change the file. Leave it out if you'd
#   just like to see the potential changes output to the terminal window.
# "17s" indicates that we're searching line 17
# ".*" indicates that we want to change the text of the entire line
# "REPLACEMENT-TEXT" is the new text to put on that line
# "PATH-TO-FILE" tells us what file to operate on
sed -i '17s/.*/REPLACEMENT-TEXT/' PATH-TO-FILE

# replace specific text on line 3
sed -i '3s/TEXT-TO-REPLACE/REPLACEMENT-TEXT/'

Change multiple files

If you are able to run a script, here is what I did for a similar situation:

Using a dictionary/hashMap (associative array) and variables for the sed command, we can loop through the array to replace several strings. Including a wildcard in the name_pattern will allow to replace in-place in files with a pattern (this could be something like name_pattern='File*.txt' ) in a specific directory (source_dir). All the changes are written in the logfile in the destin_dir

#!/bin/bash
source_dir=source_path
destin_dir=destin_path
logfile='sedOutput.txt'
name_pattern='File.txt'

echo "--Begin $(date)--" | tee -a $destin_dir/$logfile
echo "Source_DIR=$source_dir destin_DIR=$destin_dir "

declare -A pairs=( 
    ['WHAT1']='FOR1'
    ['OTHER_string_to replace']='string replaced'
)

for i in "${!pairs[@]}"; do
    j=${pairs[$i]}
    echo "[$i]=$j"
    replace_what=$i
    replace_for=$j
    echo " "
    echo "Replace: $replace_what for: $replace_for"
    find $source_dir -name $name_pattern | xargs sed -i "s/$replace_what/$replace_for/g" 
    find $source_dir -name $name_pattern | xargs -I{} grep -n "$replace_for" {} /dev/null | tee -a $destin_dir/$logfile
done

echo " "
echo "----End $(date)---" | tee -a $destin_dir/$logfile

First, the pairs array is declared, each pair is a replacement string, then WHAT1 will be replaced for FOR1 and OTHER_string_to replace will be replaced for string replaced in the file File.txt. In the loop the array is read, the first member of the pair is retrieved as replace_what=$i and the second as replace_for=$j. The find command searches in the directory the filename (that may contain a wildcard) and the sed -i command replaces in the same file(s) what was previously defined. Finally I added a grep redirected to the logfile to log the changes made in the file(s).

This worked for me in GNU Bash 4.3 sed 4.2.2 and based upon VasyaNovikov's answer for Loop over tuples in bash.

Why is sed not recognizing \t as a tab?

You don't need to use sed to do a substitution when in actual fact, you just want to insert a tab in front of the line. Substitution for this case is an expensive operation as compared to just printing it out, especially when you are working with big files. Its easier to read too as its not regex.

eg using awk

awk '{print "\t"$0}' $filename > temp && mv temp $filename

sed whole word search and replace

$ echo "bar embarassment"|awk '{for(o=1;o<=NF;o++)if($o=="bar")$o="no bar"}1'
no bar embarassment

How to output only captured groups with sed?

Give up and use Perl

Since sed does not cut it, let's just throw the towel and use Perl, at least it is LSB while grep GNU extensions are not :-)

  • Print the entire matching part, no matching groups or lookbehind needed:

    cat <<EOS | perl -lane 'print m/\d+/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    12
    3456
    
  • Single match per line, often structured data fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*/$1/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    1
    34
    

    With lookbehind:

    cat <<EOS | perl -lane 'print m/(?<=a)(\d+)/'
    a1 b2
    a34 b56
    EOS
    
  • Multiple fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*?b(\d+).*/$1 $2/g'
    a1 c0 b2 c0
    a34 c0 b56 c0
    EOS
    

    Output:

    1 2
    34 56
    
  • Multiple matches per line, often unstructured data:

    cat <<EOS | perl -lape 's/.*?a(\d+)|.*/$1 /g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1 
    34 78
    

    With lookbehind:

    cat EOS<< | perl -lane 'print m/(?<=a)(\d+)/g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1
    3478
    

Find and replace in file and overwrite file doesn't work, it empties the file

sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' index.html

This does a global in-place substitution on the file index.html. Quoting the string prevents problems with whitespace in the query and replacement.

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

How to cut a string after a specific character in unix

You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:

Parameter Expansion

...

${parameter#word}

Remove Smallest Prefix Pattern.
The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted.

In other words, you can write

$var="${var#*:}"

which will remove anything matching *: from $var (i.e. everything up to and including the first :). If you want to match up to the last :, then you could use ## in place of #.

This is all assuming that the part to remove does not contain : (true for IPv4 addresses, but not for IPv6 addresses)

Shell script : How to cut part of a string

$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10

Add text at the end of each line

Concise version of the sed command:

sed -i s/$/:80/ file.txt

Explanation:

  • sed stream editor
    • -i in-place (edit file in place)
    • s substitution command
    • /replacement_from_reg_exp/replacement_to_text/ statement
    • $ matches the end of line (replacement_from_reg_exp)
    • :80 text you want to add at the end of every line (replacement_to_text)
  • file.txt the file name

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

Insert line after first match using sed

A POSIX compliant one using the s command:

sed '/CLIENTSCRIPT="foo"/s/.*/&\
CLIENTSCRIPT2="hello"/' file

How to find and replace all occurrences of a string recursively in a directory tree?

For me works the next command:

find /path/to/dir -name "file.txt" | xargs sed -i 's/string_to_replace/new_string/g'

if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.

For example: 's@string/to/replace@new/string@g'

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

Using sed, how do you print the first 'N' characters of a line?

don't have to use grep either

an example:

sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file

Using sed, Insert a line above or below the pattern?

More portable to use ed; some systems don't support \n in sed

printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
    /bin/ed $filename

Replace a string in shell script using a variable

Not related to question but in case if someone is passing the string as an argument to bash script this might help.

Use:

./bash_script.sh "path\to\file"

Instead of:

./bash_script.sh path\to\file

For your reference.

Find and replace with sed in directory and sub directories

Since there are also macOS folks reading this one (as I did), the following code worked for me (on 10.14)

egrep -rl '<pattern>' <dir> | xargs -I@ sed -i '' 's/<arg1>/<arg2>/g' @

All other answers using -i and -e do not work on macOS.

Source

Use sed to replace all backslashes with forward slashes

I had to use [\\] or [/] to be able to make this work, FYI.

awk '!/[\\]/' file > temp && mv temp file

and

awk '!/[/]/' file > temp && mv temp file

I was using awk to remove backlashes and forward slashes from a list.

How to replace multiple patterns at once with sed?

If replacing the string by Variable, the solution doesn't work. The sed command need to be in double quotes instead on single quote.

#sed -e "s/#replacevarServiceName#/$varServiceName/g" -e "s/#replacevarImageTag#/$varImageTag/g" deployment.yaml

Retrieve last 100 lines logs

You can simply use the following command:-

tail -NUMBER_OF_LINES FILE_NAME

e.g tail -100 test.log

  • will fetch the last 100 lines from test.log

In case, if you want the output of the above in a separate file then you can pipes as follows:-

tail -NUMBER_OF_LINES FILE_NAME > OUTPUT_FILE_NAME

e.g tail -100 test.log > output.log

  • will fetch the last 100 lines from test.log and store them into a new file output.log)

How can I delete a newline if it is the last character in a file?

I had a similar problem, but was working with a windows file and need to keep those CRLF -- my solution on linux:

sed 's/\r//g' orig | awk '{if (NR>1) printf("\r\n"); printf("%s",$0)}' > tweaked

Find and Replace string in all files recursive using grep and sed

grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"

Is there any sed like utility for cmd.exe?

> (Get-content file.txt) | Foreach-Object {$_ -replace "^SourceRegexp$", "DestinationString"} | Set-Content file.txt

This is behaviour of

sed -i 's/^SourceRegexp$/DestinationString/g' file.txt

Extract XML Value in bash script

XMLStarlet or another XPath engine is the correct tool for this job.

For instance, with data.xml containing the following:

<root>
  <item> 
    <title>15:54:57 - George:</title>
    <description>Diane DeConn? You saw Diane DeConn!</description> 
  </item> 
  <item> 
    <title>15:55:17 - Jerry:</title> 
    <description>Something huh?</description>
  </item>
</root>

...you can extract only the first title with the following:

xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml

Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster &amp; Jobs to Brewster & Jobs), and so forth.

How to show only next line after the matched one?

grep /Pattern/ | tail -n 2 | head -n 1

Tail first 2 and then head last one to get exactly first line after match.

How to use sed to extract substring

sed 's/[^"]*"\([^"]*\).*/\1/'

does the job.

explanation of the part inside ' '

  • s - tells sed to substitute
  • / - start of regex string to search for
  • [^"]* - any character that is not ", any number of times. (matching parameter name=)
  • " - just a ".
  • ([^"]*) - anything inside () will be saved for reference to use later. The \ are there so the brackets are not considered as characters to search for. [^"]* means the same as above. (matching RemoteHost for example)
  • .* - any character, any number of times. (matching " access="readWrite"> /parameter)
  • / - end of the search regex, and start of the substitute string.
  • \1 - reference to that string we found in the brackets above.
  • / end of the substitute string.

basically s/search for this/replace with this/ but we're telling him to replace the whole line with just a piece of it we found earlier.

How to use sed/grep to extract text between two words?

If you have a long file with many multi-line ocurrences, it is useful to first print number lines:

cat -n file | sed -n '/Here/,/String/p'

Insert a line at specific line number with sed or awk

POSIX sed (and for example OS X's sed, the sed below) require i to be followed by a backslash and a newline. Also at least OS X's sed does not include a newline after the inserted text:

$ seq 3|gsed '2i1.5'
1
1.5
2
3
$ seq 3|sed '2i1.5'
sed: 1: "2i1.5": command i expects \ followed by text
$ seq 3|sed $'2i\\\n1.5'
1
1.52
3
$ seq 3|sed $'2i\\\n1.5\n'
1
1.5
2
3

To replace a line, you can use the c (change) or s (substitute) commands with a numeric address:

$ seq 3|sed $'2c\\\n1.5\n'
1
1.5
3
$ seq 3|gsed '2c1.5'
1
1.5
3
$ seq 3|sed '2s/.*/1.5/'
1
1.5
3

Alternatives using awk:

$ seq 3|awk 'NR==2{print 1.5}1'
1
1.5
2
3
$ seq 3|awk '{print NR==2?1.5:$0}'
1
1.5
3

awk interprets backslashes in variables passed with -v but not in variables passed using ENVIRON:

$ seq 3|awk -v v='a\ba' '{print NR==2?v:$0}'
1
a
3
$ seq 3|v='a\ba' awk '{print NR==2?ENVIRON["v"]:$0}'
1
a\ba
3

Both ENVIRON and -v are defined by POSIX.

How do I escape double and single quotes in sed?

You can use %

sed -i "s%http://www.fubar.com%URL_FUBAR%g"

Insert multiple lines into a file after specified pattern using shell script

sed '/^cdef$/r'<(
    echo "line1"
    echo "line2"
    echo "line3"
    echo "line4"
) -i -- input.txt

How to select lines between two marker patterns which may occur multiple times with awk/sed

Using sed:

sed -n -e '/^abc$/,/^mno$/{ /^abc$/d; /^mno$/d; p; }'

The -n option means do not print by default.

The pattern looks for lines containing just abc to just mno, and then executes the actions in the { ... }. The first action deletes the abc line; the second the mno line; and the p prints the remaining lines. You can relax the regexes as required. Any lines outside the range of abc..mno are simply not printed.

Command to get nth line of STDOUT

From sed1line:

# print line number 52
sed -n '52p'                 # method 1
sed '52!d'                   # method 2
sed '52q;d'                  # method 3, efficient on large files

From awk1line:

# print line number 52
awk 'NR==52'
awk 'NR==52 {print;exit}'          # more efficient on large files

sed: print only matching group

The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.

For instance: echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7

Will result in output of: 2 3.4

-d sets the delimiter

-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7.

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

How to do a recursive find/replace of a string with awk or sed?

All the tricks are almost the same, but I like this one:

find <mydir> -type f -exec sed -i 's/<string1>/<string2>/g' {} +
  • find <mydir>: look up in the directory.

  • -type f:

    File is of type: regular file

  • -exec command {} +:

    This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory.

Printing everything except the first field with awk

Assigning $1 works but it will leave a leading space: awk '{first = $1; $1 = ""; print $0, first; }'

You can also find the number of columns in NF and use that in a loop.

Replace all whitespace with a line break/paragraph mark to make a word list

All of the examples listed above for sed break on one platform or another. None of them work with the version of sed shipped on Macs.

However, Perl's regex works the same on any machine with Perl installed:

perl -pe 's/\s+/\n/g' file.txt

If you want to save the output:

perl -pe 's/\s+/\n/g' file.txt > newfile.txt

If you want only unique occurrences of words:

perl -pe 's/\s+/\n/g' file.txt | sort -u > newfile.txt

In Bash, how do I add a string after each line in a file?

  1. Pure POSIX shell and sponge:

    suffix=foobar
    while read l ; do printf '%s\n' "$l" "${suffix}" ; done < file | 
    sponge file
    
  2. xargs and printf:

    suffix=foobar
    xargs -L 1 printf "%s${suffix}\n" < file | sponge file
    
  3. Using join:

    suffix=foobar
    join file file -e "${suffix}" -o 1.1,2.99999 | sponge file
    
  4. Shell tools using paste, yes, head & wc:

    suffix=foobar
    paste file <(yes "${suffix}" | head -$(wc -l < file) ) | sponge file
    

    Note that paste inserts a Tab char before $suffix.

Of course sponge can be replaced with a temp file, afterwards mv'd over the original filename, as with some other answers...

How to merge every two lines into one from the command line?

A more-general solution (allows for more than one follow-up line to be joined) as a shell script. This adds a line between each, because I needed visibility, but that is easily remedied. This example is where the "key" line ended in : and no other lines did.

#!/bin/bash
#
# join "The rest of the story" when the first line of each   story
# matches $PATTERN
# Nice for looking for specific changes in bart output
#

PATTERN='*:';
LINEOUT=""
while read line; do
    case $line in
        $PATTERN)
                echo ""
                echo $LINEOUT
                LINEOUT="$line"
                        ;;
        "")
                LINEOUT=""
                echo ""
                ;;

        *)      LINEOUT="$LINEOUT $line"
                ;;
    esac        
done

How to insert a newline in front of a pattern?

You can use perl one-liners much like you do with sed, with the advantage of full perl regular expression support (which is much more powerful than what you get with sed). There is also very little variation across *nix platforms - perl is generally perl. So you can stop worrying about how to make your particular system's version of sed do what you want.

In this case, you can do

perl -pe 's/(regex)/\n$1/'

-pe puts perl into a "execute and print" loop, much like sed's normal mode of operation.

' quotes everything else so the shell won't interfere

() surrounding the regex is a grouping operator. $1 on the right side of the substitution prints out whatever was matched inside these parens.

Finally, \n is a newline.

Regardless of whether you are using parentheses as a grouping operator, you have to escape any parentheses you are trying to match. So a regex to match the pattern you list above would be something like

\(\d\d\d\)\d\d\d-\d\d\d\d

\( or \) matches a literal paren, and \d matches a digit.

Better:

\(\d{3}\)\d{3}-\d{4}

I imagine you can figure out what the numbers in braces are doing.

Additionally, you can use delimiters other than / for your regex. So if you need to match / you won't need to escape it. Either of the below is equivalent to the regex at the beginning of my answer. In theory you can substitute any character for the standard /'s.

perl -pe 's#(regex)#\n$1#'
perl -pe 's{(regex)}{\n$1}'

A couple final thoughts.

using -ne instead of -pe acts similarly, but doesn't automatically print at the end. It can be handy if you want to print on your own. E.g., here's a grep-alike (m/foobar/ is a regex match):

perl -ne 'if (m/foobar/) {print}'

If you are finding dealing with newlines troublesome, and you want it to be magically handled for you, add -l. Not useful for the OP, who was working with newlines, though.

Bonus tip - if you have the pcre package installed, it comes with pcregrep, which uses full perl-compatible regexes.

Delete specific line number(s) from a text file using sed?

You can delete a particular single line with its line number by

sed -i '33d' file

This will delete the line on 33 line number and save the updated file.

find difference between two text files with one item per line

if you are expecting them in a certain order, you can just use diff

diff file1 file2 | grep ">"

Replace comma with newline in sed on MacOS?

Though I am late to this post, just updating my findings. This answer is only for Mac OS X.

$ sed 's/new/
> /g' m1.json > m2.json
sed: 1: "s/new/
/g": unescaped newline inside substitute pattern

In the above command I tried with Shift+Enter to add new line which didn't work. So this time I tried with "escaping" the "unescaped newline" as told by the error.

$ sed 's/new/\
> /g' m1.json > m2.json 

Worked! (in Mac OS X 10.9.3)

How to replace space with comma using sed?

Inside vim, you want to type when in normal (command) mode:

:%s/ /,/g

On the terminal prompt, you can use sed to perform this on a file:

sed -i 's/\ /,/g' input_file

Note: the -i option to sed means "in-place edit", as in that it will modify the input file.

invalid command code ., despite escaping periods, using sed

If you are on a OS X, this probably has nothing to do with the sed command. On the OSX version of sed, the -i option expects an extension argument so your command is actually parsed as the extension argument and the file path is interpreted as the command code.

Try adding the -e argument explicitly and giving '' as argument to -i:

find ./ -type f -exec sed -i '' -e "s/192.168.20.1/new.domain.com/" {} \;

See this.

What is newline character -- '\n'

I think this post by Jeff Attwood addresses your question perfectly. It takes you through the differences between newlines on Dos, Mac and Unix, and then explains the history of CR (Carriage return) and LF (Line feed).

How can I strip first X characters from string using sed?

Cut first two characters from string:

$ string="1234567890"; echo "${string:2}"
34567890

Remove non-ASCII characters from CSV

I appreciate the tips I found on this site.

But, on my Windows 10, I had to use double quotes for this to work ...

sed -i "s/[\d128-\d255]//g" FILENAME

Noticed these things ...

  1. For FILENAME the entire path\name needs to be quoted This didn't work -- %TEMP%\"FILENAME" This did -- %TEMP%\FILENAME"

  2. sed leaves behind temp files in the current directory, named sed*

How to delete duplicate lines in a file without sorting it in Unix?

Perl one-liner similar to @jonas's awk solution:

perl -ne 'print if ! $x{$_}++' file

This variation removes trailing whitespace before comparing:

perl -lne 's/\s*$//; print if ! $x{$_}++' file

This variation edits the file in-place:

perl -i -ne 'print if ! $x{$_}++' file

This variation edits the file in-place, and makes a backup file.bak

perl -i.bak -ne 'print if ! $x{$_}++' file

Why does sed not replace all occurrences?

You should add the g modifier so that sed performs a global substitution of the contents of the pattern buffer:

echo dog dog dos | sed -e 's:dog:log:g'

For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6

The official documentation for GNU sed is available at http://www.gnu.org/software/sed/manual/

Ansible playbook shell output

ANSIBLE_STDOUT_CALLBACK=debug ansible-playbook /tmp/foo.yml -vvv

Tasks with STDOUT will then have a section:

STDOUT:

What ever was in STDOUT

Using sed to split a string with a delimiter

This might work for you (GNU sed):

sed 'y/:/\n/' file

or perhaps:

sed y/:/$"\n"/ file

Replacing from match to end-of-line

This should do what you want:

sed 's/two.*/BLAH/'

$ echo "   one  two  three  five
>    four two  five five six
>    six  one  two seven four" | sed 's/two.*/BLAH/'
   one  BLAH
   four BLAH
   six  one  BLAH

The $ is unnecessary because the .* will finish at the end of the line anyways, and the g at the end is unnecessary because your first match will be the first two to the end of the line.

Command line: search and replace in all filenames matched by grep

The answer already given of using find and sed

find -name '*.html' -print -exec sed -i.bak 's/foo/bar/g' {} \;

is probably the standard answer. Or you could use perl -pi -e s/foo/bar/g' instead of the sed command.

For most quick uses, you may find the command rpl is easier to remember. Here is replacement (foo -> bar), recursively on all files in the current directory:

rpl -R foo bar .

It's not available by default on most Linux distros but is quick to install (apt-get install rpl or similar).

However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:

  • Support renaming of files as well as search-and-replace on file contents (including moving files between directories and creating new parent directories).
  • See changes before you commit to performing the search and replace.
  • Support regular expressions with back substitution, whole words, case insensitive, and case preserving (replace foo -> bar, Foo -> Bar, FOO -> BAR) modes.
  • Works with multiple replacements, including swaps (foo -> bar and bar -> foo) or sets of non-unique replacements (foo -> bar, f -> x).

Check the README for examples.

How to extract string following a pattern with grep, regex or perl

If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.

Appending a line to a file only if it does not already exist

another sed solution is to always append it on the last line and delete a pre existing one.

sed -e '$a\' -e '<your-entry>' -e "/<your-entry-properly-escaped>/d"

"properly-escaped" means to put a regex that matches your entry, i.e. to escape all regex controls from your actual entry, i.e. to put a backslash in front of ^$/*?+().

this might fail on the last line of your file or if there's no dangling newline, I'm not sure, but that could be dealt with by some nifty branching...

How can I remove the first line of a text file using bash/sed script?

No, that's about as efficient as you're going to get. You could write a C program which could do the job a little faster (less startup time and processing arguments) but it will probably tend towards the same speed as sed as files get large (and I assume they're large if it's taking a minute).

But your question suffers from the same problem as so many others in that it pre-supposes the solution. If you were to tell us in detail what you're trying to do rather then how, we may be able to suggest a better option.

For example, if this is a file A that some other program B processes, one solution would be to not strip off the first line, but modify program B to process it differently.

Let's say all your programs append to this file A and program B currently reads and processes the first line before deleting it.

You could re-engineer program B so that it didn't try to delete the first line but maintains a persistent (probably file-based) offset into the file A so that, next time it runs, it could seek to that offset, process the line there, and update the offset.

Then, at a quiet time (midnight?), it could do special processing of file A to delete all lines currently processed and set the offset back to 0.

It will certainly be faster for a program to open and seek a file rather than open and rewrite. This discussion assumes you have control over program B, of course. I don't know if that's the case but there may be other possible solutions if you provide further information.

Non greedy (reluctant) regex matching in sed?

another way, not using regex, is to use fields/delimiter method eg

string="http://www.suepearson.co.uk/product/174/71/3816/"
echo $string | awk -F"/" '{print $1,$2,$3}' OFS="/"

Delete all lines beginning with a # from a file

you can directly edit your file with

sed -i '/^#/ d'

If you want also delete comment lines that start with some whitespace use

sed -i '/^\s*#/ d'

Usually, you want to keep the first line of your script, if it is a sha-bang, so sed should not delete lines starting with #!. also it should delete lines, that just contain only a hash but no text. put it all together:

sed -i '/^\s*\(#[^!].*\|#$\)/d'

To be conform with all sed variants you need to add a backup extension to the -i option:

sed -i.bak '/^\s*#/ d' $file
rm -Rf $file.bak

Delete the first five characters on any line of a text file in Linux with sed

sed 's/^.\{,5\}//' file.dat worked like a charm for me

Escape a string for a sed replace pattern

Here is an example of an AWK I used a while ago. It is an AWK that prints new AWKS. AWK and SED being similar it may be a good template.

ls | awk '{ print "awk " "'"'"'"  " {print $1,$2,$3} " "'"'"'"  " " $1 ".old_ext > " $1 ".new_ext"  }' > for_the_birds

It looks excessive, but somehow that combination of quotes works to keep the ' printed as literals. Then if I remember correctly the vaiables are just surrounded with quotes like this: "$1". Try it, let me know how it works with SED.

How to use sed to remove the last n lines of a file

I came up with this, where n is the number of lines you want to delete:

count=`wc -l file`
lines=`expr "$count" - n`
head -n "$lines" file > temp.txt
mv temp.txt file
rm -f temp.txt

It's a little roundabout, but I think it's easy to follow.

  1. Count up the number of lines in the main file
  2. Subtract the number of lines you want to remove from the count
  3. Print out the number of lines you want to keep and store in a temp file
  4. Replace the main file with the temp file
  5. Remove the temp file

Shell script - remove first and last quote (") from a variable

There is a straightforward way using xargs:

> echo '"quoted"' | xargs
quoted

xargs uses echo as the default command if no command is provided and strips quotes from the input. See e.g. here.

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

In-place edits with sed on OS X

You can use:

sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>

Example:

sed -i -e 's/Hello/Bye/' file.txt

This works flawless in Mac.

Using grep and sed to find and replace a string

I have taken Vlad's idea and changed it a little bit. Instead of

grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null

Which yields

sed: couldn't edit /dev/null: not a regular file

I'm doing in 3 different connections to the remote server

touch deleteme
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' ./deleteme
rm deleteme

Although this is less elegant and requires 2 more connections to the server (maybe there's a way to do it all in one line) it does the job efficiently as well

What is the difference between sed and awk?

1) What is the difference between awk and sed ?

Both are tools that transform text. BUT awk can do more things besides just manipulating text. Its a programming language by itself with most of the things you learn in programming, like arrays, loops, if/else flow control etc You can "program" in sed as well, but you won't want to maintain the code written in it.

2) What kind of application are best use cases for sed and awk tools ?

Conclusion: Use sed for very simple text parsing. Anything beyond that, awk is better. In fact, you can ditch sed altogether and just use awk. Since their functions overlap and awk can do more, just use awk. You will reduce your learning curve as well.

How to replace an entire line in a text file by line number

Given this test file (test.txt)

Lorem ipsum dolor sit amet,
consectetur adipiscing elit. 
Duis eu diam non tortor laoreet 
bibendum vitae et tellus.

the following command will replace the first line to "newline text"

$ sed '1 c\
> newline text' test.txt

Result:

newline text
consectetur adipiscing elit. 
Duis eu diam non tortor laoreet 
bibendum vitae et tellus.

more information can be found here

http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-append-insert-replace-and-count-file-lines/

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

Assuming all data is formatted like your example, use 'cut' to get the first column only.

cat $file | cut -d ' ' -f 1  

or to get the first 10 chars.

cat $file | cut -c 1-10

How to use sed to remove all double quotes within a file

Additional comment. Yes this works:

    sed 's/\"//g' infile.txt  > outfile.txt

(however with batch gnu sed, will just print to screen)

In batch scripting (GNU SED), this was needed:

    sed 's/\x22//g' infile.txt  > outfile.txt

How can I replace a newline (\n) using sed?

In order to replace all newlines with spaces using awk, without reading the whole file into memory:

awk '{printf "%s ", $0}' inputfile

If you want a final newline:

awk '{printf "%s ", $0} END {printf "\n"}' inputfile

You can use a character other than space:

awk '{printf "%s|", $0} END {printf "\n"}' inputfile

Delete empty lines using sed

I am missing the awk solution:

awk 'NF' file

Which would return:

xxxxxx
yyyyyy
zzzzzz

How does this work? Since NF stands for "number of fields", those lines being empty have 0 fiedls, so that awk evaluates 0 to False and no line is printed; however, if there is at least one field, the evaluation is True and makes awk perform its default action: print the current line.

delete a column with awk or sed

With GNU awk for inplace editing, \s/\S, and gensub() to delete

1) the FIRST field:

awk -i inplace '{sub(/^\S+\s*/,"")}1' file

or

awk -i inplace '{$0=gensub(/^\S+\s*/,"",1)}1' file

2) the LAST field:

awk -i inplace '{sub(/\s*\S+$/,"")}1' file

or

awk -i inplace '{$0=gensub(/\s*\S+$/,"",1)}1' file

3) the Nth field where N=3:

awk -i inplace '{$0=gensub(/\s*\S+/,"",3)}1' file

Without GNU awk you need a match()+substr() combo or multiple sub()s + vars to remove a middle field. See also Print all but the first three columns.

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

How to insert a text at the beginning of a file?

echo -n "text to insert " ;tac filename.txt| tac > newfilename.txt

The first tac pipes the file backwards (last line first) so the "text to insert" appears last. The 2nd tac wraps it once again so the inserted line is at the beginning and the original file is in its original order.

How to extract text from a string using sed?

Try this instead:

echo "This is 02G05 a test string 20-Jul-2012" | sed 's/.* \([0-9]\+G[0-9]\+\) .*/\1/'

But note, if there is two pattern on one line, it will prints the 2nd.

Bash tool to get nth line from a file

Using what others mentioned, I wanted this to be a quick & dandy function in my bash shell.

Create a file: ~/.functions

Add to it the contents:

getline() { line=$1 sed $line'q;d' $2 }

Then add this to your ~/.bash_profile:

source ~/.functions

Now when you open a new bash window, you can just call the function as so:

getline 441 myfile.txt

bash, extract string before a colon

This works for me you guys can try it out

INPUT='ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/bin/bash'
SUBSTRING=$(echo $INPUT| cut -d: -f1)
echo $SUBSTRING

sed command with -i option failing on Mac, but works on Linux

I believe on OS X when you use -i an extension for the backup files is required. Try:

sed -i .bak 's/hello/gbye/g' *

Using GNU sed the extension is optional.

Printing with sed or awk a line following a matching pattern

If pattern match, copy next line into the pattern buffer, delete a return, then quit -- side effect is to print.

sed '/pattern/ { N; s/.*\n//; q }; d'

sed with literal string--not input file

You have a single quotes conflict, so use:

 echo "A,B,C" | sed "s/,/','/g"

If using , you can do too (<<< is a here-string):

sed "s/,/','/g" <<< "A,B,C"

but not

sed "s/,/','/g"  "A,B,C"

because sed expect file(s) as argument(s)

EDIT:

if you use or any other ones :

echo string | sed ...

Linux bash script to extract IP address

awk '/inet addr:/{gsub(/^.{5}/,"",$2); print $2}' file
192.168.1.103

remove white space from the end of line in linux

This might work for you (GNU sed):

sed -ri  '/\s+$/s///' file

This looks for whitespace at the end of the line and and if present removes it.

How to insert strings containing slashes with sed?

A very useful but lesser-known fact about sed is that the familiar s/foo/bar/ command can use any punctuation, not only slashes. A common alternative is s@foo@bar@, from which it becomes obvious how to solve your problem.

Environment variable substitution in sed

Another easy alternative:

Since $PWD will usually contain a slash /, use | instead of / for the sed statement:

sed -e "s|xxx|$PWD|"

RE error: illegal byte sequence on Mac OS X

mklement0's answer is great, but I have some small tweaks.

It seems like a good idea to explicitly specify bash's encoding when using iconv. Also, we should prepend a byte-order mark (even though the unicode standard doesn't recommend it) because there can be legitimate confusions between UTF-8 and ASCII without a byte-order mark. Unfortunately, iconv doesn't prepend a byte-order mark when you explicitly specify an endianness (UTF-16BE or UTF-16LE), so we need to use UTF-16, which uses platform-specific endianness, and then use file --mime-encoding to discover the true endianness iconv used.

(I uppercase all my encodings because when you list all of iconv's supported encodings with iconv -l they are all uppercase.)

# Find out MY_FILE's encoding
# We'll convert back to this at the end
FILE_ENCODING="$( file --brief --mime-encoding MY_FILE )"
# Find out bash's encoding, with which we should encode
# MY_FILE so sed doesn't fail with 
# sed: RE error: illegal byte sequence
BASH_ENCODING="$( locale charmap | tr [:lower:] [:upper:] )"
# Convert to UTF-16 (unknown endianness) so iconv ensures
# we have a byte-order mark
iconv -f "$FILE_ENCODING" -t UTF-16 MY_FILE > MY_FILE.utf16_encoding
# Whether we're using UTF-16BE or UTF-16LE
UTF16_ENCODING="$( file --brief --mime-encoding MY_FILE.utf16_encoding )"
# Now we can use MY_FILE.bash_encoding with sed
iconv -f "$UTF16_ENCODING" -t "$BASH_ENCODING" MY_FILE.utf16_encoding > MY_FILE.bash_encoding
# sed!
sed 's/.*/&/' MY_FILE.bash_encoding > MY_FILE_SEDDED.bash_encoding
# now convert MY_FILE_SEDDED.bash_encoding back to its original encoding
iconv -f "$BASH_ENCODING" -t "$FILE_ENCODING" MY_FILE_SEDDED.bash_encoding > MY_FILE_SEDDED
# Now MY_FILE_SEDDED has been processed by sed, and is in the same encoding as MY_FILE

How to print the number of characters in each line of a text file

Try this:

while read line    
do    
    echo -e |wc -m      
done <abc.txt    

sed one-liner to convert all uppercase to lowercase?

Here are many solutions :

To upercaser with perl, tr, sed and awk

perl -ne 'print uc'
perl -npe '$_=uc'
perl -npe 'tr/[a-z]/[A-Z]/'
perl -npe 'tr/a-z/A-Z/'
tr '[a-z]' '[A-Z]'
sed y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
sed 's/\([a-z]\)/\U\1/g'
sed 's/.*/\U&/'
awk '{print toupper($0)}'

To lowercase with perl, tr, sed and awk

perl -ne 'print lc'
perl -npe '$_=lc'
perl -npe 'tr/[A-Z]/[a-z]/'
perl -npe 'tr/A-Z/a-z/'
tr '[A-Z]' '[a-z]'
sed y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
sed 's/\([A-Z]\)/\L\1/g'
sed 's/.*/\L&/'
awk '{print tolower($0)}'

Complicated bash to lowercase :

while read v;do v=${v//A/a};v=${v//B/b};v=${v//C/c};v=${v//D/d};v=${v//E/e};v=${v//F/f};v=${v//G/g};v=${v//H/h};v=${v//I/i};v=${v//J/j};v=${v//K/k};v=${v//L/l};v=${v//M/m};v=${v//N/n};v=${v//O/o};v=${v//P/p};v=${v//Q/q};v=${v//R/r};v=${v//S/s};v=${v//T/t};v=${v//U/u};v=${v//V/v};v=${v//W/w};v=${v//X/x};v=${v//Y/y};v=${v//Z/z};echo "$v";done

Complicated bash to uppercase :

while read v;do v=${v//a/A};v=${v//b/B};v=${v//c/C};v=${v//d/D};v=${v//e/E};v=${v//f/F};v=${v//g/G};v=${v//h/H};v=${v//i/I};v=${v//j/J};v=${v//k/K};v=${v//l/L};v=${v//m/M};v=${v//n/N};v=${v//o/O};v=${v//p/P};v=${v//q/Q};v=${v//r/R};v=${v//s/S};v=${v//t/T};v=${v//u/U};v=${v//v/V};v=${v//w/W};v=${v//x/X};v=${v//y/Y};v=${v//z/Z};echo "$v";done

Simple bash to lowercase :

while read v;do echo "${v,,}"; done

Simple bash to uppercase :

while read v;do echo "${v^^}"; done

Note that ${v,} and ${v^} only change the first letter.

You should use it that way :

(while read v;do echo "${v,,}"; done) < input_file.txt > output_file.txt

How to remove leading whitespace from each line in a file

You can use AWK:

$ awk '{$1=$1}1' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)

sed

$ sed 's|^[[:blank:]]*||g' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)

The shell's while/read loop

while read -r line
do
    echo $line
done <"file"

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

How to delete from a text file, all lines that contain a specific string?

You can also delete a range of lines in a file. For example to delete stored procedures in a SQL file.

sed '/CREATE PROCEDURE.*/,/END ;/d' sqllines.sql

This will remove all lines between CREATE PROCEDURE and END ;.

I have cleaned up many sql files withe this sed command.

How to remove trailing whitespaces with sed?

I have a script in my .bashrc that works under OSX and Linux (bash only !)

function trim_trailing_space() {
  if [[ $# -eq 0 ]]; then
    echo "$FUNCNAME will trim (in place) trailing spaces in the given file (remove unwanted spaces at end of lines)"
    echo "Usage :"
    echo "$FUNCNAME file"
    return
  fi
  local file=$1
  unamestr=$(uname)
  if [[ $unamestr == 'Darwin' ]]; then
    #specific case for Mac OSX
    sed -E -i ''  's/[[:space:]]*$//' $file
  else
    sed -i  's/[[:space:]]*$//' $file
  fi
}

to which I add:

SRC_FILES_EXTENSIONS="js|ts|cpp|c|h|hpp|php|py|sh|cs|sql|json|ini|xml|conf"

function find_source_files() {
  if [[ $# -eq 0 ]]; then
    echo "$FUNCNAME will list sources files (having extensions $SRC_FILES_EXTENSIONS)"
    echo "Usage :"
    echo "$FUNCNAME folder"
    return
  fi
  local folder=$1

  unamestr=$(uname)
  if [[ $unamestr == 'Darwin' ]]; then
    #specific case for Mac OSX
    find -E $folder -iregex '.*\.('$SRC_FILES_EXTENSIONS')'
  else
    #Rhahhh, lovely
    local extensions_escaped=$(echo $SRC_FILES_EXTENSIONS | sed s/\|/\\\\\|/g)
    #echo "extensions_escaped:$extensions_escaped"
    find $folder -iregex '.*\.\('$extensions_escaped'\)$'
  fi
}

function trim_trailing_space_all_source_files() {
  for f in $(find_source_files .); do trim_trailing_space $f;done
}

How can I extract a predetermined range of lines from a text file on Unix?

Quick and dirty:

head -16428 < file.in | tail -259 > file.out

Probably not the best way to do it but it should work.

BTW: 259 = 16482-16224+1.

Turning multiple lines into one comma separated line

based on your input example, this awk line works. (without trailing comma)

awk -vRS="" -vOFS=',' '$1=$1' file

test:

kent$  echo "foo
bar
qux
zuu
sdf
sdfasdf"|awk -vRS="" -vOFS=',' '$1=$1' 
foo,bar,qux,zuu,sdf,sdfasdf

How to replace a whole line with sed?

If you would like to use awk then this would work too

awk -F= '{$2="xxx";print}' OFS="\=" filename

Replace whitespace with a comma in a text file in Linux

This worked for me.

sed -e 's/\s\+/,/g' input.txt >> output.csv

How to use variables in a command in sed?

This might work for you:

sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1

sed edit file in place

Like Moneypenny said in Skyfall: "Sometimes the old ways are best." Kincade said something similar later on.

$ printf ',s/false/true/g\nw\n' | ed {YourFileHere}

Happy editing in place. Added '\nw\n' to write the file. Apologies for delay answering request.

Creating watermark using html and css

I would recommend everyone look into CSS grids. It has been supported by most browsers now since about 2017. Here is a link to some documentation: https://css-tricks.com/snippets/css/complete-guide-grid/ . It is so much easier to keep your page elements where you want them, especially when it comes to responsiveness. It took me all of 20 minutes to learn how to do it, and I'm a newbie!

<div class="grid-div">
    <p class="hello">Hello</p>
    <p class="world">World</p>
</div>


//begin css//

.grid-div {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-template-rows: 50% 50%;
}

.hello {
    grid-column-start: 2;
    grid-row-start: 2;
}

.world {
    grid-column-start: 1;
    grid-row-start: 2;
}

This code will split the page into 4 equal quadrants, placing the "Hello" in the bottom right, and the "World" in the bottom left without having to change their positioning or playing with margins.

This can be extrapolated into very complex grid layouts with overlapping, infinite grids of all sizes, and even grids nested inside grids, without losing control of your elements every time something changes (MS Word I'm looking at you).

Hope this helps whoever still needs it!

Save Screen (program) output to a file

A different answer if you need to save the output of your whole scrollback buffer from an already actively running screen:

Ctrl-a [ g SPACE G $ >.

This will save your whole buffer to /tmp/screen-exchange

Checking if a string is empty or null in Java

You can use Apache commons-lang

StringUtils.isEmpty(String str) - Checks if a String is empty ("") or null.

or

StringUtils.isBlank(String str) - Checks if a String is whitespace, empty ("") or null.

the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API

HTML5 Video not working in IE 11

What is the resolution of the video? I had a similar problem with IE11 in Win7. The Microsoft H.264 decoder supports only 1920x1088 pixels in Windows 7. See my story: http://lars.st0ne.at/blog/html5+video+in+IE11+-+size+does+matter

Link and execute external JavaScript file hosted on GitHub

There is a good workaround for this, now, by using jsdelivr.net.

Steps:

  1. Find your link on GitHub, and click to the "Raw" version.
  2. Copy the URL.
  3. Change raw.githubusercontent.com to cdn.jsdelivr.net
  4. Insert /gh/ before your username.
  5. Remove the branch name.
  6. (Optional) Insert the version you want to link to, as @version (if you do not do this, you will get the latest - which may cause long-term caching)

Examples:

http://raw.githubusercontent.com/<username>/<repo>/<branch>/path/to/file.js

Use this URL to get the latest version:

http://cdn.jsdelivr.net/gh/<username>/<repo>/path/to/file.js

Use this URL to get a specific version or commit hash:

http://cdn.jsdelivr.net/gh/<username>/<repo>@<version or hash>/path/to/file.js

For production environments, consider targeting a specific tag or commit-hash rather than the branch. Using the latest link may result in long-term caching of the file, causing your link to not be updated as you push new versions. Linking to a file by commit-hash or tag makes the link unique to version.


Why is this needed?

In 2013, GitHub started using X-Content-Type-Options: nosniff, which instructs more modern browsers to enforce strict MIME type checking. It then returns the raw files in a MIME type returned by the server, preventing the browser from using the file as-intended (if the browser honors the setting).

For background on this topic, please refer to this discussion thread.

How to trigger a build only if changes happen on particular set of files

You can use Generic Webhook Trigger Plugin for this.

With a variable like changed_files and expression $.commits[*].['modified','added','removed'][*].

You can have a filter text like $changed_files and filter regexp like "folder/subfolder/[^"]+?" if folder/subfolder is the folder that should trigger builds.

Change color of Button when Mouse is over

<Button Content="Click" Width="200" Height="50">
<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="LightBlue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="LightGreen" TargetName="Border" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Button.Style>

split string only on first instance of specified character

For beginner like me who are not used to Regular Expression, this workaround solution worked:

   var field = "Good_Luck_Buddy";
   var newString = field.slice( field.indexOf("_")+1 );

slice() method extracts a part of a string and returns a new string and indexOf() method returns the position of the first found occurrence of a specified value in a string.

Perl - Multiple condition if statement without duplicating code?

if (   ($name eq "tom" and $password eq "123!")
    or ($name eq "frank" and $password eq "321!")) {

    print "You have gained access.";
}
else {
    print "Access denied!";
}

How to check internet access on Android? InetAddress never times out

There's more than one way

First, shortest but Inefficient way

Network State Permission only needed

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Then this method,

 public boolean activeNetwork () {
        ConnectivityManager cm =
                (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnected();

        return isConnected;

    }

As seen in answers ConnectivityManager is a solution, I just added it within a method this is a simplified method all use
ConnectivityManager returns true if there is a network access not Internet access, means if your WiFi is connected to a router but the router has no internet it returns true, it check connection availability

Second, Efficient way

Network State and Internet Permissions needed

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

Then this class,

 public class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> {

        private Context context;

        public CheckInternetAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected Boolean doInBackground(Void... params) {

            ConnectivityManager cm =
                    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

            assert cm != null;
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnected();


            if (isConnected) {
                try {
                    HttpURLConnection urlc = (HttpURLConnection)
                            (new URL("http://clients3.google.com/generate_204")
                                    .openConnection());
                    urlc.setRequestProperty("User-Agent", "Android");
                    urlc.setRequestProperty("Connection", "close");
                    urlc.setConnectTimeout(1500);
                    urlc.connect();
                    if (urlc.getResponseCode() == 204 &&
                            urlc.getContentLength() == 0)
                        return true;

                } catch (IOException e) {
                    Log.e("TAG", "Error checking internet connection", e);
                    return false;
                }
            } else {
                Log.d("TAG", "No network available!");
                return false;
            }


            return null;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            Log.d("TAG", "result" + result);

            if(result){
                // do ur code
            }

        }


    }

Call CheckInternetAsyncTask

new CheckInternetAsyncTask(getApplicationContext()).execute();

Some Explanations :-

  • you have to check Internet on AsyncTask, otherwise it can throw android.os.NetworkOnMainThreadException in some cases

  • ConnectivityManager used to check the network access if true sends request (Ping)

  • Request send to http://clients3.google.com/generate_204, This well-known URL is known to return an empty page with an HTTP status 204 this is faster and more efficient than http://www.google.com , read this. if you have website it's preferred to put you website instead of google, only if you use it within the app

  • Timeout can be changed range (20ms -> 2000ms), 1500ms is commonly used

JQuery create a form and add elements to it programmatically

function setValToAssessment(id)
{

     $.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
     {
        var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm'); 
         $.each(response,function(key,value){
            $("<input type='text' value='"+value+"' >")
 .attr("id", key)
 .attr("name", key)
 .appendTo("form");


             });
              $('#hiddenForm').appendTo('body').submit();

        // window.location.href = "<?=URL.$param->module?>/assessment";
    });

}     

How to disable HTML button using JavaScript?

Since this setting is not an attribute

It is an attribute.

Some attributes are defined as boolean, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled", you include only the bold part. In HTML 4, you should include only the bold part as the full version is marked as a feature with limited support (although that is less true now then when the spec was written).

As of HTML 5, the rules have changed and now you include only the name and not the value. This makes no practical difference because the name and the value are the same.

The DOM property is also called disabled and is a boolean that takes true or false.

foo.disabled = true;

In theory you can also foo.setAttribute('disabled', 'disabled'); and foo.removeAttribute("disabled"), but I wouldn't trust this with older versions of Internet Explorer (which are notoriously buggy when it comes to setAttribute).

SQLite Query in Android to count rows

how to get count column

final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;

int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);

This is the most concise and precise alternative. No need to handle cursors and their closing.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).

Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

First, if you are able to locate your

bootstrap.css file

and

bootstrap.min.js file

in your computer, then what you just do is

First download your favorite theme i.e. from http://bootswatch.com/

Copy the downloaded bootstrap.css and bootstrap.min.js files

Then in your computer locate the existing files and replace them with the new downloaded files.

NOTE: ensure your downloaded files are renamed to what is in your folder

i.e.

enter image description here

Then you are good to go.

sometimes result may not display immediately. your may need to run the css on your browser as a way of refreshing

Web Service vs WCF Service

The major difference is time-out, WCF Service has timed-out when there is no response, but web-service does not have this property.

Splitting dataframe into multiple dataframes

  • First, the method in the OP works, but isn't efficient. It may have seemed to run forever, because the dataset was long.
  • Use .groupby on the 'method' column, and create a dict of DataFrames with unique 'method' values as the keys, with a dict-comprehension.
    • .groupby returns a groupby object, that contains information about the groups, where g is the unique value in 'method' for each group, and d is the DataFrame for that group.
  • The value of each key in df_dict, will be a DataFrame, which can be accessed in the standard way, df_dict['key'].
  • The original question wanted a list of DataFrames, which can be done with a list-comprehension
    • df_list = [d for _, d in df.groupby('method')]
import pandas as pd
import seaborn as sns  # for test dataset

# load data for example
df = sns.load_dataset('planets')

# display(df.head())
            method  number  orbital_period   mass  distance  year
0  Radial Velocity       1         269.300   7.10     77.40  2006
1  Radial Velocity       1         874.774   2.21     56.95  2008
2  Radial Velocity       1         763.000   2.60     19.84  2011
3  Radial Velocity       1         326.030  19.40    110.62  2007
4  Radial Velocity       1         516.220  10.50    119.47  2009


# Using a dict-comprehension, the unique 'method' value will be the key
df_dict = {g: d for g, d in df.groupby('method')}

print(df_dict.keys())
[out]:
dict_keys(['Astrometry', 'Eclipse Timing Variations', 'Imaging', 'Microlensing', 'Orbital Brightness Modulation', 'Pulsar Timing', 'Pulsation Timing Variations', 'Radial Velocity', 'Transit', 'Transit Timing Variations'])

# or a specific name for the key, using enumerate (e.g. df1, df2, etc.)
df_dict = {f'df{i}': d for i, (g, d) in enumerate(df.groupby('method'))}

print(df_dict.keys())
[out]:
dict_keys(['df0', 'df1', 'df2', 'df3', 'df4', 'df5', 'df6', 'df7', 'df8', 'df9'])
  • df_dict['df1].head(3) or df_dict['Astrometry'].head(3)
  • There are only 2 in this group
         method  number  orbital_period  mass  distance  year
113  Astrometry       1          246.36   NaN     20.77  2013
537  Astrometry       1         1016.00   NaN     14.98  2010
  • df_dict['df2].head(3) or df_dict['Eclipse Timing Variations'].head(3)
                       method  number  orbital_period  mass  distance  year
32  Eclipse Timing Variations       1         10220.0  6.05       NaN  2009
37  Eclipse Timing Variations       2          5767.0   NaN    130.72  2008
38  Eclipse Timing Variations       2          3321.0   NaN    130.72  2008
  • df_dict['df3].head(3) or df_dict['Imaging'].head(3)
     method  number  orbital_period  mass  distance  year
29  Imaging       1             NaN   NaN     45.52  2005
30  Imaging       1             NaN   NaN    165.00  2007
31  Imaging       1             NaN   NaN    140.00  2004

Alternatively

  • This is a manual method to create separate DataFrames using pandas: Boolean Indexing
  • This is similar to the accepted answer, but .loc is not required.
  • This is an acceptable method for creating a couple extra DataFrames.
  • The pythonic way to create multiple objects, is by placing them in a container (e.g. dict, list, generator, etc.), as shown above.
df1 = df[df.method == 'Astrometry']
df2 = df[df.method == 'Eclipse Timing Variations']

Android SDK Setup under Windows 7 Pro 64 bit

This blog shows how to update the registry so the Android SDK can find your Java SDK on a 64-bit machine.

http://codearetoy.wordpress.com/2010/12/23/jdk-not-found-on-installing-android-sdk/

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Rob Heiser suggested checking out your java version by using 'java -version'.

That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).

http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path

java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.

I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).

Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.

Converting string to double in C#

You can try this example out. A simple C# progaram to convert string to double

class Calculations{

protected double length;
protected double height;
protected double width;

public void get_data(){

this.length = Convert.ToDouble(Console.ReadLine());
this.width  = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());

   }
}

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

Spring schemaLocation fails when there is no internet connection

Find class path

If you are using eclipse click on corresponding jar file. Goto ->META-INF-> open file spring.schemas

you will see the lines something like below.

http://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.1.xsd

copy after = and configure beans something like below.

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:rabbit="http://www.springframework.org/schema/rabbit" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/rabbit classpath:org/springframework/amqp/rabbit/config/spring-rabbit-1.1.xsd http://www.springframework.org/schema/beans classpath:org/springframework/beans/factory/xml/spring-beans-3.1.xsd http://www.springframework.org/schema/context classpath:org/springframework/context/config/spring-context-3.1.xsd http://www.springframework.org/schema/util classpath:org/springframework/beans/factory/xml/spring-util-3.1.xsd">

App crashing when trying to use RecyclerView on android 5.0

I faced the same issue cause I had the RecyclerView in another layout and not on activity_main.xml.

By searching on some sites I got something and felt like sharing here

  1. Add Id to Include tag in Activity_main.xml

    <include id="includedRecyclerLayout" .... </include>

  2. call this layout before Searching view by ID in MainActivity.java

    `ConstraintLayout includedLayout = findViewById(R.id.inckudedRecyclerLayout);

    RecyclerViewrecyclerview=includedLayout.findViewById(R.id.RECYCLER_VIEW_ID)`;

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

To switch from vertical split to horizontal split fast in Vim

In VIM, take a look at the following to see different alternatives for what you might have done:

:help opening-window

For instance:

Ctrl-W s
Ctrl-W o
Ctrl-W v
Ctrl-W o
Ctrl-W s
...

An error when I add a variable to a string

You have empty $entry_database variable. As you see in error: ListEmail, Title FROM WHERE ID bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:

SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]

which in your way should become:

SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'

When should I use Kruskal as opposed to Prim (and vice versa)?

In kruskal Algorithm we have number of edges and number of vertices on a given graph but on each edge we have some value or weight on behalf of which we can prepare a new graph which must be not cyclic or not close from any side For Example

graph like this _____________ | | | | | | |__________| | Give name to any vertex a,b,c,d,e,f .

How to do scanf for single char in C

First of all, avoid scanf(). Using it is not worth the pain.

See: Why does everyone say not to use scanf? What should I use instead?

Using a whitespace character in scanf() would ignore any number of whitespace characters left in the input stream, what if you need to read more inputs? Consider:

#include <stdio.h>

int main(void)
{
   char ch1, ch2;

   scanf("%c", &ch1);  /* Leaves the newline in the input */
   scanf(" %c", &ch2); /* The leading whitespace ensures it's the
                          previous newline is ignored */
   printf("ch1: %c, ch2: %c\n", ch1, ch2);

   /* All good so far */

   char ch3;
   scanf("%c", &ch3); /* Doesn't read input due to the same problem */
   printf("ch3: %c\n", ch3);

   return 0;
}

While the 3rd scanf() can be fixed in the same way using a leading whitespace, it's not always going to that simple as above. Another major problem is, scanf() will not discard any input in the input stream if it doesn't match the format. For example, if you input abc for an int such as: scanf("%d", &int_var); then abc will have to read and discarded. Consider:

#include <stdio.h>

int main(void)
{
    int i;

    while(1) {
        if (scanf("%d", &i) != 1) { /* Input "abc" */
            printf("Invalid input. Try again\n");
        } else {
            break;
        }
    }

    printf("Int read: %d\n", i);
    return 0;
}

Another common problem is mixing scanf() and fgets(). Consider:

#include <stdio.h>

int main(void)
{
    int age;
    char name[256];
    printf("Input your age:");
    scanf("%d", &age); /* Input 10 */
    printf("Input your full name [firstname lastname]");
    fgets(name, sizeof name, stdin); /* Doesn't read! */
    return 0;
}

The call to fgets() doesn't wait for input because the newline left by the previous scanf() call is read and fgets() terminates input reading when it encounters a newline.

There are many other similar problems associated with scanf(). That's why it's generally recommended to avoid it.

So, what's the alternative? Use fgets() function instead in the following fashion to read a single character:

#include <stdio.h>

int main(void)
{
    char line[256];
    char ch;

    if (fgets(line, sizeof line, stdin) == NULL) {
        printf("Input error.\n");
        exit(1);
    }

    ch = line[0];
    printf("Character read: %c\n", ch);
    return 0;
}

One detail to be aware of when using fgets() will read in the newline character if there's enough room in the inut buffer. If it's not desirable then you can remove it:

char line[256];

if (fgets(line, sizeof line, stdin) == NULL) {
    printf("Input error.\n");
    exit(1);
}

line[strcpsn(line, "\n")] = 0; /* removes the trailing newline, if present */

Parsing ISO 8601 date in Javascript

Looks like moment.js is the most popular and with active development:

moment("2010-01-01T05:06:07", moment.ISO_8601);

Where does Android app package gets installed on phone

You will find the application folder at:

/data/data/"your package name"

you can access this folder using the DDMS for your Emulator. you can't access this location on a real device unless you have a rooted device.

I have Python on my Ubuntu system, but gcc can't find Python.h

None of the answers worked for me. If you are running on Ubuntu, you can try:

With python3:

sudo apt-get install python3 python-dev python3-dev \
     build-essential libssl-dev libffi-dev \
     libxml2-dev libxslt1-dev zlib1g-dev \
     python-pip

With Python 2:

sudo apt-get install python-dev  \
     build-essential libssl-dev libffi-dev \
     libxml2-dev libxslt1-dev zlib1g-dev \
     python-pip

Bootstrap 3 with remote Modal

Regarding the remote option for modals, from the docs:

If a remote URL is provided, content will be loaded via jQuery's load method and injected into the root of the modal element.

That means your remote file should provide the complete modal structure, not just what you want to display on the body.

Bootstrap 3.1 Update:

In v3.1 the above behavior was changed and now the remote content is loaded into .modal-content

See this Demo fiddle

Boostrap 3.3 Update:

This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.

Facebook Oauth Logout

Update: This solution works and just a call to 'FB.logout()' doesn't work because browser wants a user interaction to actually call this function, so that it knows - it is a user not a script.

<a href="#" onclick="FB.logout();">Logout</a> 

Check whether variable is number or string in JavaScript

Check if the value is a string literal or String object:

function isString(o) {
    return typeof o == "string" || (typeof o == "object" && o.constructor === String);
}

Unit test:

function assertTrue(value, message) {
    if (!value) {
        alert("Assertion error: " + message);
    }
}

function assertFalse(value, message)
{
    assertTrue(!value, message);
}

assertTrue(isString("string literal"), "number literal");
assertTrue(isString(new String("String object")), "String object");
assertFalse(isString(1), "number literal");
assertFalse(isString(true), "boolean literal");
assertFalse(isString({}), "object");

Checking for a number is similar:

function isNumber(o) {
    return typeof o == "number" || (typeof o == "object" && o.constructor === Number);
}

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to write ternary operator condition in jQuery?

The Ternary operator is just written as a boolean expression followed by a questionmark and then two further expressions separated by a colon.

The first thing that I can see that you have got wrong is that your first expression isn't returning a boolean or anything sensible that could be converted to a boolean. Your first expression is always going to return a jQuery object that has no sensible interpretation as a boolean and what it does convert to is probably an unchanging interpretation. You are always best off returning something that has a well known boolean interpretation, if nothign else for the sake of readability.

The second thing is that you are putting a semicolon after each of your expressions which is wrong. In effect this is saying "end of construct" and so is breaking your ternary operator.

In this situation though you probably can do this a more easy way. If you use classes and the toggleClass method then you can easily get it to switch a class on and off and then you can put your styles in that class definition (Kudos to @yoavmatchulsky for suggesting use of classes up there in comments).

A fiddle of this is found here: http://jsfiddle.net/chrisvenus/wSMnV/ (based on the original)

SQL Server: converting UniqueIdentifier to string in a case statement

Instead of Str(RequestID), try convert(varchar(38), RequestID)

One liner to check if element is in the list

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

                if( Arrays.asList("a","b","c").contains("a"){
                      System.out.println("It is here");
         }
    }

}

This is what you looking for. The contains() method simply checks the index of element in the list. If the index is greater than '0' than element is present in the list.

public boolean contains(Object o) {
return indexOf(o) >= 0;
}

"java.lang.OutOfMemoryError : unable to create new native Thread"

I had the same problem due to ghost processes that didn't show up when using top in bash. This prevented the JVM to spawn more threads.

For me, it resolved when listing all java processes with jps (just execute jps in your shell) and killed them separately using the kill -9 pid bash command for each ghost process.

This might help in some scenarios.

Timer function to provide time in nano seconds using C++

If this is for Linux, I've been using the function "gettimeofday", which returns a struct that gives the seconds and microseconds since the Epoch. You can then use timersub to subtract the two to get the difference in time, and convert it to whatever precision of time you want. However, you specify nanoseconds, and it looks like the function clock_gettime() is what you're looking for. It puts the time in terms of seconds and nanoseconds into the structure you pass into it.

Add Favicon with React and Webpack

Here is all you need:

new HtmlWebpackPlugin({
    favicon: "./src/favicon.gif"
})

That is definitely after adding "favicon.gif" to the folder "src".

This will transfer the icon to your build folder and include it in your tag like this <link rel="shortcut icon" href="favicon.gif">. This is safer than just importing with copyWebpackPLugin

Stop and Start a service via batch or cmd file?

We'd like to think that "net stop " will stop the service. Sadly, reality isn't that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won't know, though, unless you check errorlevel.

The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.

But then again...

I'm seeing the first service take a long time to stop, then the "net stop" for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still "Started" - no change to "Stopping". Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.

What is the simplest way to swap each pair of adjoining chars in a string with Python?

While the above solutions do work, there is a very simple solution shall we say in "layman's" terms. Someone still learning python and string's can use the other answers but they don't really understand how they work or what each part of the code is doing without a full explanation by the poster as opposed to "this works". The following executes the swapping of every second character in a string and is easy for beginners to understand how it works.

It is simply iterating through the string (any length) by two's (starting from 0 and finding every second character) and then creating a new string (swapped_pair) by adding the current index + 1 (second character) and then the actual index (first character), e.g., index 1 is put at index 0 and then index 0 is put at index 1 and this repeats through iteration of string.

Also added code to ensure string is of even length as it only works for even length.

DrSanjay Bhakkad post above is also a good one that works for even or odd strings and is basically doing the same function as below.

string = "abcdefghijklmnopqrstuvwxyz123"

# use this prior to below iteration if string needs to be even but is possibly odd
if len(string) % 2 != 0:
    string = string[:-1]

# iteration to swap every second character in string
swapped_pair = ""
for i in range(0, len(string), 2):
    swapped_pair += (string[i + 1] + string[i])

# use this after above iteration for any even or odd length of strings
if len(swapped_pair) % 2 != 0:
    swapped_adj += swapped_pair[-1]

print(swapped_pair)

badcfehgjilknmporqtsvuxwzy21 # output if the "needs to be even" code used
badcfehgjilknmporqtsvuxwzy213 # output if the "even or odd" code used

Can you explain the HttpURLConnection connection process?

String message = URLEncoder.encode("my message", "UTF-8");

try {
    // instantiate the URL object with the target URL of the resource to
    // request
    URL url = new URL("http://www.example.com/comment");

    // instantiate the HttpURLConnection with the URL object - A new
    // connection is opened every time by calling the openConnection
    // method of the protocol handler for this URL.
    // 1. This is the point where the connection is opened.
    HttpURLConnection connection = (HttpURLConnection) url
            .openConnection();
    // set connection output to true
    connection.setDoOutput(true);
    // instead of a GET, we're going to send using method="POST"
    connection.setRequestMethod("POST");

    // instantiate OutputStreamWriter using the output stream, returned
    // from getOutputStream, that writes to this connection.
    // 2. This is the point where you'll know if the connection was
    // successfully established. If an I/O error occurs while creating
    // the output stream, you'll see an IOException.
    OutputStreamWriter writer = new OutputStreamWriter(
            connection.getOutputStream());

    // write data to the connection. This is data that you are sending
    // to the server
    // 3. No. Sending the data is conducted here. We established the
    // connection with getOutputStream
    writer.write("message=" + message);

    // Closes this output stream and releases any system resources
    // associated with this stream. At this point, we've sent all the
    // data. Only the outputStream is closed at this point, not the
    // actual connection
    writer.close();
    // if there is a response code AND that response code is 200 OK, do
    // stuff in the first if block
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        // OK

        // otherwise, if any other status code is returned, or no status
        // code is returned, do stuff in the else block
    } else {
        // Server returned HTTP error code.
    }
} catch (MalformedURLException e) {
    // ...
} catch (IOException e) {
    // ...
}

The first 3 answers to your questions are listed as inline comments, beside each method, in the example HTTP POST above.

From getOutputStream:

Returns an output stream that writes to this connection.

Basically, I think you have a good understanding of how this works, so let me just reiterate in layman's terms. getOutputStream basically opens a connection stream, with the intention of writing data to the server. In the above code example "message" could be a comment that we're sending to the server that represents a comment left on a post. When you see getOutputStream, you're opening the connection stream for writing, but you don't actually write any data until you call writer.write("message=" + message);.

From getInputStream():

Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.

getInputStream does the opposite. Like getOutputStream, it also opens a connection stream, but the intent is to read data from the server, not write to it. If the connection or stream-opening fails, you'll see a SocketTimeoutException.

How about the getInputStream? Since I'm only able to get the response at getInputStream, then does it mean that I didn't send any request at getOutputStream yet but simply establishes a connection?

Keep in mind that sending a request and sending data are two different operations. When you invoke getOutputStream or getInputStream url.openConnection(), you send a request to the server to establish a connection. There is a handshake that occurs where the server sends back an acknowledgement to you that the connection is established. It is then at that point in time that you're prepared to send or receive data. Thus, you do not need to call getOutputStream to establish a connection open a stream, unless your purpose for making the request is to send data.

In layman's terms, making a getInputStream request is the equivalent of making a phone call to your friend's house to say "Hey, is it okay if I come over and borrow that pair of vice grips?" and your friend establishes the handshake by saying, "Sure! Come and get it". Then, at that point, the connection is made, you walk to your friend's house, knock on the door, request the vice grips, and walk back to your house.

Using a similar example for getOutputStream would involve calling your friend and saying "Hey, I have that money I owe you, can I send it to you"? Your friend, needing money and sick inside that you kept it for so long, says "Sure, come on over you cheap bastard". So you walk to your friend's house and "POST" the money to him. He then kicks you out and you walk back to your house.

Now, continuing with the layman's example, let's look at some Exceptions. If you called your friend and he wasn't home, that could be a 500 error. If you called and got a disconnected number message because your friend is tired of you borrowing money all the time, that's a 404 page not found. If your phone is dead because you didn't pay the bill, that could be an IOException. (NOTE: This section may not be 100% correct. It's intended to give you a general idea of what's happening in layman's terms.)

Question #5:

Yes, you are correct that openConnection simply creates a new connection object but does not establish it. The connection is established when you call either getInputStream or getOutputStream.

openConnection creates a new connection object. From the URL.openConnection javadocs:

A new connection is opened every time by calling the openConnection method of the protocol handler for this URL.

The connection is established when you call openConnection, and the InputStream, OutputStream, or both, are called when you instantiate them.

Question #6:

To measure the overhead, I generally wrap some very simple timing code around the entire connection block, like so:

long start = System.currentTimeMillis();
log.info("Time so far = " + new Long(System.currentTimeMillis() - start) );

// run the above example code here
log.info("Total time to send/receive data = " + new Long(System.currentTimeMillis() - start) );

I'm sure there are more advanced methods for measuring the request time and overhead, but this generally is sufficient for my needs.

For information on closing connections, which you didn't ask about, see In Java when does a URL connection close?.

Understanding ibeacon distancing

It's possible, but it depends on the power output of the beacon you're receiving, other rf sources nearby, obstacles and other environmental factors. Best thing to do is try it out in the environment you're interested in.

How to concat two ArrayLists?

var arr3 = new arraylist();
for(int i=0, j=0, k=0; i<arr1.size()+arr2.size(); i++){
    if(i&1)
        arr3.add(arr1[j++]);
    else
        arr3.add(arr2[k++]);
}

as you say, "the names and numbers beside each other".

MySQL - UPDATE query based on SELECT Query

Easy in MySQL:

UPDATE users AS U1, users AS U2 
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id

Change class on mouseover in directive

I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.

.directive('hoverClass', function () {
    return {
        restrict: 'A',
        scope: {
            hoverClass: '@'
        },
        link: function (scope, element) {
            element.on('mouseenter', function() {
                element.addClass(scope.hoverClass);
            });
            element.on('mouseleave', function() {
                element.removeClass(scope.hoverClass);
            });
        }
    };
})

then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:

<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
                index="{{$index}}"><i class="{{item.icon}}"
                box="course-{{$index}}"></i></li>

This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work

<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
 data-ng-controller ="CourseItemController"
 data-ng-class="{ selected: isSelected }">

providing of course that the li's are infact children of the parent div

What's the most appropriate HTTP status code for an "item not found" error page

That's depending if userid is a resource identifier or additional parameter. If it is then it's ok to return 404 if not you might return other code like

400 (bad request) - indicates a bad request
or
412 (Precondition Failed) e.g. conflict by performing conditional update

More info in free InfoQ Explores: REST book.

Printing hexadecimal characters in C

You can use hh to tell printf that the argument is an unsigned char. Use 0 to get zero padding and 2 to set the width to 2. x or X for lower/uppercase hex characters.

uint8_t a = 0x0a;
printf("%02hhX", a); // Prints "0A"
printf("0x%02hhx", a); // Prints "0x0a"

Edit: If readers are concerned about 2501's assertion that this is somehow not the 'correct' format specifiers I suggest they read the printf link again. Specifically:

Even though %c expects int argument, it is safe to pass a char because of the integer promotion that takes place when a variadic function is called.

The correct conversion specifications for the fixed-width character types (int8_t, etc) are defined in the header <cinttypes>(C++) or <inttypes.h> (C) (although PRIdMAX, PRIuMAX, etc is synonymous with %jd, %ju, etc).

As for his point about signed vs unsigned, in this case it does not matter since the values must always be positive and easily fit in a signed int. There is no signed hexideximal format specifier anyway.

Edit 2: ("when-to-admit-you're-wrong" edition):

If you read the actual C11 standard on page 311 (329 of the PDF) you find:

hh: Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument.

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

Download TS files from video stream

using this post

  • Open Firefox / chrome

  • open page the video

  • Play Video

  • click F12 on keyboard -> network

  • in Filter URLs ts

  • copy link of ts

  • remove index and ts extension from link

    for example:

    http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000_454.ts
    

    will be copied as

     http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000
    

insert in below script under LINK

#!/bin/bash

# insert here urls
LINK=(

'http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000' # replace this with your url 

)

mkdir my-videos
cd mkdir my-videos

CNT=0

for URL in ${LINK[@]}
do
  # create folder for streaming media
  CNT=$((CNT + 1))
  mkdir $CNT
  cd $CNT

  (

   DIR="${URL##*/}"

   # download all videos
   wget $URL'_'{0..1200}.ts

   # link videos
   echo $DIR'_'{0..1200}.ts | tr " " "\n" > tslist
   while read line; do cat $line >> $CNT.mp4; done < tslist

   rm -rf media* tslist
   ) &
   cd ..

done

wait

EDIT

adding script in python - runs on windows and linux

import urllib.request
import os
import shutil

my_lessons = [
   #  http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000_454.ts
    "http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000" # replace this with your url 


]

lesson_dir = "my_vids"
try:
    shutil.rmtree(lesson_dir)
except:
    print "ok"

os.makedirs(lesson_dir)
os.chdir(lesson_dir)

for lesson, dwn_link in enumerate(my_lessons):
    print ("downloading lesson  %d.. " % (lesson), dwn_link)
    file_name = '%04d.mp4' % lesson
    f = open(file_name, 'ab')
    for x in range(0, 1200):
        try:
            rsp = urllib.request.urlopen(dwn_link + "_%04d.ts" % (x) )
        except:
            break
        file_name = '%d.mp4' % lesson
        print "downloading  %d.ts" % (x)
        f.write(rsp.read())
    f.close()



print "done good luck!! ==================  "

if the script fails, or downloads empty file, try removing the try wrap to see what fails

Selenium Webdriver move mouse to Point

IMHO you should pay your attention to Robot.class

Still if you want to move the mouse pointer physically, you need to take different approach using Robot class

  Point coordinates = driver.findElement(By.id("ctl00_portalmaster_txtUserName")).getLocation();
  Robot robot = new Robot();
  robot.mouseMove(coordinates.getX(),coordinates.getY()+120);

Webdriver provide document coordinates, where as Robot class is based on Screen coordinates, so I have added +120 to compensate the browser header.
Screen Coordinates: These are coordinates measured from the top left corner of the user's computer screen. You'd rarely get coordinates (0,0) because that is usually outside the browser window. About the only time you'd want these coordinates is if you want to position a newly created browser window at the point where the user clicked. In all browsers these are in event.screenX and event.screenY.
Window Coordinates: These are coordinates measured from the top left corner of the browser's content area. If the window is scrolled, vertically or horizontally, this will be different from the top left corner of the document. This is rarely what you want. In all browsers these are in event.clientX and event.clientY.
Document Coordinates: These are coordinates measured from the top left corner of the HTML Document. These are the coordinates that you most frequently want, since that is the coordinate system in which the document is defined.

More details you can get here

Hope this be helpful to you.

How to get streaming url from online streaming radio station

not that hard,

if you take a look at the page source, you'll see that it uses to stream the audio via shoutcast.

this is the stream url

"StreamUrl": "http://stream.radiotime.com/listen.stream?streamIds=3244651&rti=c051HQVbfRc4FEMbKg5RRVMzRU9KUBw%2fVBZHS0dPF1VIExNzJz0CGQtRcX8OS0o0CUkYRFJDDW8LEVRxGAEOEAcQXko%2bGgwSBBZrV1pQZgQZZxkWCA4L%7e%7e%7e",

which returns a JSON like that:

{
    "Streams": [
        {
            "StreamId": 3244651,
            "Reliability": 92,
            "Bandwidth": 64,
            "HasPlaylist": false,
            "MediaType": "MP3",
            "Url": "http://mp3hdfm32.hala.jo:8132",
            "Type": "Live"
        }
    ]
}

i believe that's the url you need: http://mp3hdfm32.hala.jo:8132

this is the station WebSite

executing shell command in background from script

Leave off the quotes

$cmd &
$othercmd &

eg:

nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash

cmd="ls -la"

$cmd &


nicholas@nick-win7 /tmp
$ ./test

nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root    0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx  1 nicholas None   35 2010-09-10 20:44 test
-rwxr-xr-x  1 nicholas None   41 2010-09-10 20:43 test~

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

My problem was fideloper proxy version.

when i upgraded laravel 5.5 to 5.8 this happened

just sharing if anybody get help

change you composer json fideloper version:

"fideloper/proxy": "^4.0",

After that you need to run update composer that's it.

composer update

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Java: How to set Precision for double value?

You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.

You will have to convert into a decimal radix, either via BigDecimal or DecimalFormat, depending on what you want to do with the value later.

See also my answer to this question for a refutation of the inevitable *100/100 answers.

How to create string with multiple spaces in JavaScript

With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:

let a = `something                 something`;

and to make multiline strings just press enter to create a new line, with no special characters:

let a = `something 

    
                         something`;

The results are exactly the same as you write in the string.

What is this date format? 2011-08-12T20:17:46.384Z

You can use the following example.

    String date = "2011-08-12T20:17:46.384Z";

    String inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

    String outputPattern = "yyyy-MM-dd HH:mm:ss";

    LocalDateTime inputDate = null;
    String outputDate = null;


    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);

    inputDate = LocalDateTime.parse(date, inputFormatter);
    outputDate = outputFormatter.format(inputDate);

    System.out.println("inputDate: " + inputDate);
    System.out.println("outputDate: " + outputDate);

How can I get query parameters from a URL in Vue.js?

More detailed answer to help the newbies of VueJS:

  • First define your router object, select the mode you seem fit. You can declare your routes inside the routes list.
  • Next you would want your main app to know router exists, so declare it inside the main app declaration .
  • Lastly they $route instance holds all the information about the current route. The code will console log just the parameter passed in the url. (*Mounted is similar to document.ready , .ie its called as soon as the app is ready)

And the code itself:

<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
    mode: 'history',
    routes: []
});
var vm =  new Vue({
    router,
    el: '#app',
    mounted: function() {
        q = this.$route.query.q
        console.log(q)
    },
});

Text Editor For Linux (Besides Vi)?

I agree with Mike, though I'm a Vim die-hard. I've been using GEdit quite frequently lately when I'm doing lightweight Ruby scripting. The standard editor (plus Ruby code snippets) is extremely usable and polished, and can provide a nice reprieve from full-strength, always-on programming editors.

printf not printing on console

Try setting this before you print:

setvbuf (stdout, NULL, _IONBF, 0);

Eclipse reported "Failed to load JNI shared library"

Yep, in Windows 7 64 bit you have C:\Program Files and C:\Program Files (x86). You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin to environment variable PATH.

C++ Pass A String

print(string ("Yo!"));

You need to make a (temporary) std::string object out of it.

How To Use DateTimePicker In WPF?

There is DatePicker in WPF Tool Kit, but I have not seen DateTime Picker in WPF ToolKit. So I don't know what kind of DateTimePicker control John is talking about.

When use ResponseEntity<T> and @RestController for Spring RESTful applications

According to official documentation: Creating REST Controllers with the @RestController annotation

@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

It seems that it's best to use @RestController for clarity, but you can also combine it with ResponseEntity for flexibility when needed (According to official tutorial and the code here and my question to confirm that).

For example:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    @ResponseStatus(HttpStatus.OK)
    public User test() {
        User user = new User();
        user.setName("Name 1");

        return user;
    }

}

is the same as:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    public ResponseEntity<User> test() {
        User user = new User();
        user.setName("Name 1");

        HttpHeaders responseHeaders = new HttpHeaders();
        // ...
        return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
    }

}

This way, you can define ResponseEntity only when needed.

Update

You can use this:

    return ResponseEntity.ok().headers(responseHeaders).body(user);

Run Executable from Powershell script with parameters

Try quoting the argument list:

Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"

You can also provide the argument list as an array (comma separated args) but using a string is usually easier.

Add newly created specific folder to .gitignore in Git

I'm incredibly lazy. I just did a search hoping to find a shortcut to this problem but didn't get an answer so I knocked this up.

~/bin/IGNORE_ALL

#!/bin/bash
# Usage: IGNORE_ALL <commit message>                                                                                                                             
git status --porcelain | grep '^??' | cut -f2 -d' ' >> .gitignore              
git commit -m "$*" .gitignore 

EG: IGNORE_ALL added stat ignores

This will just append all the ignore files to your .gitignore and commit. note you might want to add annotations to the file afterwards.

No input file specified

disabling PHP-FPM fixed my issue.

Converting DateTime format using razor

This is solution:

@item.Published.Value.ToString("dd. MM. yyyy")

Before ToString() use Value.

Class method decorator with self arguments?

Yes. Instead of passing in the instance attribute at class definition time, check it at runtime:

def check_authorization(f):
    def wrapper(*args):
        print args[0].url
        return f(*args)
    return wrapper

class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization
    def get(self):
        print 'get'

>>> Client('http://www.google.com').get()
http://www.google.com
get

The decorator intercepts the method arguments; the first argument is the instance, so it reads the attribute off of that. You can pass in the attribute name as a string to the decorator and use getattr if you don't want to hardcode the attribute name:

def check_authorization(attribute):
    def _check_authorization(f):
        def wrapper(self, *args):
            print getattr(self, attribute)
            return f(self, *args)
        return wrapper
    return _check_authorization

Array Size (Length) in C#

For a single dimension array, you use the Length property:

int size = theArray.Length;

For multiple dimension arrays the Length property returns the total number of items in the array. You can use the GetLength method to get the size of one of the dimensions:

int size0 = theArray.GetLength(0);

Node.js Hostname/IP doesn't match certificate's altnames

I had the same issue using the request module to proxy POST request from somewhere else and it was because I left the host property in the header (I was copying the header from the original request).

git: How to diff changed files versus previous versions after a pull?

There are all kinds of wonderful ways to specify commits - see the specifying revisions section of man git-rev-parse for more details. In this case, you probably want:

git diff HEAD@{1}

The @{1} means "the previous position of the ref I've specified", so that evaluates to what you had checked out previously - just before the pull. You can tack HEAD on the end there if you also have some changes in your work tree and you don't want to see the diffs for them.

I'm not sure what you're asking for with "the commit ID of my latest version of the file" - the commit "ID" (SHA1 hash) is that 40-character hex right at the top of every entry in the output of git log. It's the hash for the entire commit, not for a given file. You don't really ever need more - if you want to diff just one file across the pull, do

git diff HEAD@{1} filename

This is a general thing - if you want to know about the state of a file in a given commit, you specify the commit and the file, not an ID/hash specific to the file.

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

Check if a property exists in a class

This answers a different question:

If trying to figure out if an OBJECT (not class) has a property,

OBJECT.GetType().GetProperty("PROPERTY") != null

returns true if (but not only if) the property exists.

In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.

@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
        Model.AddTimeoffBlackouts)

helped me here.

Edit: Nowadays, it's probably smart to use the nameof operator instead of the stringified property name.

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

What is `related_name` used for in Django?

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

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

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

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

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

Cannot load properties file from resources directory

I believe running from Eclipse, if you're using "myconf.properties" as the relative path, You file structure should look somehting like this

ProjectRoot
         src
         bin
         myconf.properties

Eclipse will look for the the file in the project root dir if no other dirs are specified in the file path

Is there a way to iterate over a range of integers?

The problem is not the range, the problem is how the end of slice is calculated. with a fixed number 10 the simple for loop is ok but with a calculated size like bfl.Size() you get a function-call on every iteration. A simple range over int32 would help because this evaluate the bfl.Size() only once.

type BFLT PerfServer   
  func (this *BFLT) Call() {
    bfl := MqBufferLCreateTLS(0)                                                                                   
    for this.ReadItemExists() {                                                                                    
      bfl.AppendU(this.ReadU())                                                                                    
    }
    this.SendSTART()
    // size := bfl.Size() 
    for i := int32(0); i < bfl.Size() /* size */; i++ {                                                                             
      this.SendU(bfl.IndexGet(i))                                                                                  
    }
    this.SendRETURN()
  }

TortoiseSVN icons overlay not showing after updating to Windows 10

The following steps worked for me:

  1. TortoiseSVN -> Settings -> IconOverlays -> Icon Set
  2. Choose "Win10" icon set
  3. Restart computer.

Firebug like plugin for Safari browser

The Safari built in dev tool is great. I have to admit that Firebug on Firefox is my long time favorite, but I think that the Safari tool do a great job too!

What is a "web service" in plain English?

A web service differs from a web site in that a web service provides information consumable by software rather than humans. As a result, we are usually talking about exposed JSON, XML, or SOAP services.

Web services are a key component in "mashups". Mashups are when information from many websites is automatically aggregated into a new and useful service. For example, there are sites that aggregate Google Maps with information about police reports to give you a graphical representation of crime in your area. Another type of mashup would be to take real stock data provided by another site and combine it with a fake trading application to create a stock-market "game".

Web services are also used to provide news (see RSS), latest items added to a site, information on new products, podcasts, and other great features that make the modern web turn.

Hope this helps!

Swipe ListView item From right to left show delete button

An app is available that demonstrates a listview that combines both swiping-to-delete and dragging to reorder items. The code is based on Chet Haase's code for swiping-to-delete and Daniel Olshansky's code for dragging-to-reorder.

Chet's code deletes an item immediately. I improved on this by making it function more like Gmail where swiping reveals a bottom view that indicates that the item is deleted but provides an Undo button where the user has the possibility to undo the deletion. Chet's code also has a bug in it. If you have less items in the listview than the height of the listview is and you delete the last item, the last item appears to not be deleted. This was fixed in my code.

Daniel's code requires pressing long on an item. Many users find this unintuitive as it tends to be a hidden function. Instead, I modified the code to allow for a "Move" button. You simply press on the button and drag the item. This is more in line with the way the Google News app works when you reorder news topics.

The source code along with a demo app is available at: https://github.com/JohannBlake/ListViewOrderAndSwipe

Chet and Daniel are both from Google.

Chet's video on deleting items can be viewed at: https://www.youtube.com/watch?v=YCHNAi9kJI4

Daniel's video on reordering items can be viewed at: https://www.youtube.com/watch?v=_BZIvjMgH-Q

A considerable amount of work went into gluing all this together to provide a seemless UI experience, so I'd appreciate a Like or Up Vote. Please also star the project in Github.

Using PowerShell to remove lines from a text file if it contains a string

The pipe character | has a special meaning in regular expressions. a|b means "match either a or b". If you want to match a literal | character, you need to escape it:

... | Select-String -Pattern 'H\|159' -NotMatch | ...

How to add calendar events in Android?

Google calendar is the "native" calendar app. As far as I know, all phones come with a version of it installed, and the default SDK provides a version.

You might check out this tutorial for working with it.

How to convert SecureString to System.String?

Use the System.Runtime.InteropServices.Marshal class:

String SecureStringToString(SecureString value) {
  IntPtr valuePtr = IntPtr.Zero;
  try {
    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
    return Marshal.PtrToStringUni(valuePtr);
  } finally {
    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  }
}

If you want to avoid creating a managed string object, you can access the raw data using Marshal.ReadInt16(IntPtr, Int32):

void HandleSecureString(SecureString value) {
  IntPtr valuePtr = IntPtr.Zero;
  try {
    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
    for (int i=0; i < value.Length; i++) {
      short unicodeChar = Marshal.ReadInt16(valuePtr, i*2);
      // handle unicodeChar
    }
  } finally {
    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  }
}

Removing leading zeroes from a field in a SQL statement

select CASE
         WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0
           THEN ''
           ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)
       END

How do you make an array of structs in C?

Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.

Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:

typedef struct
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
}Body;

Then declare your array of structs. Initialization of each element goes along with the declaration:

Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};

To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.

How to replace all strings to numbers contained in each string in Notepad++?

In Notepad++ to replace, hit Ctrl+H to open the Replace menu.

Then if you check the "Regular expression" button and you want in your replacement to use a part of your matching pattern, you must use "capture groups" (read more on google). For example, let's say that you want to match each of the following lines

value="4"
value="403"
value="200"
value="201"
value="116"
value="15"

using the .*"\d+" pattern and want to keep only the number. You can then use a capture group in your matching pattern, using parentheses ( and ), like that: .*"(\d+)". So now in your replacement you can simply write $1, where $1 references to the value of the 1st capturing group and will return the number for each successful match. If you had two capture groups, for example (.*)="(\d+)", $1 will return the string value and $2 will return the number.

So by using:

Find: .*"(\d+)"

Replace: $1

It will return you

4
403
200
201
116
15

Please note that there many alternate and better ways of matching the aforementioned pattern. For example the pattern value="([0-9]+)" would be better, since it is more specific and you will be sure that it will match only these lines. It's even possible of making the replacement without the use of capture groups, but this is a slightly more advanced topic, so I'll leave it for now :)

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

Defining custom attrs

Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:

xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"

with:

xmlns:whatever="http://schemas.android.com/apk/res-auto"

Otherwise the application that uses the library will have runtime errors.

Android: adbd cannot run as root in production builds

For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root can run smoothly.

How to update array value javascript?

If you want to reassign an element in an array, you can do the following:

var blah = ['Jan', 'Fed', 'Apr'];

console.log(blah);

function reassign(array, index, newValue) {
    array[index] = newValue;
    return array;
}

reassign(blah, [2], 'Mar');

Why is Visual Studio 2013 very slow?

Did anybody find CodeLens (the reference counter) problems with startup performance?

Disable CodeLens (menu ToolsOptionstext editorAll languagesCodeLens)

Disable Git Source Control too (menu Tools* → OptionsSource control)

Select count(*) from result query

select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)

should works

'nuget' is not recognized but other nuget commands working

There are much nicer ways to do it.

  1. Install Nuget.Build package in you project that you want to pack. May need to close and re-open solution after install.
  2. Install nuget via chocolatey - much nicer. Install chocolatey: https://chocolatey.org/, then run

    cinst Nuget.CommandLine

in your command prompt. This will install nuget and setup environment paths, so nuget is always available.

How to kill all active and inactive oracle sessions for user

For Oracle 11g this may not work as you may receive an error like below

Error report:
SQL Error: ORA-00026: missing or invalid session ID
00026. 00000 -  "missing or invalid session ID"
*Cause:    Missing or invalid session ID string for ALTER SYSTEM KILL SESSION.
*Action:   Retry with a valid session ID.

To rectify this, use below code to identify the sessions

SQL> select inst_id,sid,serial# from gv$session or v$session

NOTE : v$session do not have inst_id field

and Kill them using

alter system kill session 'sid,serial,@inst_id' IMMEDIATE;

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

how to get 2 digits after decimal point in tsql?

Try this one -

DECLARE @i FLOAT = 6.677756

SELECT 
      ROUND(@i, 2)
    , FORMAT(@i, 'N2')
    , CAST(@i AS DECIMAL(18,2))
    , SUBSTRING(PARSENAME(CAST(@i AS VARCHAR(10)), 1), PATINDEX('%.%', CAST(@i AS VARCHAR(10))) - 1, 2)
    , FLOOR((@i - FLOOR(@i)) * 100)

Output:

----------------------
6,68
6.68
6.68
67
67

stopPropagation vs. stopImmediatePropagation

Here I am adding my JSfiddle example for stopPropagation vs stopImmediatePropagation. JSFIDDLE

_x000D_
_x000D_
let stopProp = document.getElementById('stopPropagation');_x000D_
let stopImmediate = document.getElementById('stopImmediatebtn');_x000D_
let defaultbtn = document.getElementById("defalut-btn");_x000D_
_x000D_
_x000D_
stopProp.addEventListener("click", function(event){_x000D_
 event.stopPropagation();_x000D_
  console.log('stopPropagation..')_x000D_
  _x000D_
})_x000D_
stopProp.addEventListener("click", function(event){_x000D_
  console.log('AnotherClick')_x000D_
  _x000D_
})_x000D_
stopImmediate.addEventListener("click", function(event){_x000D_
  event.stopImmediatePropagation();_x000D_
    console.log('stopimmediate')_x000D_
})_x000D_
_x000D_
stopImmediate.addEventListener("click", function(event){_x000D_
    console.log('ImmediateStop Another event wont work')_x000D_
})_x000D_
_x000D_
defaultbtn.addEventListener("click", function(event){_x000D_
    alert("Default Clik");_x000D_
})_x000D_
defaultbtn.addEventListener("click", function(event){_x000D_
    console.log("Second event defined will also work same time...")_x000D_
})
_x000D_
div{_x000D_
  margin: 10px;_x000D_
}
_x000D_
<p>_x000D_
The simple example for event.stopPropagation and stopImmediatePropagation?_x000D_
Please open console to view the results and click both button._x000D_
</p>_x000D_
<div >_x000D_
<button id="stopPropagation">_x000D_
stopPropagation-Button_x000D_
</button>_x000D_
</div>_x000D_
<div  id="grand-div">_x000D_
  <div class="new" id="parent-div">_x000D_
    <button id="stopImmediatebtn">_x000D_
    StopImmediate_x000D_
    </button>_x000D_
  </div>_x000D_
</div>_x000D_
<div>_x000D_
<button id="defalut-btn">_x000D_
Normat Button_x000D_
</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to downgrade php from 5.5 to 5.3

Long answer: it is possible!

  1. Temporarily rename existing xampp folder
  2. Install xampp 1.7.7 into xampp folder name
  3. Folder containing just installed 1.7.7 distribution rename to different name and previously existing xampp folder rename back just to xampp.
  4. In xampp folder rename php and apache folders to different names (I propose php_prev and apache_prev) so you can after switch back to them by renaming them back.
  5. Copy apache and php folders from folder with xampp 1.7.7 into xampp directory
  6. In xampp directory comment line apache/conf/httpd.conf:458

    #Include "conf/extra/httpd-perl.conf"

  7. In xampp directory do next replaces in files:

php/pci.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pci" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\php.exe" -f "%XAMPPPHPDIR%\pci" -- %*

php/pciconf.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pciconf" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\.\php.exe" -f "%XAMPPPHPDIR%\pciconf" -- %*

php/pear.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/peardev.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/pecl.bat:32

from

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php\" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/phar.phar.bat:1

from

%~dp0php.exe %~dp0pharcommand.phar %*

to

"%~dp0php.exe" "%~dp0pharcommand.phar" %*

Enjoy new XAMPP with PHP 5.3

Checked by myself in XAMPP 5.6.31, 7.0.15 & 7.1.1 with XAMPP Control Panel v3.2.2

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

phpmailer error "Could not instantiate mail function"

Your code looks good, did you forget to install PostFix on your server?

sudo apt-get install postfix

It worked for me ;)

Cheers

Passing an array as parameter in JavaScript

Just remove the .value, like this:

function(arrayP){    
   for(var i = 0; i < arrayP.length; i++){
      alert(arrayP[i]);    //no .value here
   }
}

Sure you can pass an array, but to get the element at that position, use only arrayName[index], the .value would be getting the value property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value would also be undefined.

java.util.NoSuchElementException: No line found

For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine() method before each call to nextLine(), make sure the correct encoding is passed to the Scanner constructor, e.g.:

Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");

batch to copy files with xcopy

After testing most of the switches this worked for me:

xcopy C:\folder1 C:\folder2\folder1 /t /e /i /y

This will copy the folder folder1 into the folder folder2. So the directory tree would look like:

C:
   Folder1
   Folder2
      Folder1

How to open a specific port such as 9090 in Google Compute Engine

Here is the command-line approach to answer this question:

gcloud compute firewall-rules create <rule-name> --allow tcp:9090 --source-tags=<list-of-your-instances-names> --source-ranges=0.0.0.0/0 --description="<your-description-here>"

This will open the port 9090 for the instances that you name. Omitting --source-tags and --source-ranges will apply the rule to all instances. More details are in the Gcloud documentation and the firewall-rule create command manual

The previous answers are great, but Google recommends using the newer gcloud commands instead of the gcutil commands.

PS: To get an idea of Google's firewall rules, run gcloud compute firewall-rules list and view all your firewall rules

Mysql - How to quit/exit from stored procedure

This works for me :

 CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
IN bus_fun_temp_id int  , OUT o_message VARCHAR (50) ,
            OUT o_number INT )
 BEGIN

DECLARE  v_pkg_name  varchar(50) ;

DECLARE  v_pkg_temp_id  int(10)  ; 

DECLARE  v_workflow_count INT(10);

-- checking if workflow created for package
select count(*)  INTO v_workflow_count from workflow w where w.package_id = 
package_id ;

this_proc:BEGIN   -- this_proc block start here 

 IF  v_workflow_count = 0 THEN
   select 'no work flow ' as 'workflow_status' ;
    SET o_message ='Work flow is not created for this package.';
    SET  o_number = -2 ;
      LEAVE this_proc;
 END IF;

select 'work flow  created ' as 'workflow_status' ;
-- To  send some message
SET o_message ='SUCCESSFUL';
SET  o_number = 1 ;

  END ;-- this_proc block end here 

END

How do I drop a foreign key constraint only if it exists in sql server?

ALTER TABLE [dbo].[TableName]
    DROP CONSTRAINT FK_TableName_TableName2

Ruby class instance variable vs. class variable

As others said, class variables are shared between a given class and its subclasses. Class instance variables belong to exactly one class; its subclasses are separate.

Why does this behavior exist? Well, everything in Ruby is an object—even classes. That means that each class has an object of the class Class (or rather, a subclass of Class) corresponding to it. (When you say class Foo, you're really declaring a constant Foo and assigning a class object to it.) And every Ruby object can have instance variables, so class objects can have instance variables, too.

The trouble is, instance variables on class objects don't really behave the way you usually want class variables to behave. You usually want a class variable defined in a superclass to be shared with its subclasses, but that's not how instance variables work—the subclass has its own class object, and that class object has its own instance variables. So they introduced separate class variables with the behavior you're more likely to want.

In other words, class instance variables are sort of an accident of Ruby's design. You probably shouldn't use them unless you specifically know they're what you're looking for.

Submitting the value of a disabled input field

Input elements have a property called disabled. When the form submits, just run some code like this:

var myInput = document.getElementById('myInput');
myInput.disabled = true;

Redirect from an HTML page

You can auto redirect by HTTP Status Code 301 or 302.

For PHP:

<?php
    Header("HTTP/1.1 301 Moved Permanently");
    Header("Location: http://www.redirect-url.com");
?>

Image resolution for new iPhone 6 and 6+, @3x support added?

I've tried in a sample project to use standard, @2x and @3x images, and the iPhone 6+ simulator uses the @3x image. So it would seem that there are @3x images to be done (if the simulator actually replicates the device's behavior). But the strange thing is that all devices (simulators) seem to use this @3x image when it's on the project structure, iPhone 4S/iPhone 5 too.
The lack of communication from Apple on a potential @3x structure, while they ask developers to publish their iOS8 apps is quite confusing, especially when seeing those results on simulator.

**Edit from Apple's Website **: Also found this on the "What's new on iOS 8" section on Apple's developer space :

Support for a New Screen Scale The iPhone 6 Plus uses a new Retina HD display with a screen scale of 3.0. To provide the best possible experience on these devices, include new artwork designed for this screen scale. In Xcode 6, asset catalogs can include images at 1x, 2x, and 3x sizes; simply add the new image assets and iOS will choose the correct assets when running on an iPhone 6 Plus. The image loading behavior in iOS also recognizes an @3x suffix.

Still not understanding why all devices seem to load the @3x. Maybe it's because I'm using regular files and not xcassets ? Will try soon.

Edit after further testing : Ok it seems that iOS8 has a talk in this. When testing on an iOS 7.1 iPhone 5 simulator, it uses correctly the @2x image. But when launching the same on iOS 8 it uses the @3x on iPhone 5. Not sure if that's a wanted behavior or a mistake/bug in iOS8 GM or simulators in Xcode 6 though.

Angular directives - when and how to use compile, controller, pre-link and post-link

Post-link function

When the post-link function is called, all previous steps have taken place - binding, transclusion, etc.

This is typically a place to further manipulate the rendered DOM.

Do:

  • Manipulate DOM (rendered, and thus instantiated) elements.
  • Attach event handlers.
  • Inspect child elements.
  • Set up observations on attributes.
  • Set up watches on the scope.

Replace all 0 values to NA

Replacing all zeroes to NA:

df[df == 0] <- NA



Explanation

1. It is not NULL what you should want to replace zeroes with. As it says in ?'NULL',

NULL represents the null object in R

which is unique and, I guess, can be seen as the most uninformative and empty object.1 Then it becomes not so surprising that

data.frame(x = c(1, NULL, 2))
#   x
# 1 1
# 2 2

That is, R does not reserve any space for this null object.2 Meanwhile, looking at ?'NA' we see that

NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw.

Importantly, NA is of length 1 so that R reserves some space for it. E.g.,

data.frame(x = c(1, NA, 2))
#    x
# 1  1
# 2 NA
# 3  2

Also, the data frame structure requires all the columns to have the same number of elements so that there can be no "holes" (i.e., NULL values).

Now you could replace zeroes by NULL in a data frame in the sense of completely removing all the rows containing at least one zero. When using, e.g., var, cov, or cor, that is actually equivalent to first replacing zeroes with NA and setting the value of use as "complete.obs". Typically, however, this is unsatisfactory as it leads to extra information loss.

2. Instead of running some sort of loop, in the solution I use df == 0 vectorization. df == 0 returns (try it) a matrix of the same size as df, with the entries TRUE and FALSE. Further, we are also allowed to pass this matrix to the subsetting [...] (see ?'['). Lastly, while the result of df[df == 0] is perfectly intuitive, it may seem strange that df[df == 0] <- NA gives the desired effect. The assignment operator <- is indeed not always so smart and does not work in this way with some other objects, but it does so with data frames; see ?'<-'.


1 The empty set in the set theory feels somehow related.
2 Another similarity with the set theory: the empty set is a subset of every set, but we do not reserve any space for it.

Using CSS to affect div style inside iframe

Yes, it's possible although cumbersome. You would need to print/echo the HTML of the page into the body of your page then apply a CSS rule change function. Using the same examples given above, you would essentially be using a parsing method of finding the divs in the page, and then applying the CSS to it and then reprinting/echoing it out to the end user. I don't need this so I don't want to code that function into every item in the CSS of another webpage just to aphtply.

References:

Execute multiple command lines with the same process using .NET

You could also tell MySQL to execute the commands in the given file, like so:

mysql --user=root --password=sa casemanager < CaseManager.sql

Returning a stream from File.OpenRead()

Try changing your code to this:

private void Test()
{            
    System.IO.MemoryStream data = new System.IO.MemoryStream(TestStream());

    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);                       
}

Compare dates in MySQL

I got the answer.

Here is the code:

SELECT * FROM table
WHERE STR_TO_DATE(column, '%d/%m/%Y')
  BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
    AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

White space showing up on right side of page when background image should extend full length of page

Debug your CSS for Ghost CSS Elements.

Use this bookmark to debug your CSS: https://blog.wernull.com/2013/04/debug-ghost-css-elements-causing-unwanted-scrolling/

Or add the CSS directly yourself:

* {
  background: #000 !important;
  color: #0f0 !important;
  outline: solid #f00 1px !important;
}

In my case a Facebook Like Button caused the problem.

Tracking changes in Windows registry

A straightforward way to do this with no extra tools is to export the registry to a text file before the install, then export it to another file after. Then, compare the two files.

Having said that, the Sysinternals tools are great for this.

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

In my case I had to enable virtualization in the BIOS setting.

  1. Restart PC
  2. While you are on the 'restart' screen press any of these keys and you enter the bios settings in windows: esc, f1, f2, f3, f4, f8 or delete
  3. For intel based systems:
    • press f7 (advanced mode)
    • go to advanced
    • cpa configuration
    • enable virtualization

And after all above steps, it finally works :-)

Why .NET String is immutable?

  1. Instances of immutable types are inherently thread-safe, since no thread can modify it, the risk of a thread modifying it in a way that interferes with another is removed (the reference itself is a different matter).
  2. Similarly, the fact that aliasing can't produce changes (if x and y both refer to the same object a change to x entails a change to y) allows for considerable compiler optimisations.
  3. Memory-saving optimisations are also possible. Interning and atomising being the most obvious examples, though we can do other versions of the same principle. I once produced a memory saving of about half a GB by comparing immutable objects and replacing references to duplicates so that they all pointed to the same instance (time-consuming, but a minute's extra start-up to save a massive amount of memory was a performance win in the case in question). With mutable objects that can't be done.
  4. No side-effects can come from passing an immutable type as a method to a parameter unless it is out or ref (since that changes the reference, not the object). A programmer therefore knows that if string x = "abc" at the start of a method, and that doesn't change in the body of the method, then x == "abc" at the end of the method.
  5. Conceptually, the semantics are more like value types; in particular equality is based on state rather than identity. This means that "abc" == "ab" + "c". While this doesn't require immutability, the fact that a reference to such a string will always equal "abc" throughout its lifetime (which does require immutability) makes uses as keys where maintaining equality to previous values is vital, much easier to ensure correctness of (strings are indeed commonly used as keys).
  6. Conceptually, it can make more sense to be immutable. If we add a month onto Christmas, we haven't changed Christmas, we have produced a new date in late January. It makes sense therefore that Christmas.AddMonths(1) produces a new DateTime rather than changing a mutable one. (Another example, if I as a mutable object change my name, what has changed is which name I am using, "Jon" remains immutable and other Jons will be unaffected.
  7. Copying is fast and simple, to create a clone just return this. Since the copy can't be changed anyway, pretending something is its own copy is safe.
  8. [Edit, I'd forgotten this one]. Internal state can be safely shared between objects. For example, if you were implementing list which was backed by an array, a start index and a count, then the most expensive part of creating a sub-range would be copying the objects. However, if it was immutable then the sub-range object could reference the same array, with only the start index and count having to change, with a very considerable change to construction time.

In all, for objects which don't have undergoing change as part of their purpose, there can be many advantages in being immutable. The main disadvantage is in requiring extra constructions, though even here it's often overstated (remember, you have to do several appends before StringBuilder becomes more efficient than the equivalent series of concatenations, with their inherent construction).

It would be a disadvantage if mutability was part of the purpose of an object (who'd want to be modeled by an Employee object whose salary could never ever change) though sometimes even then it can be useful (in a many web and other stateless applications, code doing read operations is separate from that doing updates, and using different objects may be natural - I wouldn't make an object immutable and then force that pattern, but if I already had that pattern I might make my "read" objects immutable for the performance and correctness-guarantee gain).

Copy-on-write is a middle ground. Here the "real" class holds a reference to a "state" class. State classes are shared on copy operations, but if you change the state, a new copy of the state class is created. This is more often used with C++ than C#, which is why it's std:string enjoys some, but not all, of the advantages of immutable types, while remaining mutable.

Regex doesn't work in String.matches()

You can make your pattern case insensitive by doing:

Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);

npm ERR! Error: EPERM: operation not permitted, rename

I did the following:

  1. Upgraded the npm to the latest version: npm install -g [email protected]
  2. deleted the npm-cache folder from: c:/users/[username]/AppData/Roaming/npm-cache
  3. Did cache clean : npm cache clean --force
  4. Ran the npm install.

How to pass a form input value into a JavaScript function

There are several ways to approach this. Personally, I would avoid in-line scripting. Since you've tagged jQuery, let's use that.

HTML:

<form>
    <input type="text" id="formValueId" name="valueId"/>
    <input type="button" id="myButton" />
</form>

JavaScript:

$(document).ready(function() {
    $('#myButton').click(function() {
      foo($('#formValueId').val());
    });
});

How to iterate for loop in reverse order in swift?

If one is wanting to iterate through an array (Array or more generally any SequenceType) in reverse. You have a few additional options.

First you can reverse() the array and loop through it as normal. However I prefer to use enumerate() much of the time since it outputs a tuple containing the object and it's index.

The one thing to note here is that it is important to call these in the right order:

for (index, element) in array.enumerate().reverse()

yields indexes in descending order (which is what I generally expect). whereas:

for (index, element) in array.reverse().enumerate() (which is a closer match to NSArray's reverseEnumerator)

walks the array backward but outputs ascending indexes.

Invalid application of sizeof to incomplete type with a struct

It means the file containing main doesn't have access to the player structure definition (i.e. doesn't know what it looks like).

Try including it in header.h or make a constructor-like function that allocates it if it's to be an opaque object.

EDIT

If your goal is to hide the implementation of the structure, do this in a C file that has access to the struct:

struct player *
init_player(...)
{
    struct player *p = calloc(1, sizeof *p);

    /* ... */
    return p;
}

However if the implementation shouldn't be hidden - i.e. main should legally say p->canPlay = 1 it would be better to put the definition of the structure in header.h.

XML Document to String

First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().

print spaces with String.format()

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

c# dictionary How to add multiple values for single key?

Use NameValuedCollection.

Good starting point is here. Straight from the link.

System.Collections.Specialized.NameValueCollection myCollection
    = new System.Collections.Specialized.NameValueCollection();

  myCollection.Add(“Arcane”, “http://arcanecode.com”);
  myCollection.Add(“PWOP”, “http://dotnetrocks.com”);
  myCollection.Add(“PWOP”, “http://dnrtv.com”);
  myCollection.Add(“PWOP”, “http://www.hanselminutes.com”);
  myCollection.Add(“TWIT”, “http://www.twit.tv”);
  myCollection.Add(“TWIT”, “http://www.twit.tv/SN”);

How to make the script wait/sleep in a simple way in unity

You were correct to use WaitForSeconds. But I suspect that you tried using it without coroutines. That's how it should work:

public void SomeMethod()
{
    StartCoroutine(SomeCoroutine());
}

private IEnumerator SomeCoroutine()
{
    TextUI.text = "Welcome to Number Wizard!";
    yield return new WaitForSeconds (3);
    TextUI.text = ("The highest number you can pick is " + max);
    yield return new WaitForSeconds (3);
    TextUI.text = ("The lowest number you can pick is " + min);
}

How to get the date from jQuery UI datepicker

You can retrieve the date by using the getDate function:

$("#datepicker").datepicker( 'getDate' );

The value is returned as a JavaScript Date object.

If you want to use this value when the user selects a date, you can use the onSelect event:

$("#datepicker").datepicker({
   onSelect: function(dateText, inst) { 
      var dateAsString = dateText; //the first parameter of this function
      var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
   }
});

The first parameter is in this case the selected Date as String. Use parseDate to convert it to a JS Date Object.

See http://docs.jquery.com/UI/Datepicker for the full jQuery UI DatePicker reference.

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

Looks like the mysql server is not started.

Look to the official documentation of MySQL how you can start a service under windows.

Install the server as a service using this command: C:> "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --install

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

For me, none of the solutions work. I had to download the XCode from the App store. It's too big around 12 GB. After installing it works like a charm.

How to insert data to MySQL having auto incremented primary key?

Set the auto increment field to NULL or 0 if you want it to be auto magically assigned...

Log4j2 configuration - No log4j2 configuration file found

In my case I had to put it in the bin folder of my project even the fact that my classpath is set to the src folder. I have no idea why, but it's worth a try.

Google maps API V3 method fitBounds()

This happens because LatLngBounds() does not take two arbitrary points as parameters, but SW and NE points

use the .extend() method on an empty bounds object

var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);

Demo at http://jsfiddle.net/gaby/22qte/

Check that a variable is a number in UNIX shell

Shell variables have no type, so the simplest way is to use the return type test command:

if [ $var -eq $var 2> /dev/null ]; then ...

(Or else parse it with a regexp)

How do I make a MySQL database run completely in memory?

It is also possible to place the MySQL data directory in a tmpfs in thus speeding up the database write and read calls. It might not be the most efficient way to do this but sometimes you can't just change the storage engine.

Here is my fstab entry for my MySQL data directory

none            /opt/mysql/server-5.6/data  tmpfs   defaults,size=1000M,uid=999,gid=1000,mode=0700          0       0

You may also want to take a look at the innodb_flush_log_at_trx_commit=2 setting. Maybe this will speedup your MySQL sufficently.

innodb_flush_log_at_trx_commit changes the mysql disk flush behaviour. When set to 2 it will only flush the buffer every second. By default each insert will cause a flush and thus cause more IO load.

How to use "not" in xpath?

not() is a function in xpath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

Adding days to $Date in PHP

You can also use the following format

strtotime("-3 days", time());
strtotime("+1 day", strtotime($date));

You can stack changes this way:

strtotime("+1 day", strtotime("+1 year", strtotime($date)));

Note the difference between this approach and the one in other answers: instead of concatenating the values +1 day and <timestamp>, you can just pass in the timestamp as the second parameter of strtotime.

Print commit message of a given commit in git

git show is more a plumbing command than git log, and has the same formatting options:

git show -s --format=%B SHA1

How to pass parameters to ThreadStart method in Thread?

In Additional

    Thread thread = new Thread(delegate() { download(i); });
    thread.Start();

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

How to use code to open a modal in Angular 2?

The below answer is in reference to the latest ng-bootstrap

Install

npm install --save @ng-bootstrap/ng-bootstrap

app.module.ts

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...

    NgbModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Component Controller

import { TemplateRef, ViewChild } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-app-registration',
  templateUrl: './app-registration.component.html',
  styleUrls: ['./app-registration.component.css']
})

export class AppRegistrationComponent implements OnInit {

  @ViewChild('editModal') editModal : TemplateRef<any>; // Note: TemplateRef

  constructor(private modalService: NgbModal) { }

  openModal(){
    this.modalService.open(this.editModal);
  }

}

Component HTML

<ng-template #editModal let-modal>

<div class="modal-header">
  <h4 class="modal-title" id="modal-basic-title">Edit Form</h4>
  <button type="button" class="close" aria-label="Close" (click)="modal.dismiss()">
    <span aria-hidden="true">&times;</span>
  </button>
</div>

<div class="modal-body">
  
  <form>
    <div class="form-group">
      <label for="dateOfBirth">Date of birth</label>
      <div class="input-group">
        <input id="dateOfBirth" class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #dp="ngbDatepicker">
        <div class="input-group-append">
          <button class="btn btn-outline-secondary calendar" (click)="dp.toggle()" type="button"></button>
        </div>
      </div>
    </div>
  </form>

</div>

<div class="modal-footer">
  <button type="button" class="btn btn-outline-dark" (click)="modal.close()">Save</button>
</div>

</ng-template>

JetBrains / IntelliJ keyboard shortcut to collapse all methods

The above suggestion of Ctrl+Shift+- code folds all code blocks recursively. I only wanted to fold the methods for my classes.

Code > Folding > Expand all to level > 1

I managed to achieve this by using the menu option Code > Folding > Expand all to level > 1.

I re-assigned it to Ctrl+NumPad-1 which gives me a quick way to collapse my classes down to their methods.

This works at the 'block level' of the file and assumes that you have classes defined at the top level of your file, which works for code such as PHP but not for JavaScript (nested closures etc.)

Confirm deletion using Bootstrap 3 modal box

enter image description here Following solution is better than bootbox.js, because

  • It can do everything bootbox.js can do;
  • The use syntax is simpler
  • It allows you to elegantly control the color of your message using "error", "warning" or "info"
  • Bootbox is 986 lines long, mine only 110 lines long

digimango.messagebox.js:

_x000D_
_x000D_
const dialogTemplate = '\_x000D_
    <div class ="modal" id="digimango_messageBox" role="dialog">\_x000D_
        <div class ="modal-dialog">\_x000D_
            <div class ="modal-content">\_x000D_
                <div class ="modal-body">\_x000D_
                    <p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\_x000D_
                    <p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\_x000D_
                </div>\_x000D_
                <div class ="modal-footer">\_x000D_
                    <button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\_x000D_
                    <button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\_x000D_
                </div>\_x000D_
            </div>\_x000D_
        </div>\_x000D_
    </div>';_x000D_
_x000D_
_x000D_
// See the comment inside function digimango_onOkClick(event) {_x000D_
var digimango_numOfDialogsOpened = 0;_x000D_
_x000D_
_x000D_
function messageBox(msg, significance, options, actionConfirmedCallback) {_x000D_
    if ($('#digimango_MessageBoxContainer').length == 0) {_x000D_
        var iDiv = document.createElement('div');_x000D_
        iDiv.id = 'digimango_MessageBoxContainer';_x000D_
        document.getElementsByTagName('body')[0].appendChild(iDiv);_x000D_
        $("#digimango_MessageBoxContainer").html(dialogTemplate);_x000D_
    }_x000D_
_x000D_
    var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;_x000D_
_x000D_
    if (options == null) {_x000D_
        okButtonName = 'OK';_x000D_
        cancelButtonName = null;_x000D_
        showTextBox = null;_x000D_
        textBoxDefaultText = null;_x000D_
    } else {_x000D_
        okButtonName = options.okButtonName;_x000D_
        cancelButtonName = options.cancelButtonName;_x000D_
        showTextBox = options.showTextBox;_x000D_
        textBoxDefaultText = options.textBoxDefaultText;_x000D_
    }_x000D_
_x000D_
    if (showTextBox == true) {_x000D_
        if (textBoxDefaultText == null)_x000D_
            $('#digimango_messageBoxTextArea').val('');_x000D_
        else_x000D_
            $('#digimango_messageBoxTextArea').val(textBoxDefaultText);_x000D_
_x000D_
        $('#digimango_messageBoxTextArea').show();_x000D_
    }_x000D_
    else_x000D_
        $('#digimango_messageBoxTextArea').hide();_x000D_
_x000D_
    if (okButtonName != null)_x000D_
        $('#digimango_messageBoxOkButton').html(okButtonName);_x000D_
    else_x000D_
        $('#digimango_messageBoxOkButton').html('OK');_x000D_
_x000D_
    if (cancelButtonName == null)_x000D_
        $('#digimango_messageBoxCancelButton').hide();_x000D_
    else {_x000D_
        $('#digimango_messageBoxCancelButton').show();_x000D_
        $('#digimango_messageBoxCancelButton').html(cancelButtonName);_x000D_
    }_x000D_
_x000D_
    $('#digimango_messageBoxOkButton').unbind('click');_x000D_
    $('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);_x000D_
_x000D_
    $('#digimango_messageBoxCancelButton').unbind('click');_x000D_
    $('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);_x000D_
_x000D_
    var content = $("#digimango_messageBoxMessage");_x000D_
_x000D_
    if (significance == 'error')_x000D_
        content.attr('class', 'text-danger');_x000D_
    else if (significance == 'warning')_x000D_
        content.attr('class', 'text-warning');_x000D_
    else_x000D_
        content.attr('class', 'text-success');_x000D_
_x000D_
    content.html(msg);_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $("#digimango_messageBox").modal();_x000D_
_x000D_
    digimango_numOfDialogsOpened++;_x000D_
}_x000D_
_x000D_
function digimango_onOkClick(event) {_x000D_
    // JavaScript's nature is unblocking. So the function call in the following line will not block,_x000D_
    // thus the last line of this function, which is to hide the dialog, is executed before user_x000D_
    // clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count_x000D_
    // how many dialogs is currently showing. If we know there is still a dialog being shown, we do_x000D_
    // not execute the last line in this function._x000D_
    if (typeof (event.data.callback) != 'undefined')_x000D_
        event.data.callback($('#digimango_messageBoxTextArea').val());_x000D_
_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}_x000D_
_x000D_
function digimango_onCancelClick() {_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}
_x000D_
_x000D_
_x000D_

To use digimango.messagebox.js:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title>A useful generic message box</title>_x000D_
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />_x000D_
_x000D_
    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />_x000D_
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootstrap.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootbox.js" type="text/javascript"></script>_x000D_
_x000D_
    <script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
    <script type="text/javascript">_x000D_
        function testAlert() {_x000D_
            messageBox('Something went wrong!', 'error');_x000D_
        }_x000D_
_x000D_
        function testAlertWithCallback() {_x000D_
            messageBox('Something went wrong!', 'error', null, function () {_x000D_
                messageBox('OK clicked.');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testConfirm() {_x000D_
            messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {_x000D_
                messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPrompt() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPromptWithDefault() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
    </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <a href="#" onclick="testAlert();">Test alert</a> <br/>_x000D_
    <a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />_x000D_
    <a href="#" onclick="testConfirm();">Test confirm</a> <br/>_x000D_
    <a href="#" onclick="testPrompt();">Test prompt</a><br />_x000D_
    <a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Most popular screen sizes/resolutions on Android phones

Also, their "device dashboard" stats at:

http://developer.android.com/about/dashboards/index.html#Screens

can be pretty helpful. They are current and derived from Android Market visits.

How to set DateTime to null

You can write DateTime? newdate = null;

Increase max execution time for php

Add these lines of code in your htaccess file. I hope it will solve your problem.

<IfModule mod_php5.c>
php_value max_execution_time 259200
</IfModule>

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

Why can't variables be declared in a switch statement?

You can't do this, because case labels are actually just entry points into the containing block.

This is most clearly illustrated by Duff's device. Here's some code from Wikipedia:

strcpy(char *to, char *from, size_t count) {
    int n = (count + 7) / 8;
    switch (count % 8) {
    case 0: do { *to = *from++;
    case 7:      *to = *from++;
    case 6:      *to = *from++;
    case 5:      *to = *from++;
    case 4:      *to = *from++;
    case 3:      *to = *from++;
    case 2:      *to = *from++;
    case 1:      *to = *from++;
               } while (--n > 0);
    }
}

Notice how the case labels totally ignore the block boundaries. Yes, this is evil. But this is why your code example doesn't work. Jumping to a case label is the same as using goto, so you aren't allowed to jump over a local variable with a constructor.

As several other posters have indicated, you need to put in a block of your own:

switch (...) {
    case FOO: {
        MyObject x(...);
        ...
        break; 
    }
    ...
 }

QUERY syntax using cell reference

Copied from Web Applications:

=QUERY(Responses!B1:I, "Select B where G contains '"&$B1&"'")

TSQL How do you output PRINT in a user defined function?

No, you can not.

You can call a function from a stored procedure and debug a stored procedure (this will step into the function)

jQuery - How to dynamically add a validation rule

The documentation says:

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is,

> $("form").validate() is called first.

Did you do that? The error message kind of indicates that you didn't.

Get a timestamp in C in microseconds?

You have two choices for getting a microsecond timestamp. The first (and best) choice, is to use the timeval type directly:

struct timeval GetTimeStamp() {
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv;
}

The second, and for me less desirable, choice is to build a uint64_t out of a timeval:

uint64_t GetTimeStamp() {
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv.tv_sec*(uint64_t)1000000+tv.tv_usec;
}

bootstrap datepicker setDate format dd/mm/yyyy

Changing to format: 'dd/mm/yyyy' didn't work for me, and changing that to dateFormat: 'dd/mm/yyyy' added year multiple times, The finest one for me was,

dateFormat: 'dd/mm/yy'

How do I raise the same Exception with a custom message in Python?

Try below:

try:
    raise ValueError("Original message. ")
except Exception as err:
    message = 'My custom error message. '
    # Change the order below to "(message + str(err),)" if custom message is needed first. 
    err.args = (str(err) + message,)
    raise 

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
      1 try:
----> 2     raise ValueError("Original message")
      3 except Exception as err:
      4     message = 'My custom error message.'
      5     err.args = (str(err) + ". " + message,)

ValueError: Original message. My custom error message.

python BeautifulSoup parsing table

Updated Answer

If a programmer is interested in only parsing a table from a webpage, they can utilize the pandas method pandas.read_html.

Let's say we want to extract the GDP data table from the website: https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries

Then following codes does the job perfectly (No need of beautifulsoup and fancy html):

import pandas as pd
import requests

url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"

r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
df = df_list[0]
df.head()

Output

First five lines of the table from the Website

Downloading and unzipping a .zip file without writing to disk

Below is a code snippet I used to fetch zipped csv file, please have a look:

Python 2:

from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen

resp = urlopen("http://www.test.com/file.zip")
zipfile = ZipFile(StringIO(resp.read()))
for line in zipfile.open(file).readlines():
    print line

Python 3:

from io import BytesIO
from zipfile import ZipFile
from urllib.request import urlopen
# or: requests.get(url).content

resp = urlopen("http://www.test.com/file.zip")
zipfile = ZipFile(BytesIO(resp.read()))
for line in zipfile.open(file).readlines():
    print(line.decode('utf-8'))

Here file is a string. To get the actual string that you want to pass, you can use zipfile.namelist(). For instance,

resp = urlopen('http://mlg.ucd.ie/files/datasets/bbc.zip')
zipfile = ZipFile(BytesIO(resp.read()))
zipfile.namelist()
# ['bbc.classes', 'bbc.docs', 'bbc.mtx', 'bbc.terms']

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

DELETE TB1, TB2
    FROM customer_details
        LEFT JOIN customer_booking on TB1.cust_id = TB2.fk_cust_id
    WHERE TB1.cust_id = $id

caching JavaScript files

The best (and only) method is to set correct HTTP headers, specifically these ones: "Expires", "Last-Modified", and "Cache-Control". How to do it depends on the server software you use.

In Improving performance… look for "Optimization on server side" for general considerations and relevant links and for "Client-side cache" for the Apache-specific advice.

If you are a fan of nginx (or nginx in plain English) like I am, you can easily configure it too:

location /images {
  ...
  expires 4h;
}

In the example above any file from /images/ will be cached on the client for 4 hours.

Now when you know right words to look for (HTTP headers "Expires", "Last-Modified", and "Cache-Control"), just peruse the documentation of the web server you use.

How do I order my SQLITE database in descending order, for an android app?

SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns. Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");

SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(
            TABLE_NAME,
            rank,
            null,
            null,
            null,
            null,
            COLUMN + " DESC",
            null);

Mac install and open mysql using terminal

In MacOS, Mysql's executable file is located in /usr/local/mysql/bin/mysql and you can easily login to it with the following command:

/usr/local/mysql/bin/mysql -u USERNAME -p

But this is a very long command and very boring, so you can add mysql path to Os's Environment variable and access to it much easier.

For macOS Catalina and later

Starting with macOS Catalina, Mac devices use zsh as the default login shell and interactive shell and you have to update .zprofile file in your home directory.

echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.zprofile
source ~/.zprofile
mysql -u USERNAME -p

For macOS Mojave and earlier

Although you can always switch to zsh, bash is the default shell in macOS Mojave and earlier and with bash you have to update .bash_profile file.

echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.bash_profile
source ~/.bash_profile
mysql -u USERNAME -p

WampServer orange icon

  • go to C:\wamp\bin\mysql\mysql5.6.17
  • look for "my.ini"; right click to edit it
    • use your favorite editor (notepad++, jedit…)
  • look for 3306 and change it to 3307
  • restart all the services and it should work :)

How to list only files and not directories of a directory Bash?

Using find:

find . -maxdepth 1 -type f

Using the -maxdepth 1 option ensures that you only look in the current directory (or, if you replace the . with some path, that directory). If you want a full recursive listing of all files in that and subdirectories, just remove that option.

JPA CascadeType.ALL does not delete orphans

If you are using JPA with EclipseLink, you'll have to set the @PrivateOwned annotation.

Documentation: Eclipse Wiki - Using EclipseLink JPA Extensions - Chapter 1.4 How to Use the @PrivateOwned Annotation

Is there a way to specify a default property value in Spring XML?

http://thiamteck.blogspot.com/2008/04/spring-propertyplaceholderconfigurer.html points out that "local properties" defined on the bean itself will be considered defaults to be overridden by values read from files:

<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  <property name="location"><value>my_config.properties</value></property>  
  <property name="properties">  
    <props>  
      <prop key="entry.1">123</prop>  
    </props>  
  </property>  
</bean> 

Cannot delete or update a parent row: a foreign key constraint fails

You could create a trigger to delete the referenced rows in before deleting the job.

    DELIMITER $$
    CREATE TRIGGER before_jobs_delete 
        BEFORE DELETE ON jobs
        FOR EACH ROW 
    BEGIN
        delete from advertisers where advertiser_id=OLD.advertiser_id;
    END$$
    DELIMITER ;

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

JSONObject obj=(JSONObject)JSONValue.parse(content); 
JSONArray arr=(JSONArray)obj.get("units"); 
System.out.println(arr.get(1));  //this will print {"id":42,...sities ..}

@cyberz is right but explain it reverse

Why would one use nested classes in C++?

Nested classes are cool for hiding implementation details.

List:

class List
{
    public:
        List(): head(nullptr), tail(nullptr) {}
    private:
        class Node
        {
              public:
                  int   data;
                  Node* next;
                  Node* prev;
        };
    private:
        Node*     head;
        Node*     tail;
};

Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.

Look at std::list or std::map they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list.

How to create a 100% screen width div inside a container in bootstrap?

2019's answer as this is still actively seen today

You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.

original hack from 2015 that still works in some situations

You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.

If you cannot pull it out of the div for some reason, you should change the position style with this css:

.full-width-div {
    position: absolute;
    width: 100%;
    left: 0;
}

Instead of absolute, you could also use fixed, but then it will not move as you scroll.

ExtJs Gridpanel store refresh

Combination of Dasha's and MMT solutions:

  Ext.getCmp('yourGridId').getView().ds.reload();

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Bootstrap.yml is used to fetch config from the server. It can be for a Spring cloud application or for others. Typically it looks like:

spring:
  application:
    name: "app-name"
  cloud:
    config:
      uri: ${config.server:http://some-server-where-config-resides}

When we start the application it tries to connect to the given server and read the configuration based on spring profile mentioned in run/debug configuration. bootstrap.yml loads the first

If the server is unreachable application might even be unable to proceed further. However, if configurations matching the profile are present locally the server configs get overridden.

Good approach:

Maintain a separate profile for local and run the app using different profiles.

Send private messages to friends

This is not possible now, but there is a work around. You can engage with the user in the public realm and ask them to send you private messages, but you can't send private messages back, only public ones. Of course, this all depends on if the user gives you the correct permissions.

If you have given permission to access a person's friends, you can then theoretically post on that users wall with references to each one of the friends, asking them to publicly interact with you and then potentially privately message you.

Get Friends

#if authenticated
https://graph.facebook.com/me/friends
http://developers.facebook.com/docs/reference/api/user/

Post in the Public Domain

http://developers.facebook.com/docs/reference/api/status/

Get Messages sent to that user (if given permission)

http://developers.facebook.com/docs/reference/api/message/

Adding new line of data to TextBox

C# - serialData is ReceivedEventHandler in TextBox.

SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();

serialData.Invoke(new Action(() => serialData.Text = String.Concat(recvData)));

Now Visual Studio drops my lines. TextBox, of course, had all the correct options on.

Serial:

Serial.print(rnd);
Serial.( '\n' );  //carriage return

JOptionPane Input to int

String String_firstNumber = JOptionPane.showInputDialog("Input  Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);

Now your Int_firstnumber contains integer value of String_fristNumber.

hope it helped

What does "Error: object '<myvariable>' not found" mean?

I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.

Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!

Hope to help

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give each input a name attribute. Only the clicked input's name attribute will be sent to the server.

<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">

And then

<?php
    if (isset($_POST['publish'])) {
        # Publish-button was clicked
    }
    elseif (isset($_POST['save'])) {
        # Save-button was clicked
    }
?>

Edit: Changed value attributes to alt. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]?

Edit: Since this keeps getting upvotes I went ahead and changed the weird alt/value code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image].

How can I get table names from an MS Access Database?

To build on Ilya's answer try the following query:

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name 

(this one works without modification with an MDB)

ACCDB users may need to do something like this

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6))
        AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name 

As there is an extra table is included that appears to be a system table of some sort.

How can I stop a While loop?

The is operator in Python probably doesn't do what you expect. Instead of this:

    if numpy.array_equal(tmp,universe_array) is True:
        break

I would write it like this:

    if numpy.array_equal(tmp,universe_array):
        break

The is operator tests object identity, which is something quite different from equality.

Twitter bootstrap hide element on small devices

For Bootstrap 4.0 there is a change

See the docs: https://getbootstrap.com/docs/4.0/utilities/display/

In order to hide the content on mobile and display on the bigger devices you have to use the following classes:

d-none d-sm-block

The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.

I suggest to read about that before migration:

https://getbootstrap.com/docs/4.0/migration/#responsive-utilities

How to access component methods from “outside” in ReactJS?

As of React 16.3 React.createRef can be used, (use ref.current to access)

var ref = React.createRef()

var parent = (
  <div>
    <Child ref={ref} />
    <button onClick={e=>console.log(ref.current)}
  </div>
);

React.renderComponent(parent, document.body)

Eloquent: find() and where() usage laravel

Not Found Exceptions

Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

$model = App\Flight::findOrFail(1);

$model = App\Flight::where('legs', '>', 100)->firstOrFail();

If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:

Route::get('/api/flights/{id}', function ($id) {
    return App\Flight::findOrFail($id);
});

How to open an existing project in Eclipse?

If it's a maven project, go to file>import>maven project >existing maven project, then browse for the folder that contains the project, select folder then click finish. That worked for me

How to create a signed APK file using Cordova command line interface?

In the current documentation we can specify a build.json with the keystore:

{
     "android": {
         "debug": {
             "keystore": "..\android.keystore",
             "storePassword": "android",
             "alias": "mykey1",
             "password" : "password",
             "keystoreType": ""
         },
         "release": {
             "keystore": "..\android.keystore",
             "storePassword": "",
             "alias": "mykey2",
             "password" : "password",
             "keystoreType": ""
         }
     }
 }

And then, execute the commando with --buildConfig argumente, this way:

cordova run android --buildConfig

Change input value onclick button - pure javascript or jQuery

My Attempt ( JsFiddle)

Javascript

$(document).ready(function () {
    $('#buttons input[type=button]').on('click', function () {
        var qty = $(this).data('quantity');
        var price = $('#totalPrice').text(); 
        $('#count').val(price * qty);
    });
});

Html

  Product price:$500
<br>Total price: $<span id='totalPrice'>500</span>
<br>
<div id='buttons'>
    <input id='qty2' type="button" data-quantity='2' value="2&#x00A;Qty">
    <input id='qty2' type="button" class="mnozstvi_sleva" data-quantity='4' value="4&#x00A;Qty">
</div>
<br>Total
<input type="text" id="count" value="1">

What is the purpose of global.asax in asp.net

The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

if you are trying to execute mysql query withouth defining connectionstring, you will get this error.

Probably you forgat to define connection string before execution. have you check this out? (sorry for bad english)

How to update the value of a key in a dictionary in Python?

You are modifying the list book_shop.values()[i], which is not getting updated in the dictionary. Whenever you call the values() method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.

Simple way to sort strings in the (case sensitive) alphabetical order

The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html

private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
        public int compare(String str1, String str2) {
            return ComparisonChain.start().
                                compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
                                compare(str1,str2).
                                result();
         }
 };
Collections.sort(list, stringAlphabeticalComparator);

The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:

"AA","Aa","aa","Development","development"

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);

How can I make Flexbox children 100% height of their parent?

I suppose that Chrome's behavior is more consistent with the CSS specification (though it's less intuitive). According to Flexbox specification, the default stretch value of align-self property changes only the used value of the element's "cross size property" (height, in this case). And, as I understand the CSS 2.1 specification, the percentage heights are calculated from the specified value of the parent's height, not its used value. The specified value of the parent's height isn't affected by any flex properties and is still auto.

Setting an explicit height: 100% makes it formally possible to calculate the percentage height of the child, just like setting height: 100% to html makes it possible to calculate the percentage height of body in CSS 2.1.

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Elegant ways to support equivalence ("equality") in Python classes

The way you describe is the way I've always done it. Since it's totally generic, you can always break that functionality out into a mixin class and inherit it in classes where you want that functionality.

class CommonEqualityMixin(object):

    def __eq__(self, other):
        return (isinstance(other, self.__class__)
            and self.__dict__ == other.__dict__)

    def __ne__(self, other):
        return not self.__eq__(other)

class Foo(CommonEqualityMixin):

    def __init__(self, item):
        self.item = item