Programs & Examples On #Scripting

Scripting is a form of programming generally characterized by low formality, loose typing, and no requirement for explicit compilation. There are numerous scripting languages, and these are used in a wide variety of scenarios - command-line applications, GUIs, server-side applications, extension modules.

Test or check if sheet exists

Without any doubt that the above function can work, I just ended up with the following code which works pretty well:

Sub Sheet_exist ()
On Error Resume Next
If Sheets("" & Range("Sheet_Name") & "") Is Nothing Then
    MsgBox "doesnt exist"
Else
    MsgBox "exist"
End if
End sub

Note: Sheets_Name is where I ask the user to input the name, so this might not be the same for you.

How do I script a "yes" response for installing programs?

If you want to just accept defaults you can use:

\n | ./shell_being_run

How to create batch file in Windows using "start" with a path and command with spaces

Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:

start "" "c:\path with spaces\app.exe" param1 "param with spaces"

You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.

Remove the last line from a file in Bash

For Mac Users :

On Mac, head -n -1 wont work. And, I was trying to find a simple solution [ without worrying about processing time ] to solve this problem only using "head" and/or "tail" commands.

I tried the following sequence of commands and was happy that I could solve it just using "tail" command [ with the options available on Mac ]. So, if you are on Mac, and want to use only "tail" to solve this problem, you can use this command :

cat file.txt | tail -r | tail -n +2 | tail -r

Explanation :

1> tail -r : simply reverses the order of lines in its input

2> tail -n +2 : this prints all the lines starting from the second line in its input

Loading .sql files from within PHP

In my projects I've used next solution:

<?php

/**
 * Import SQL from file
 *
 * @param string path to sql file
 */
function sqlImport($file)
{

    $delimiter = ';';
    $file = fopen($file, 'r');
    $isFirstRow = true;
    $isMultiLineComment = false;
    $sql = '';

    while (!feof($file)) {

        $row = fgets($file);

        // remove BOM for utf-8 encoded file
        if ($isFirstRow) {
            $row = preg_replace('/^\x{EF}\x{BB}\x{BF}/', '', $row);
            $isFirstRow = false;
        }

        // 1. ignore empty string and comment row
        if (trim($row) == '' || preg_match('/^\s*(#|--\s)/sUi', $row)) {
            continue;
        }

        // 2. clear comments
        $row = trim(clearSQL($row, $isMultiLineComment));

        // 3. parse delimiter row
        if (preg_match('/^DELIMITER\s+[^ ]+/sUi', $row)) {
            $delimiter = preg_replace('/^DELIMITER\s+([^ ]+)$/sUi', '$1', $row);
            continue;
        }

        // 4. separate sql queries by delimiter
        $offset = 0;
        while (strpos($row, $delimiter, $offset) !== false) {
            $delimiterOffset = strpos($row, $delimiter, $offset);
            if (isQuoted($delimiterOffset, $row)) {
                $offset = $delimiterOffset + strlen($delimiter);
            } else {
                $sql = trim($sql . ' ' . trim(substr($row, 0, $delimiterOffset)));
                query($sql);

                $row = substr($row, $delimiterOffset + strlen($delimiter));
                $offset = 0;
                $sql = '';
            }
        }
        $sql = trim($sql . ' ' . $row);
    }
    if (strlen($sql) > 0) {
        query($row);
    }

    fclose($file);
}

/**
 * Remove comments from sql
 *
 * @param string sql
 * @param boolean is multicomment line
 * @return string
 */
function clearSQL($sql, &$isMultiComment)
{
    if ($isMultiComment) {
        if (preg_match('#\*/#sUi', $sql)) {
            $sql = preg_replace('#^.*\*/\s*#sUi', '', $sql);
            $isMultiComment = false;
        } else {
            $sql = '';
        }
        if(trim($sql) == ''){
            return $sql;
        }
    }

    $offset = 0;
    while (preg_match('{--\s|#|/\*[^!]}sUi', $sql, $matched, PREG_OFFSET_CAPTURE, $offset)) {
        list($comment, $foundOn) = $matched[0];
        if (isQuoted($foundOn, $sql)) {
            $offset = $foundOn + strlen($comment);
        } else {
            if (substr($comment, 0, 2) == '/*') {
                $closedOn = strpos($sql, '*/', $foundOn);
                if ($closedOn !== false) {
                    $sql = substr($sql, 0, $foundOn) . substr($sql, $closedOn + 2);
                } else {
                    $sql = substr($sql, 0, $foundOn);
                    $isMultiComment = true;
                }
            } else {
                $sql = substr($sql, 0, $foundOn);
                break;
            }
        }
    }
    return $sql;
}

/**
 * Check if "offset" position is quoted
 *
 * @param int $offset
 * @param string $text
 * @return boolean
 */
function isQuoted($offset, $text)
{
    if ($offset > strlen($text))
        $offset = strlen($text);

    $isQuoted = false;
    for ($i = 0; $i < $offset; $i++) {
        if ($text[$i] == "'")
            $isQuoted = !$isQuoted;
        if ($text[$i] == "\\" && $isQuoted)
            $i++;
    }
    return $isQuoted;
}

function query($sql)
{
    global $mysqli;
    //echo '#<strong>SQL CODE TO RUN:</strong><br>' . htmlspecialchars($sql) . ';<br><br>';
    if (!$query = $mysqli->query($sql)) {
        throw new Exception("Cannot execute request to the database {$sql}: " . $mysqli->error);
    }
}

set_time_limit(0);

$mysqli = new mysqli('localhost', 'root', '', 'test');
$mysqli->set_charset("utf8");

header('Content-Type: text/html;charset=utf-8');
sqlImport('import.sql');

echo "Peak MB: ", memory_get_peak_usage(true)/1024/1024;

On test sql file (41Mb) memory peak usage: 3.25Mb

How to resolve symbolic links in a shell script

Another way:

# Gets the real path of a link, following all links
myreadlink() { [ ! -h "$1" ] && echo "$1" || (local link="$(expr "$(command ls -ld -- "$1")" : '.*-> \(.*\)$')"; cd $(dirname $1); myreadlink "$link" | sed "s|^\([^/].*\)\$|$(dirname $1)/\1|"); }

# Returns the absolute path to a command, maybe in $PATH (which) or not. If not found, returns the same
whereis() { echo $1 | sed "s|^\([^/].*/.*\)|$(pwd)/\1|;s|^\([^/]*\)$|$(which -- $1)|;s|^$|$1|"; } 

# Returns the realpath of a called command.
whereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed "s|^\([^/].*\)\$|$(dirname ${SCRIPT_PATH})/\1|"; } 

Which programming languages can be used to develop in Android?

Here's a list of languages that can be used to develop on android:

  • Java - primary android development language

  • Kotlin, language from JetBrains which received first-party support from Google, announced in Google I/O 2017

  • C++ - NDK for libraries, not apps

  • Python, bash, et. al. - Via the Scripting Environment

  • Corona- One is to use the Corona SDK . Corona is a high level SDK built on the Lua programming language. Lua is much simpler to learn than Java and the SDK takes away a lot of the pain in developing Android app.

  • Cordova - which uses HTML5, JavaScript, CSS, and can be extended with Java

  • Xamarin technology - that uses c# and in which mono is used for that. Here MonoTouch and Mono for Android are cross-platform implementations of the Common Language Infrastructure (CLI) and Common Language Specifications.

As for your second question: android is highly dependent on it's java architecture, I find it unlikely that there will be other primary development languages available any time soon. However, there's no particular reason why someone couldn't implement another language in Java (something like Jython) and use that. However, that surely won't be easier or as performant as just writing the code in Java.

Copy files to network computers on windows command line

check Robocopy:

ROBOCOPY \\server-source\c$\VMExports\ C:\VMExports\ /E /COPY:DAT

make sure you check what robocopy parameter you want. this is just an example. type robocopy /? in a comandline/powershell on your windows system.

How do I write a bash script to restart a process if it dies?

Have a look at monit (http://mmonit.com/monit/). It handles start, stop and restart of your script and can do health checks plus restarts if necessary.

Or do a simple script:

while true
do
/your/script
sleep 1
done

Automatic confirmation of deletion in powershell

The default is: no prompt.

You can enable it with -Confirm or disable it with -Confirm:$false

However, it will still prompt, when the target:

  • is a directory
  • and it is not empty
  • and the -Recurse parameter is not specified.

-Force is required to also remove hidden and read-only items etc.

To sum it up:

Remove-Item -Recurse -Force -Confirm:$false

...should cover all scenarios.

How do I know the script file name in a Bash script?

If you want it without the path then you would use ${0##*/}

How to run a PowerShell script without displaying a window?

I think that the best way to hide the console screen of the PowerShell when your are running a background scripts is this code ("Bluecakes" answer).

I add this code in the beginning of all my PowerShell scripts that I need to run in background.

# .Net methods for hiding/showing the console in the background
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
function Hide-Console
{
    $consolePtr = [Console.Window]::GetConsoleWindow()
    #0 hide
    [Console.Window]::ShowWindow($consolePtr, 0)
}
Hide-Console

If this answer was help you, please vote to "Bluecakes" in his answer in this post.

How do I remove newlines from a text file?

If the data is in file.txt, then:

echo $(<file.txt) | tr -d ' '

The '$(<file.txt)' reads the file and gives the contents as a series of words which 'echo' then echoes with a space between them. The 'tr' command then deletes any spaces:

22791;14336;22821;34653;21491;25522;33238;

Bash scripting missing ']'

add a space before the close bracket

Find and Replace Inside a Text File from a Bash Command

Try the following shell command:

find ./  -type f -name "file*.txt" | xargs sed -i -e 's/abc/xyz/g'

When is a language considered a scripting language?

Scripting languages tend to run within a scripting engine which is part of a larger application. For example, JavaScript runs inside your browsers scripting engine.

How to store the hostname in a variable in a .bat file?

hmm - something like this?

set host=%COMPUTERNAME%
echo %host%

EDIT: expanding on jitter's answer and using a technique in an answer to this question to set an environment variable with the result of running a command line app:

@echo off
hostname.exe > __t.tmp
set /p host=<__t.tmp
del __t.tmp
echo %host%

In either case, 'host' is created as an environment variable.

How to urlencode data for curl command?

One of variants, may be ugly, but simple:

urlencode() {
    local data
    if [[ $# != 1 ]]; then
        echo "Usage: $0 string-to-urlencode"
        return 1
    fi
    data="$(curl -s -o /dev/null -w %{url_effective} --get --data-urlencode "$1" "")"
    if [[ $? != 3 ]]; then
        echo "Unexpected error" 1>&2
        return 2
    fi
    echo "${data##/?}"
    return 0
}

Here is the one-liner version for example (as suggested by Bruno):

date | curl -Gso /dev/null -w %{url_effective} --data-urlencode @- "" | cut -c 3-

# If you experience the trailing %0A, use
date | curl -Gso /dev/null -w %{url_effective} --data-urlencode @- "" | sed -E 's/..(.*).../\1/'

What is a simple command line program or script to backup SQL server databases?

If you can find the DB files... "cp DBFiles backup/"

Almost for sure not advisable in most cases, but it's simple as all getup.

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

The one-liner that Andre Miller posted above works except for recent versions of sed when the input file ends with a blank line and no chars. On my Mac my CPU just spins.

Infinite loop if last line is blank and has no chars:

sed '$!N; /^\(.*\)\n\1$/!P; D'

Doesn't hang, but you lose the last line

sed '$d;N; /^\(.*\)\n\1$/!P; D'

The explanation is at the very end of the sed FAQ:

The GNU sed maintainer felt that despite the portability problems
this would cause, changing the N command to print (rather than
delete) the pattern space was more consistent with one's intuitions
about how a command to "append the Next line" ought to behave.
Another fact favoring the change was that "{N;command;}" will
delete the last line if the file has an odd number of lines, but
print the last line if the file has an even number of lines.

To convert scripts which used the former behavior of N (deleting
the pattern space upon reaching the EOF) to scripts compatible with
all versions of sed, change a lone "N;" to "$d;N;".

sudo echo "something" >> /etc/privilegedFile doesn't work

Doing

sudo sh -c "echo >> somefile"

should work. The problem is that > and >> are handled by your shell, not by the "sudoed" command, so the permissions are your ones, not the ones of the user you are "sudoing" into.

Windows batch - concatenate multiple text files into one

cat "input files" > "output files"

This works in PowerShell, which is the Windows preferred shell in current Windows versions, therefore it works. It is also the only version of the answers above to work with large files, where 'type' or 'copy' fails.

Python recursive folder read

os.walk does recursive walk by default. For each dir, starting from root it yields a 3-tuple (dirpath, dirnames, filenames)

from os import walk
from os.path import splitext, join

def select_files(root, files):
    """
    simple logic here to filter out interesting files
    .py files in this example
    """

    selected_files = []

    for file in files:
        #do concatenation here to get full path 
        full_path = join(root, file)
        ext = splitext(file)[1]

        if ext == ".py":
            selected_files.append(full_path)

    return selected_files

def build_recursive_dir_tree(path):
    """
    path    -    where to begin folder scan
    """
    selected_files = []

    for root, dirs, files in walk(path):
        selected_files += select_files(root, files)

    return selected_files

Error handling in Bash

I prefer something really easy to call. So I use something that looks a little complicated, but is easy to use. I usually just copy-and-paste the code below into my scripts. An explanation follows the code.

#This function is used to cleanly exit any script. It does this displaying a
# given error message, and exiting with an error code.
function error_exit {
    echo
    echo "$@"
    exit 1
}
#Trap the killer signals so that we can exit with a good message.
trap "error_exit 'Received signal SIGHUP'" SIGHUP
trap "error_exit 'Received signal SIGINT'" SIGINT
trap "error_exit 'Received signal SIGTERM'" SIGTERM

#Alias the function so that it will print a message with the following format:
#prog-name(@line#): message
#We have to explicitly allow aliases, we do this because they make calling the
#function much easier (see example).
shopt -s expand_aliases
alias die='error_exit "Error ${0}(@`echo $(( $LINENO - 1 ))`):"'

I usually put a call to the cleanup function in side the error_exit function, but this varies from script to script so I left it out. The traps catch the common terminating signals and make sure everything gets cleaned up. The alias is what does the real magic. I like to check everything for failure. So in general I call programs in an "if !" type statement. By subtracting 1 from the line number the alias will tell me where the failure occurred. It is also dead simple to call, and pretty much idiot proof. Below is an example (just replace /bin/false with whatever you are going to call).

#This is an example useage, it will print out
#Error prog-name (@1): Who knew false is false.
if ! /bin/false ; then
    die "Who knew false is false."
fi

What is the most useful script you've written for everyday life?

Super remote reset button.
A rack of super special simulation hardware (backin the days when a room full of VME crates did less than your GPU) that a user on the other side of the world would crash in the early hours of the morning. It took an hour to get into the lab and through security.

But we weren't allowed to connect to the super special controller or modify the hardware. The solution was an old DEC workstation with an epson dot matrix printer, tape a plastic ruler to the paper feed knob, position the printer near the reset button.
Log in to the WS as a regular user (no root allowed, all external ports locked down), print a document with 24blank lines - which rotated the paper feed knob and the ruler pressed over the reset on the super special hardware.

Find multiple files and rename them in Linux

If you just want to rename and don't mind using an external tool, then you can use rnm. The command would be:

#on current folder
rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' *

-dp -1 will make it recursive to all subdirectories.

-fo implies file only mode.

-ssf '_dbg' searches for files with _dbg in the filename.

-rs '/_dbg//' replaces _dbg with empty string.

You can run the above command with the path of the CURRENT_FOLDER too:

rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' /path/to/the/directory

Store mysql query output into a shell variable

Other way:

Your Script:

#!/bin/sh

# Set these variables
MyUSER="root"   # DB_USERNAME
MyPASS="yourPass"   # DB_PASSWORD
MyHOST="yourHost"    # DB_HOSTNAME
DB_NAME="dbName"
CONTAINER="containerName" #if use docker

# Get data
data=$($MyHOST -u $MyUSER -p$MyPASS $DB_NAME -h $CONTAINER -e "SELECT data1,data2 from table_name LIMIT 1;"  -B --skip-column-names)

# Set data
data1=$(echo $data | awk '{print $1}')
data2=$(echo $data | awk '{print $2}')

# Print data
echo $data1 $data2

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

Execute SQL script from command line

Take a look at the sqlcmd utility. It allows you to execute SQL from the command line.

http://msdn.microsoft.com/en-us/library/ms162773.aspx

It's all in there in the documentation, but the syntax should look something like this:

sqlcmd -U myLogin -P myPassword -S MyServerName -d MyDatabaseName 
    -Q "DROP TABLE MyTable"

Setting a windows batch file variable to the day of the week

%DATE% is not your friend. Because the %DATE% environment variable (and the DATE command) returns the current date using the Windows short date format that is fully and endlessly customizable. One user may configure the system to return 07/06/2012 while another might choose Fri060712. Using %DATE% is a complete nightmare for a BAT programmer.

There are two possible approaches to solve this problem:

  1. You may be tempted to temporarily change the short date format, by changing the locale settings in the registry value HKCU\Control Panel\International\sShortDate, to your recognizable format. Then access %DATE% to get the date in the format you want; and finally restore the format back to the original user format. Something like this

    reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f >nul
    reg add "HKCU\Control Panel\International" /v sShortDate /d "ddd" /f >nul
    set DOW=%DATE%
    reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f >nul
    

    but this method has two problems:

    • it tampers with a global registry value for its local particular purpouses, so it may interfere with other processes or user tasks that at the very same time query the date in short date format, including itself if run simultaneously.

    • and it returns the three letter day of the week in the local language that may be different in different systems or different users.

  2. use WMIC Win32_LocalTime, that returns the date in a convenient way to directly parse it with a FOR command.

    FOR /F "skip=1" %%A IN ('WMIC Path Win32_LocalTime Get DayOfWeek' ) DO (
      set DOW=%%A
    )
    

    this is the method I recommend.

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Can Windows' built-in ZIP compression be scripted?

Just for clarity: GZip is not an MS-only algorithm as suggested by Guy Starbuck in his comment from August. The GZipStream in System.IO.Compression uses the Deflate algorithm, just the same as the zlib library, and many other zip tools. That class is fully interoperable with unix utilities like gzip.

The GZipStream class is not scriptable from the commandline or VBScript, to produce ZIP files, so it alone would not be an answer the original poster's request.

The free DotNetZip library does read and produce zip files, and can be scripted from VBScript or Powershell. It also includes command-line tools to produce and read/extract zip files.

Here's some code for VBScript:

dim filename 
filename = "C:\temp\ZipFile-created-from-VBScript.zip"

WScript.echo("Instantiating a ZipFile object...")
dim zip 
set zip = CreateObject("Ionic.Zip.ZipFile")

WScript.echo("using AES256 encryption...")
zip.Encryption = 3

WScript.echo("setting the password...")
zip.Password = "Very.Secret.Password!"

WScript.echo("adding a selection of files...")
zip.AddSelectedFiles("*.js")
zip.AddSelectedFiles("*.vbs")

WScript.echo("setting the save name...")
zip.Name = filename

WScript.echo("Saving...")
zip.Save()

WScript.echo("Disposing...")
zip.Dispose()

WScript.echo("Done.")

Here's some code for Powershell:

[System.Reflection.Assembly]::LoadFrom("c:\\dinoch\\bin\\Ionic.Zip.dll");

$directoryToZip = "c:\\temp";
$zipfile =  new-object Ionic.Zip.ZipFile;
$e= $zipfile.AddEntry("Readme.txt", "This is a zipfile created from within powershell.")
$e= $zipfile.AddDirectory($directoryToZip, "home")
$zipfile.Save("ZipFiles.ps1.out.zip");

In a .bat or .cmd file, you can use the zipit.exe or unzip.exe tools. Eg:

zipit NewZip.zip  -s "This is string content for an entry"  Readme.txt  src 

PHP - Redirect and send data via POST

/**
 * Redirect with POST data.
 *
 * @param string $url URL.
 * @param array $post_data POST data. Example: array('foo' => 'var', 'id' => 123)
 * @param array $headers Optional. Extra headers to send.
 */
public function redirect_post($url, array $data, array $headers = null) {
    $params = array(
        'http' => array(
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );
    if (!is_null($headers)) {
        $params['http']['header'] = '';
        foreach ($headers as $k => $v) {
            $params['http']['header'] .= "$k: $v\n";
        }
    }
    $ctx = stream_context_create($params);
    $fp = @fopen($url, 'rb', false, $ctx);
    if ($fp) {
        echo @stream_get_contents($fp);
        die();
    } else {
        // Error
        throw new Exception("Error loading '$url', $php_errormsg");
    }
}

How to run a shell script in OS X by double-clicking?

No need to use third-party apps such as Platypus.

Just create an Apple Script with Script Editor and use the command do shell script "shell commands" for direct command calls or executable shell script files, keep the editable script file safe somewhere then export it to create an Application script. the app script is launch-able by double click or selection in bar folder.

Can I create a One-Time-Use Function in a Script or Stored Procedure?

I know I might get criticized for suggesting dynamic SQL, but sometimes it's a good solution. Just make sure you understand the security implications before you consider this.

DECLARE @add_a_b_func nvarchar(4000) = N'SELECT @c = @a + @b;';
DECLARE @add_a_b_parm nvarchar(500) = N'@a int, @b int, @c int OUTPUT';

DECLARE @result int;
EXEC sp_executesql @add_a_b_func, @add_a_b_parm, 2, 3, @c = @result OUTPUT;
PRINT CONVERT(varchar, @result); -- prints '5'

How do I get the day month and year from a Windows cmd.exe script?

This variant works for all localizations:

@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    if "%%B" NEQ "" (
        SET /A FDATE=%%F*10000+%%D*100+%%A
    )
)
@echo on
echo date=%FDATE%
echo year=%FDATE:~2,2%
echo month=%FDATE:~4,2%

Raise error in a Bash script

There are a couple more ways with which you can approach this problem. Assuming one of your requirement is to run a shell script/function containing a few shell commands and check if the script ran successfully and throw errors in case of failures.

The shell commands in generally rely on exit-codes returned to let the shell know if it was successful or failed due to some unexpected events.

So what you want to do falls upon these two categories

  • exit on error
  • exit and clean-up on error

Depending on which one you want to do, there are shell options available to use. For the first case, the shell provides an option with set -e and for the second you could do a trap on EXIT

Should I use exit in my script/function?

Using exit generally enhances readability In certain routines, once you know the answer, you want to exit to the calling routine immediately. If the routine is defined in such a way that it doesn’t require any further cleanup once it detects an error, not exiting immediately means that you have to write more code.

So in cases if you need to do clean-up actions on script to make the termination of the script clean, it is preferred to not to use exit.

Should I use set -e for error on exit?

No!

set -e was an attempt to add "automatic error detection" to the shell. Its goal was to cause the shell to abort any time an error occurred, but it comes with a lot of potential pitfalls for example,

  • The commands that are part of an if test are immune. In the example, if you expect it to break on the test check on the non-existing directory, it wouldn't, it goes through to the else condition

    set -e
    f() { test -d nosuchdir && echo no dir; }
    f
    echo survived
    
  • Commands in a pipeline other than the last one, are immune. In the example below, because the most recently executed (rightmost) command's exit code is considered ( cat) and it was successful. This could be avoided by setting by the set -o pipefail option but its still a caveat.

    set -e
    somecommand that fails | cat -
    echo survived 
    

Recommended for use - trap on exit

The verdict is if you want to be able to handle an error instead of blindly exiting, instead of using set -e, use a trap on the ERR pseudo signal.

The ERR trap is not to run code when the shell itself exits with a non-zero error code, but when any command run by that shell that is not part of a condition (like in if cmd, or cmd ||) exits with a non-zero exit status.

The general practice is we define an trap handler to provide additional debug information on which line and what cause the exit. Remember the exit code of the last command that caused the ERR signal would still be available at this point.

cleanup() {
    exitcode=$?
    printf 'error condition hit\n' 1>&2
    printf 'exit code returned: %s\n' "$exitcode"
    printf 'the command executing at the time of the error was: %s\n' "$BASH_COMMAND"
    printf 'command present on line: %d' "${BASH_LINENO[0]}"
    # Some more clean up code can be added here before exiting
    exit $exitcode
}

and we just use this handler as below on top of the script that is failing

trap cleanup ERR

Putting this together on a simple script that contained false on line 15, the information you would be getting as

error condition hit
exit code returned: 1
the command executing at the time of the error was: false
command present on line: 15

The trap also provides options irrespective of the error to just run the cleanup on shell completion (e.g. your shell script exits), on signal EXIT. You could also trap on multiple signals at the same time. The list of supported signals to trap on can be found on the trap.1p - Linux manual page

Another thing to notice would be to understand that none of the provided methods work if you are dealing with sub-shells are involved in which case, you might need to add your own error handling.

  • On a sub-shell with set -e wouldn't work. The false is restricted to the sub-shell and never gets propagated to the parent shell. To do the error handling here, add your own logic to do (false) || false

    set -e
    (false)
    echo survived
    
  • The same happens with trap also. The logic below wouldn't work for the reasons mentioned above.

    trap 'echo error' ERR
    (false)
    

How to make a Python script run like a service or daemon in Linux

You can also make the python script run as a service using a shell script. First create a shell script to run the python script like this (scriptname arbitary name)

#!/bin/sh
script='/home/.. full path to script'
/usr/bin/python $script &

now make a file in /etc/init.d/scriptname

#! /bin/sh

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/home/.. path to shell script scriptname created to run python script
PIDFILE=/var/run/scriptname.pid

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

case "$1" in
  start)
     log_daemon_msg "Starting feedparser"
     start_daemon -p $PIDFILE $DAEMON
     log_end_msg $?
   ;;
  stop)
     log_daemon_msg "Stopping feedparser"
     killproc -p $PIDFILE $DAEMON
     PID=`ps x |grep feed | head -1 | awk '{print $1}'`
     kill -9 $PID       
     log_end_msg $?
   ;;
  force-reload|restart)
     $0 stop
     $0 start
   ;;
  status)
     status_of_proc -p $PIDFILE $DAEMON atd && exit 0 || exit $?
   ;;
 *)
   echo "Usage: /etc/init.d/atd {start|stop|restart|force-reload|status}"
   exit 1
  ;;
esac

exit 0

Now you can start and stop your python script using the command /etc/init.d/scriptname start or stop.

How to get disk capacity and free space of remote computer

$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Select-Object Size,FreeSpace

$disk.Size
$disk.FreeSpace

To extract the values only and assign them to a variable:

$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Foreach-Object {$_.Size,$_.FreeSpace}

How do I get cURL to not show the progress bar?

I found that with curl 7.18.2 the download progress bar is not hidden with:

curl -s http://google.com > temp.html

but it is with:

curl -ss http://google.com > temp.html

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

Bash or KornShell (ksh)?

Bash is the standard for Linux.
My experience is that it is easier to find help for bash than for ksh or csh.

How do I abort the execution of a Python script?

Try

sys.exit("message")

It is like the perl

die("message")

if this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function

Shell script to send email

sendmail works for me on the mac (10.6.8)

echo "Hello" | sendmail -f [email protected] [email protected]

Add a prefix string to beginning of each line

Here is a hightly readable oneliner solution using the ts command from moreutils

$ cat file | ts prefix | tr -d ' '

And how it's derived step by step:

# Step 0. create the file

$ cat file
line1
line2
line3
# Step 1. add prefix to the beginning of each line

$ cat file | ts prefix
prefix line1
prefix line2
prefix line3
# Step 2. remove spaces in the middle

$ cat file | ts prefix | tr -d ' '
prefixline1
prefixline2
prefixline3

Wait for a process to finish

Had the same issue, I solved the issue killing the process and then waiting for each process to finish using the PROC filesystem:

while [ -e /proc/${pid} ]; do sleep 0.1; done

Shell script to capture Process ID and kill it if exist

I use the command pkill for this:

NAME
       pgrep, pkill - look up or signal processes based on name and 
       other attributes

SYNOPSIS
       pgrep [options] pattern
       pkill [options] pattern

DESCRIPTION
       pgrep looks through the currently running processes and lists 
       the process IDs which match the selection criteria to stdout.
       All the criteria have to match.  For example,

              $ pgrep -u root sshd

       will only list the processes called sshd AND owned by root.
       On the other hand,

              $ pgrep -u root,daemon

       will list the processes owned by root OR daemon.

       pkill will send the specified signal (by default SIGTERM) 
       to each process instead of listing them on stdout.

If your code runs via interpreter (java, python, ...) then the name of the process is the name of the interpreter. You need to user the argument --full. This matches against the command name and the arguments.

script to map network drive

Does this not work (assuming "ROUTERNAME" is the user name the router expects)?

net use Z: "\\10.0.1.1\DRIVENAME" /user:"ROUTERNAME" "PW"

Alternatively, you can use use a small VBScript:

Option Explicit
Dim u, p, s, l
Dim Network: Set Network= CreateObject("WScript.Network")

l = "Z:"
s = "\\10.0.1.1\DRIVENAME"

u = "ROUTERNAME"
p = "PW"

Network.MapNetworkDrive l, s, False, u, p

Shell script not running, command not found

I'm new to shell scripting too, but I had this same issue. Make sure at the end of your script you have a blank line. Otherwise it won't work.

How to pass boolean values to a PowerShell script from a command prompt

You can also use 0 for False or 1 for True. It actually suggests that in the error message:

Cannot process argument transformation on parameter 'Unify'. Cannot convert value "System.String" to type "System.Boolean", parameters of this type only accept booleans or numbers, use $true, $false, 1 or 0 instead.

For more info, check out this MSDN article on Boolean Values and Operators.

How to check the extension of a filename in a bash script?

I guess that '$PATH_TO_SOMEWHERE'is something like '<directory>/*'.

In this case, I would change the code to:

find <directory> -maxdepth 1 -type d -exec ... \;
find <directory> -maxdepth 1 -type f -name "*.txt" -exec ... \;

If you want to do something more complicated with the directory and text file names, you could:

find <directory> -maxdepth 1 -type d | while read dir; do echo $dir; ...; done
find <directory> -maxdepth 1 -type f -name "*.txt" | while read txtfile; do echo $txtfile; ...; done

If you have spaces in your file names, you could:

find <directory> -maxdepth 1 -type d | xargs ...
find <directory> -maxdepth 1 -type f -name "*.txt" | xargs ...

Hiding user input on terminal in Linux script

Update

In case you want to get fancy by outputting an * for each character they type, you can do something like this (using andreas' read -s solution):

unset password;
while IFS= read -r -s -n1 pass; do
  if [[ -z $pass ]]; then
     echo
     break
  else
     echo -n '*'
     password+=$pass
  fi
done

Without being fancy

echo "Please enter your username";
read username;

echo "Please enter your password";
stty -echo
read password;
stty echo

How to get a password from a shell script without echoing

You can also prompt for a password without setting a variable in the current shell by doing something like this:

$(read -s;echo $REPLY)

For instance:

my-command --set password=$(read -sp "Password: ";echo $REPLY)

You can add several of these prompted values with line break, doing this:

my-command --set user=$(read -sp "`echo $'\n '`User: ";echo $REPLY) --set password=$(read -sp "`echo $'\n '`Password: ";echo $REPLY)

Counter increment in Bash loop not working

This is all you need to do:

$((COUNTER++))

Here's an excerpt from Learning the bash Shell, 3rd Edition, pp. 147, 148:

bash arithmetic expressions are equivalent to their counterparts in the Java and C languages.[9] Precedence and associativity are the same as in C. Table 6-2 shows the arithmetic operators that are supported. Although some of these are (or contain) special characters, there is no need to backslash-escape them, because they are within the $((...)) syntax.

..........................

The ++ and - operators are useful when you want to increment or decrement a value by one.[11] They work the same as in Java and C, e.g., value++ increments value by 1. This is called post-increment; there is also a pre-increment: ++value. The difference becomes evident with an example:

$ i=0
$ echo $i
0
$ echo $((i++))
0
$ echo $i
1
$ echo $((++i))
2
$ echo $i
2

See http://www.safaribooksonline.com/a/learning-the-bash/7572399/

How do I compare two string variables in an 'if' statement in Bash?

Use:

#!/bin/bash

s1="hi"
s2="hi"

if [ "x$s1" == "x$s2" ]
then
  echo match
fi

Adding an additional string inside makes it more safe.

You could also use another notation for single-line commands:

[ "x$s1" == "x$s2" ] && echo match

Difference between a script and a program?

There are really two dimensions to the scripting vs program reality:

  1. Is the language powerful enough, particularly with string operations, to compete with a macro processor like the posix shell and particularly bash? If it isn't better than bash for running some function there isn't much point in using it.

  2. Is the language convenient and quickly started? Java, Scala, JRuby, Closure and Groovy are all powerful languages, but Java requires a lot of boilerplate and the JVM they all require just takes too long to start up.

OTOH, Perl, Python, and Ruby all start up quickly and have powerful string handling (and pretty much everything-else-handling) operations, so they tend to occupy the sometimes-disparaged-but-not-easily-encroached-upon "scripting" world. It turns out they do well at running entire traditional programs as well.

Left in limbo are languages like Javascript, which aren't used for scripting but potentially could be. Update: since this was written node.js was released on multiple platforms. In other news, the question was closed. "Oh well."

How can I run a PHP script in the background after a form is submitted?

PHP exec("php script.php") can do it.

From the Manual:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

So if you redirect the output to a log file (what is a good idea anyways), your calling script will not hang and your email script will run in bg.

Shell script to get the process ID on Linux

This works in Cygwin but it should be effective in Linux as well.

ps -W | awk '/ruby/,NF=1' | xargs kill -f

or

ps -W | awk '$0~z,NF=1' z=ruby | xargs kill -f

Bash Pitfalls

Capture key press (or keydown) event on DIV element

Here example on plain JS:

_x000D_
_x000D_
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
  console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
  outline: none;_x000D_
}
_x000D_
<div _x000D_
  id="myDiv"_x000D_
  tabindex="0"_x000D_
>_x000D_
  Press me and start typing_x000D_
</div>
_x000D_
_x000D_
_x000D_

PowerShell Script to Find and Replace for all Files with a Specific Extension

This powershell example looks for all instances of the string "\foo\" in a folder and its subfolders, replaces "\foo\" with "\bar\" AND DOES NOT REWRITE files that don't contain the string "\foo\" This way you don't destroy the file last update datetime stamps where the string was not found:

Get-ChildItem  -Path C:\YOUR_ROOT_PATH\*.* -recurse 
 | ForEach {If (Get-Content $_.FullName | Select-String -Pattern '\\foo\\') 
           {(Get-Content $_ | ForEach {$_ -replace '\\foo\\', '\bar\'}) | Set-Content $_ }
           }

In a Bash script, how can I exit the entire script if a certain condition occurs?

I have the same question but cannot ask it because it would be a duplicate.

The accepted answer, using exit, does not work when the script is a bit more complicated. If you use a background process to check for the condition, exit only exits that process, as it runs in a sub-shell. To kill the script, you have to explicitly kill it (at least that is the only way I know).

Here is a little script on how to do it:

#!/bin/bash

boom() {
    while true; do sleep 1.2; echo boom; done
}

f() {
    echo Hello
    N=0
    while
        ((N++ <10))
    do
        sleep 1
        echo $N
        #        ((N > 5)) && exit 4 # does not work
        ((N > 5)) && { kill -9 $$; exit 5; } # works 
    done
}

boom &
f &

while true; do sleep 0.5; echo beep; done

This is a better answer but still incomplete a I really don't know how to get rid of the boom part.

fork and exec in bash

Use the ampersand just like you would from the shell.

#!/usr/bin/bash
function_to_fork() {
   ...
}

function_to_fork &
# ... execution continues in parent process ...

How to get the part of a file after the first line that matches a regular expression?

As a simple approximation you could use

grep -A100000 TERMINATE file

which greps for TERMINATE and outputs up to 100000 lines following that line.

From man page

-A NUM, --after-context=NUM

Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.

How to uninstall a windows service and delete its files without rebooting

Are you not able to stop the service before the update (and restart after the update) using the commands below?

net stop <service name>
net start <service name>

Whenever I'm testing/deploying a service I'm able to upload files without reinstalling as long as the service is stopped. I'm not sure if the issue you are having is different.

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

How to execute Python scripts in Windows?

you should make the default application to handle python files be python.exe.

right click a *.py file, select "Open With" dialog. In there select "python.exe" and check "always use this program for this file type" (something like that).

then your python files will always be run using python.exe

eval command in Bash and its typical uses

I originally intentionally never learned how to use eval, because most people will recommend to stay away from it like the plague. However I recently discovered a use case that made me facepalm for not recognizing it sooner.

If you have cron jobs that you want to run interactively to test, you might view the contents of the file with cat, and copy and paste the cron job to run it. Unfortunately, this involves touching the mouse, which is a sin in my book.

Lets say you have a cron job at /etc/cron.d/repeatme with the contents:

*/10 * * * * root program arg1 arg2

You cant execute this as a script with all the junk in front of it, but we can use cut to get rid of all the junk, wrap it in a subshell, and execute the string with eval

eval $( cut -d ' ' -f 6- /etc/cron.d/repeatme)

The cut command only prints out the 6th field of the file, delimited by spaces. Eval then executes that command.

I used a cron job here as an example, but the concept is to format text from stdout, and then evaluate that text.

The use of eval in this case is not insecure, because we know exactly what we will be evaluating before hand.

How to stop a vb script running in windows

Running scripts can be terminated from the Task Manager.

However, scripts that perpetually focus program windows using .AppActivate may make it very difficult to get to the task manager -i.e you and the script will be fighting for control. Hence i recommend writing a script (which i call self destruct for obvious reasons) and make a keyboard shortcut key to activate the script.

Self destruct script:

Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "taskkill /f /im Cscript.exe", , True 
WshShell.Run "taskkill /f /im wscript.exe", , True  

Keyboard shortcut: rightclick on the script icon, select create shortcut, rightclick on script shortcut icon, select properties, click in shortcutkey and make your own.

type your shortcut key and all scripts end. Cheers

Meaning of $? (dollar question mark) in shell scripts

This is the exit status of the last executed command.

For example the command true always returns a status of 0 and false always returns a status of 1:

true
echo $? # echoes 0
false
echo $? # echoes 1

From the manual: (acessible by calling man bash in your shell)

$?       Expands to the exit status of the most recently executed foreground pipeline.

By convention an exit status of 0 means success, and non-zero return status means failure. Learn more about exit statuses on wikipedia.

There are other special variables like this, as you can see on this online manual: https://www.gnu.org/s/bash/manual/bash.html#Special-Parameters

How to check if memcache or memcached is installed for PHP?

Note that all of the class_exists, extensions_loaded, and function_exists only check the link between PHP and the memcache package.

To actually check whether memcache is installed you must either:

  • know the OS platform and use shell commands to check whether memcache package is installed
  • or test whether memcache connection can be established on the expected port

EDIT 2: OK, actually here's an easier complete solution:

if (class_exists('Memcache')) {
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect('localhost');
}
if ($isMemcacheAvailable) {
    //...
}

Outdated code below


EDIT: Actually you must force PHP to throw error on warnings first. Have a look at this SO question answer.

You can then test the connection via:

try {
    $memcache->connect('localhost');
} catch (Exception $e) {
    // well it's not here
}

Windows batch: sleep

I rely on JScript. I have a JScript file like this:

// This is sleep.js
WScript.Sleep( WScript.Arguments( 0 ) );

And inside a batch file I run it with CScript (usually it is %SystemRoot%\system32\cscript.exe)

rem This is the calling inside a BAT file to wait for 5 seconds
cscript /nologo sleep.js 5000

How to tell if a string is not defined in a Bash shell script

The explicit way to check for a variable being defined would be:

[ -v mystr ]

What does `set -x` do?

set -x

Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.

[source]

Example

set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30

set +x
echo `expr 10 + 20 `
30

Above example illustrates the usage of set -x. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.

  • First step expr has been evaluated.
  • Second step echo has been evaluated.

To know more about set ? visit this link

when it comes to your shell script,

[ "$DEBUG" == 'true' ] && set -x

Your script might have been printing some additional lines of information when the execution mode selected as DEBUG. Traditionally people used to enable debug mode when a script called with optional argument such as -d

Is there a simple way to convert C++ enum to string?

A problem with answer 0 is that the enum binary values do not necessarily start at 0 and are not necessarily contiguous.

When I need this, I usually:

  • pull the enum definition into my source
  • edit it to get just the names
  • do a macro to change the name to the case clause in the question, though typically on one line: case foo: return "foo";
  • add the switch, default and other syntax to make it legal

How can I ssh directly to a particular directory?

simply modify your home with the command: usermod -d /newhome username

How does a Linux/Unix Bash script know its own PID?

If the process is a child process and $BASHPID is not set, it is possible to query the ppid of a created child process of the running process. It might be a bit ugly, but it works. Example:

sleep 1 &
mypid=$(ps -o ppid= -p "$!")

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

There is a Powershell script buried in the msdb forums that will script all the tables and related objects:

# Script all tables in a database
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") 
    | out-null

$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') '<Servername>'
$db = $s.Databases['<Database>']

$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)
$scrp.Options.AppendToFile = $True
$scrp.Options.ClusteredIndexes = $True
$scrp.Options.DriAll = $True
$scrp.Options.ScriptDrops = $False
$scrp.Options.IncludeHeaders = $False
$scrp.Options.ToFileOnly = $True
$scrp.Options.Indexes = $True
$scrp.Options.WithDependencies = $True
$scrp.Options.FileName = 'C:\Temp\<Database>.SQL'

foreach($item in $db.Tables) { $tablearray+=@($item) }
$scrp.Script($tablearray)

Write-Host "Scripting complete"

How do I tell if a regular file does not exist in Bash?

I prefer to do the following one-liner, in POSIX shell compatible format:

$ [ -f "/$DIR/$FILE" ] || echo "$FILE NOT FOUND"

$ [ -f "/$DIR/$FILE" ] && echo "$FILE FOUND"

For a couple of commands, like I would do in a script:

$  [ -f "/$DIR/$FILE" ] || { echo "$FILE NOT FOUND" ; exit 1 ;}

Once I started doing this, I rarely use the fully typed syntax anymore!!

Using a batch to copy from network drive to C: or D: drive

You are copying all files to a single file called TEST_BACKUP_FOLDER

try this:

md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER

VBA: How to display an error message just like the standard error message which has a "Debug" button?

For Me I just wanted to see the error in my VBA application so in the function I created the below code..

Function Database_FileRpt
'-------------------------
On Error GoTo CleanFail
'-------------------------
'
' Create_DailyReport_Action and code


CleanFail:

'*************************************

MsgBox "********************" _

& vbCrLf & "Err.Number: " & Err.Number _

& vbCrLf & "Err.Description: " & Err.Description _

& vbCrLf & "Err.Source: " & Err.Source _

& vbCrLf & "********************" _

& vbCrLf & "...Exiting VBA Function: Database_FileRpt" _

& vbCrLf & "...Excel VBA Program Reset." _

, , "VBA Error Exception Raised!"

*************************************

 ' Note that the next line will reset the error object to 0, the variables 
above are used to remember the values
' so that the same error can be re-raised

Err.Clear

' *************************************

Resume CleanExit

CleanExit:

'cleanup code , if any, goes here. runs regardless of error state.

Exit Function  ' SUB  or Function    

End Function  ' end of Database_FileRpt

' ------------------

Executing multiple commands from a Windows cmd script

I don't know the direct answer to your question, but if you do a lot of these scripts, it might be worth learning a more powerful language like perl. Free implementations exist for Windows (e.g. activestate, cygwin). I've found it worth the initial effort for my own tasks.

Edit:

As suggested by @Ferruccio, if you can't install extra software, consider vbscript and/or javascript. They're built into the Windows scripting host.

How do I create a nice-looking DMG for Mac OS X using command-line tools?

I found this great mac app to automate the process - http://www.araelium.com/dmgcanvas/ you must have a look if you are creating dmg installer for your mac app

Creating an array from a text file in Bash

Use the mapfile command:

mapfile -t myArray < file.txt

The error is using for -- the idiomatic way to loop over lines of a file is:

while IFS= read -r line; do echo ">>$line<<"; done < file.txt

See BashFAQ/005 for more details.

Execute command on all files in a directory

The following bash code will pass $file to command where $file will represent every file in /dir

for file in /dir/*
do
  cmd [option] "$file" >> results.out
done

Example

el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt

PuTTY scripting to log onto host

I want to suggest a common solution for those requirements, maybe it is a use for you: AutoIt. With that program, you can write scripts on top of any window like Putty and execute all commands you want to (like button pressing or mouse clicking in textboxes or buttons).

This way you can emulate all steps you are always doing with Putty.

How can I run a windows batch file but hide the command window?

Create a shortcut to your bat file by using the right-click and selecting Create shortcut. Right-click on the shortcut you created and click on properties. Click on the Run drop-down box and select Minimized.

How to run a PowerShell script

Type:

powershell -executionpolicy bypass -File .\Test.ps1

NOTE: Here Test.ps1 is the PowerShell script.

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Batch files - number of command line arguments

The function :getargc below may be what you're looking for.

@echo off
setlocal enableextensions enabledelayedexpansion
call :getargc argc %*
echo Count is %argc%
echo Args are %*
endlocal
goto :eof

:getargc
    set getargc_v0=%1
    set /a "%getargc_v0% = 0"
:getargc_l0
    if not x%2x==xx (
        shift
        set /a "%getargc_v0% = %getargc_v0% + 1"
        goto :getargc_l0
    )
    set getargc_v0=
    goto :eof

It basically iterates once over the list (which is local to the function so the shifts won't affect the list back in the main program), counting them until it runs out.

It also uses a nifty trick, passing the name of the return variable to be set by the function.

The main program just illustrates how to call it and echos the arguments afterwards to ensure that they're untouched:

C:\Here> xx.cmd 1 2 3 4 5
    Count is 5
    Args are 1 2 3 4 5
C:\Here> xx.cmd 1 2 3 4 5 6 7 8 9 10 11
    Count is 11
    Args are 1 2 3 4 5 6 7 8 9 10 11
C:\Here> xx.cmd 1
    Count is 1
    Args are 1
C:\Here> xx.cmd
    Count is 0
    Args are
C:\Here> xx.cmd 1 2 "3 4 5"
    Count is 3
    Args are 1 2 "3 4 5"

Random number from a range in a Bash Script

and here's one with Python

randport=$(python -S -c "import random; print random.randrange(2000,63000)")

and one with awk

awk 'BEGIN{srand();print int(rand()*(63000-2000))+2000 }'

Unable to set variables in bash script

Five problems:

  1. Don't put a space before or after the equal sign.
  2. Use "$(...)" to get the output of a command as text.
  3. [ is a command. Put a space between it and the arguments.
  4. Commands are case-sensitive. You want echo.
  5. Use double quotes around variables. rm "$folderToBeMoved"

Purpose of #!/usr/bin/python3 shebang

Actually the determination of what type of file a file is very complicated, so now the operating system can't just know. It can make lots of guesses based on -

  • extension
  • UTI
  • MIME

But the command line doesn't bother with all that, because it runs on a limited backwards compatible layer, from when that fancy nonsense didn't mean anything. If you double click it sure, a modern OS can figure that out- but if you run it from a terminal then no, because the terminal doesn't care about your fancy OS specific file typing APIs.

Regarding the other points. It's a convenience, it's similarly possible to run

python3 path/to/your/script

If your python isn't in the path specified, then it won't work, but we tend to install things to make stuff like this work, not the other way around. It doesn't actually matter if you're under *nix, it's up to your shell whether to consider this line because it's a shellcode. So for example you can run bash under Windows.

You can actually ommit this line entirely, it just mean the caller will have to specify an interpreter. Also don't put your interpreters in nonstandard locations and then try to call scripts without providing an interpreter.

How to make an "alias" for a long path?

Put the following line in your myscript

set myFold = '~/Files/Scripts/Main'

In the terminal use

source myscript
cd $myFold

How to redirect the output of a PowerShell to a file during its execution

Microsoft has announced on Powershell's Connections web site (2012-02-15 at 4:40 PM) that in version 3.0 they have extended the redirection as a solution to this problem.

In PowerShell 3.0, we've extended output redirection to include the following streams: 
 Pipeline (1) 
 Error    (2) 
 Warning  (3) 
 Verbose  (4) 
 Debug    (5)
 All      (*)

We still use the same operators
 >    Redirect to a file and replace contents
 >>   Redirect to a file and append to existing content
 >&1  Merge with pipeline output

See the "about_Redirection" help article for details and examples.

help about_Redirection

How to mkdir only if a directory does not already exist?

directory_name = "foo"

if [ -d $directory_name ]
then
    echo "Directory already exists"
else
    mkdir $directory_name
fi

Refresh or force redraw the fragment

detach().detach() not working after support library update 25.1.0 (may be earlier). This solution works fine after update:

getSupportFragmentManager()
    .beginTransaction()
    .detach(oldFragment)
    .commitNowAllowingStateLoss();

getSupportFragmentManager()
    .beginTransaction()
    .attach(oldFragment)
    .commitAllowingStateLoss();

Create PostgreSQL ROLE (user) if it doesn't exist

Some answers suggested to use pattern: check if role does not exist and if not then issue CREATE ROLE command. This has one disadvantage: race condition. If somebody else creates a new role between check and issuing CREATE ROLE command then CREATE ROLE obviously fails with fatal error.

To solve above problem, more other answers already mentioned usage of PL/pgSQL, issuing CREATE ROLE unconditionally and then catching exceptions from that call. There is just one problem with these solutions. They silently drop any errors, including those which are not generated by fact that role already exists. CREATE ROLE can throw also other errors and simulation IF NOT EXISTS should silence only error when role already exists.

CREATE ROLE throw duplicate_object error when role already exists. And exception handler should catch only this one error. As other answers mentioned it is a good idea to convert fatal error to simple notice. Other PostgreSQL IF NOT EXISTS commands adds , skipping into their message, so for consistency I'm adding it here too.

Here is full SQL code for simulation of CREATE ROLE IF NOT EXISTS with correct exception and sqlstate propagation:

DO $$
BEGIN
CREATE ROLE test;
EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
END
$$;

Test output (called two times via DO and then directly):

$ sudo -u postgres psql
psql (9.6.12)
Type "help" for help.

postgres=# \set ON_ERROR_STOP on
postgres=# \set VERBOSITY verbose
postgres=# 
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
DO
postgres=# 
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
NOTICE:  42710: role "test" already exists, skipping
LOCATION:  exec_stmt_raise, pl_exec.c:3165
DO
postgres=# 
postgres=# CREATE ROLE test;
ERROR:  42710: role "test" already exists
LOCATION:  CreateRole, user.c:337

Spring JPA selecting specific columns

With the newer Spring versions One can do as follows:

If not using native query this can done as below:

public interface ProjectMini {
    String getProjectId();
    String getProjectName();
}

public interface ProjectRepository extends JpaRepository<Project, String> { 
    @Query("SELECT p FROM Project p")
    List<ProjectMini> findAllProjectsMini();
}

Using native query the same can be done as below:

public interface ProjectRepository extends JpaRepository<Project, String> { 
    @Query(value = "SELECT projectId, projectName FROM project", nativeQuery = true)
    List<ProjectMini> findAllProjectsMini();
}

For detail check the docs

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

To use an identity column in v10,

ALTER TABLE test 
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;

For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.

For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.

For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.

Initializing IEnumerable<string> In C#

You cannot instantiate an interface - you must provide a concrete implementation of IEnumerable.

In Perl, how do I create a hash whose keys come from a given array?

 @hash{@array} = (1) x @array;

It's a hash slice, a list of values from the hash, so it gets the list-y @ in front.

From the docs:

If you're confused about why you use an '@' there on a hash slice instead of a '%', think of it like this. The type of bracket (square or curly) governs whether it's an array or a hash being looked at. On the other hand, the leading symbol ('$' or '@') on the array or hash indicates whether you are getting back a singular value (a scalar) or a plural one (a list).

How to stretch the background image to fill a div

body{
  margin:0;
  background:url('image.png') no-repeat 50% 50% fixed;
  background-size: cover;
}

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

Can not change UILabel text color

May be the better way is

UIColor *color = [UIColor greenColor];
[self.myLabel setTextColor:color];

Thus we have colored text

Utilizing multi core for tar+gzip/bzip compression/decompression

You can also use the tar flag "--use-compress-program=" to tell tar what compression program to use.

For example use:

tar -c --use-compress-program=pigz -f tar.file dir_to_zip 

String contains - ignore case

You can use

org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
                                     CharSequence searchStr);

Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).

A null CharSequence will return false.

This one will be better than regex as regex is always expensive in terms of performance.

For official doc, refer to : StringUtils.containsIgnoreCase

Update :

If you are among the ones who

  • don't want to use Apache commons library
  • don't want to go with the expensive regex/Pattern based solutions,
  • don't want to create additional string object by using toLowerCase,

you can implement your own custom containsIgnoreCase using java.lang.String.regionMatches

public boolean regionMatches(boolean ignoreCase,
                             int toffset,
                             String other,
                             int ooffset,
                             int len)

ignoreCase : if true, ignores case when comparing characters.

public static boolean containsIgnoreCase(String str, String searchStr)     {
    if(str == null || searchStr == null) return false;

    final int length = searchStr.length();
    if (length == 0)
        return true;

    for (int i = str.length() - length; i >= 0; i--) {
        if (str.regionMatches(true, i, searchStr, 0, length))
            return true;
    }
    return false;
}

Position of a string within a string using Linux shell script?

I used awk for this

a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'

How to solve "Connection reset by peer: socket write error"?

I've got the same exception and in my case the problem was in a renegotiation procecess. In fact my client closed a connection when the server tried to change a cipher suite. After digging it appears that in the jdk 1.6 update 22 renegotiation process is disabled by default. If your security constraints can effort this, try to enable the unsecure renegotiation by setting the sun.security.ssl.allowUnsafeRenegotiation system property to true. Here is some information about the process:

Session renegotiation is a mechanism within the SSL protocol that allows the client or the server to trigger a new SSL handshake during an ongoing SSL communication. Renegotiation was initially designed as a mechanism to increase the security of an ongoing SSL channel, by triggering the renewal of the crypto keys used to secure that channel. However, this security measure isn't needed with modern cryptographic algorithms. Additionally, renegotiation can be used by a server to request a client certificate (in order to perform client authentication) when the client tries to access specific, protected resources on the server.

Additionally there is the excellent post about this issue in details and written in (IMHO) understandable language.

Converting BitmapImage to Bitmap and vice versa

Thanks Guillermo Hernandez, I created a variation of your code that works. I added the namespaces in this code for reference.

System.Reflection.Assembly theAsm = Assembly.LoadFrom("My.dll");
// Get a stream to the embedded resource
System.IO.Stream stream = theAsm.GetManifestResourceStream(@"picture.png");

// Here is the most important part:
System.Windows.Media.Imaging.BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.StreamSource = stream;
bmi.EndInit();

How can I check if char* variable points to empty string?

Give it a chance:

Try getting string via function gets(string) then check condition as if(string[0] == '\0')

CSV new-line character seen in unquoted field error

Try to run dos2unix on your windows imported files first

HTML checkbox - allow to check only one checkbox

sapSet = mbo.getThisMboSet()
sapCount = sapSet.count()
saplist = []

if sapCount > 1:
   for i in range(sapCount):`enter code here`
     defaultCheck = sapSet.getMbo(i)
     saplist.append(defaultCheck.getInt("HNADEFACC"))
   defCount = saplist.count(1)
   if defCount > 1:
      errorgroup = " Please Note: you are allowed"
      errorkey = "  only One Default Account"
   if defCount < 1:
      errorgroup = " Please enter "
      errorkey = "  at leat One Default Account"
else:
   mbo.setValue("HNADEFACC",1,MboConstants.NOACCESSCHECK)

Page redirect with successful Ajax request

I suppose you could attack this in two ways;

1) insert window.location = 'http://www.yourdomain.com into the success function.

2) Use a further ajax call an inject this into an element on your page, further info on which you can find in the jQuery docs at http://api.jquery.com/jQuery.get/

What does the 'export' command do?

In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. that means the changes you made become effective in new shell sessions. The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.

What is the use of join() in Python threading?

With join - interpreter will wait until your process get completed or terminated

>>> from threading import Thread
>>> import time
>>> def sam():
...   print 'started'
...   time.sleep(10)
...   print 'waiting for 10sec'
... 
>>> t = Thread(target=sam)
>>> t.start()
started

>>> t.join() # with join interpreter will wait until your process get completed or terminated
done?   # this line printed after thread execution stopped i.e after 10sec
waiting for 10sec
>>> done?

without join - interpreter wont wait until process get terminated,

>>> t = Thread(target=sam)
>>> t.start()
started
>>> print 'yes done' #without join interpreter wont wait until process get terminated
yes done
>>> waiting for 10sec

How do I make flex box work in safari?

Maybe this would be useful

-webkit-justify-content: space-around;

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Linux bash: Multiple variable assignment

Chapter 5 of the Bash Cookbook by O'Reilly, discusses (at some length) the reasons for the requirement in a variable assignment that there be no spaces around the '=' sign

MYVAR="something"

The explanation has something to do with distinguishing between the name of a command and a variable (where '=' may be a valid argument).

This all seems a little like justifying after the event, but in any case there is no mention of a method of assigning to a list of variables.

Clear icon inside input text

jQuery Mobile now has this built in:

<input type="text" name="clear" id="clear-demo" value="" data-clear-btn="true">

Jquery Mobile API TextInput docs

How to read all rows from huge table?

I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.

In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request: http://www.petefreitag.com/item/451.cfm

PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html

How to use callback with useState hook in react

Another way to achieve this:

_x000D_
_x000D_
const [Name, setName] = useState({val:"", callback: null});_x000D_
React.useEffect(()=>{_x000D_
  console.log(Name)_x000D_
  const {callback} = Name;_x000D_
  callback && callback();_x000D_
}, [Name]);_x000D_
setName({val:'foo', callback: ()=>setName({val: 'then bar'})})
_x000D_
_x000D_
_x000D_

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays in JS have two types of properties:

Regular elements and associative properties (which are nothing but objects)

When you define a = new Array(), you are defining an empty array. Note that there are no associative objects yet

When you define b = new Array(2), you are defining an array with two undefined locations.

In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.

console.log (a) or console.log(b) prints the array elements i.e. [] and [undefined, undefined] respectively. But since a1/a2 and b1/b2 are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2) kind of syntax

Vue.js dynamic images not working

I got this working by following code

  getImgUrl(pet) {
    var images = require.context('../assets/', false, /\.png$/)
    return images('./' + pet + ".png")
  }

and in HTML:

<div class="col-lg-2" v-for="pic in pics">
   <img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>

But not sure why my earlier approach did not work.

Best way to incorporate Volley (or other library) into Android Studio project

LATEST UPDATE:

Use the official version from jCenter instead.

dependencies {
    compile 'com.android.volley:volley:1.0.0'
}

The dependencies below points to deprecated volley that is no longer maintained.

ORIGINAL ANSWER

You can use this in dependency section of your build.gradle file to use volley

  dependencies {
      compile 'com.mcxiaoke.volley:library-aar:1.0.0'
  }

UPDATED:

Its not official but a mirror copy of official Volley. It is regularly synced and updated with official Volley Repository so you can go ahead to use it without any worry.

https://github.com/mcxiaoke/android-volley

If else in stored procedure sql server

if not exists (select dist_id from tbl_stock where dist_id= @cust_id and item_id=@item_id)
    insert into tbl_stock(dist_id,item_id,qty)values(@cust_id, @item_id, @qty); 
else
    update tbl_stock set qty=(qty + @qty) where dist_id= @cust_id and item_id= @item_id;

Measuring the distance between two coordinates in PHP

The multiplier is changed at every coordinate because of the great circle distance theory as written here :

http://en.wikipedia.org/wiki/Great-circle_distance

and you can calculate the nearest value using this formula described here:

http://en.wikipedia.org/wiki/Great-circle_distance#Worked_example

the key is converting each degree - minute - second value to all degree value:

N 36°7.2', W 86°40.2'  N = (+) , W = (-), S = (-), E = (+) 
referencing the Greenwich meridian and Equator parallel

(phi)     36.12° = 36° + 7.2'/60' 

(lambda)  -86.67° = 86° + 40.2'/60'

UPDATE and REPLACE part of a string

you should use the below update query

UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id IN(1, 2, 3, 4)

UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id <= 4

Either of the above queries should work.

How to force uninstallation of windows service

Refreshing the service list always did it for me. If the services window is open, it will hold some memory of it existing for some reason. F5 and I'm reinstalling again!

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

Look at ?par for the various graphics parameters.

In general cex controls size, col controls colour. If you want to control the colour of a label, the par is col.lab, the colour of the axis annotations col.axis, the colour of the main text, col.main etc. The names are quite intuitive, once you know where to begin.

For example

x <- 1:10
y <- 1:10

plot(x , y,xlab="x axis", ylab="y axis",  pch=19, col.axis = 'blue', col.lab = 'red', cex.axis = 1.5, cex.lab = 2)

enter image description here

If you need to change the colour / style of the surrounding box and axis lines, then look at ?axis or ?box, and you will find that you will be using the same parameter names within calls to box and axis.

You have a lot of control to make things however you wish.

eg

plot(x , y,xlab="x axis", ylab="y axis",  pch=19,  cex.lab = 2, axes = F,col.lab = 'red')
box(col = 'lightblue')
axis(1, col = 'blue', col.axis = 'purple', col.ticks = 'darkred', cex.axis = 1.5, font = 2, family = 'serif')
axis(2, col = 'maroon', col.axis = 'pink', col.ticks = 'limegreen', cex.axis = 0.9, font =3, family = 'mono')

enter image description here

Which is seriously ugly, but shows part of what you can control

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

The steps that worked for me (XCode 8.3.3/XCode 9 beta with a Swift 3.1 project)

 - Navigate to your project directory
 - pod install //which then asks you to do the next step
 - pod repo update //takes a while to update the repo
 - pod update
 - pod install
 - Close Xcode session
 - Open and Clean the project
 - Build/Run

Also make sure you open the .xcworkspace file rather than the project file (.xcodeproj) when working with pods. That should solve any errors with linking such as "Apple Mach -O Linker command failed"

How to make a node.js application run permanently?

I’ve found forever to do the job perfectly fine.

Assuming you already have npm installed, if not, just do

sudo apt-get install npm

Then install forever

npm install forever --global

Now you can run it like this

forever start app.js

https://codingweb.io/run-nodejs-application-background/

How to set component default props on React component

For those using something like babel stage-2 or transform-class-properties:

import React, { PropTypes, Component } from 'react';

export default class ExampleComponent extends Component {
   static contextTypes = {
      // some context types
   };

   static propTypes = {
      prop1: PropTypes.object
   };

   static defaultProps = {
      prop1: { foobar: 'foobar' }
   };

   ...

}

Update

As of React v15.5, PropTypes was moved out of the main React Package (link):

import PropTypes from 'prop-types';

Edit

As pointed out by @johndodo, static class properties are actually not a part of the ES7 spec, but rather are currently only supported by babel. Updated to reflect that.

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

How to automatically allow blocked content in IE?

I believe this will only appear when running the page locally in this particular case, i.e. you should not see this when loading the apge from a web server.

However if you have permission to do so, you could turn off the prompt for Internet Explorer by following Tools (menu) → Internet OptionsSecurity (tab) → Custom Level (button) → and Disable Automatic prompting for ActiveX controls.

This will of course, only affect your browser.

how to set image from url for imageView

You can use either Picasso or Glide.

Picasso.with(context)
   .load(your_url)
   .into(imageView);


Glide.with(context)
   .load(your_url)
   .into(imageView);

Internet Access in Ubuntu on VirtualBox

How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc.

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

If you use Java and spring MVC you just need to add the following annotation to your method returning your page :

@CrossOrigin(origins = "*")

"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.

Possible to access MVC ViewBag object from Javascript file?

For CoreMVC 3.1, that would be,

@using Newtonsoft.Json
var listInJs =  @Html.Raw(JsonConvert.SerializeObject(ViewBag.SomeGenericList));

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

In my instance, I was running an abnormal query to fix data. If you lock the tables in your query, then you won't have to deal with the Lock timeout:

LOCK TABLES `customer` WRITE;
update customer set account_import_id = 1;
UNLOCK TABLES;

This is probably not a good idea for normal use.

For more info see: MySQL 8.0 Reference Manual

How to get a list of images on docker registry v2

For the latest (as of 2015-07-31) version of Registry V2, you can get this image from DockerHub:

docker pull distribution/registry:master

List all repositories (effectively images):

curl -X GET https://myregistry:5000/v2/_catalog
> {"repositories":["redis","ubuntu"]}

List all tags for a repository:

curl -X GET https://myregistry:5000/v2/ubuntu/tags/list
> {"name":"ubuntu","tags":["14.04"]}

Debugging Stored Procedure in SQL Server 2008

One requirement for remote debugging is that the windows account used to run SSMS be part of the sysadmin role. See this MSDN link: http://msdn.microsoft.com/en-us/library/cc646024%28v=sql.105%29.aspx

What's the use of "enum" in Java?

An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Here is some code that shows you how to use the Day enum defined above:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;

            case FRIDAY:
                System.out.println("Fridays are better.");
                break;

            case SATURDAY: case SUNDAY:
                System.out.println("Weekends are best.");
                break;

            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();
        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();
        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.tellItLikeItIs();
    }
}

The output is:

Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.

Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

for (Planet p : Planet.values()) {
    System.out.printf("Your weight on %s is %f%n",
                      p, p.surfaceWeight(mass));
}

In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}

If you run Planet.class from the command line with an argument of 175, you get this output:

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413

Source: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

C# Reflection: How to get class reference from string?

You will want to use the Type.GetType method.

Here is a very simple example:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Foo");
        MethodInfo method 
             = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);

        method.Invoke(null, null);
    }
}

class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

I say simple because it is very easy to find a type this way that is internal to the same assembly. Please see Jon's answer for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.

From a Sybase Database, how I can get table description ( field names and types)?

If Sybase is SQL-92 compliant then this information is stored within the INFORMATION_SCHEMA tables.

So the following will give you a list of tables and views in any SQL-92 compliant database

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES

How do I convert ticks to minutes?

A single tick represents one hundred nanoseconds or one ten-millionth of a second. FROM MSDN.

So 28 000 000 000 * 1/10 000 000 = 2 800 sec. 2 800 sec /60 = 46.6666min

Or you can do it programmaticly with TimeSpan:

    static void Main()
    {
        TimeSpan ts = TimeSpan.FromTicks(28000000000);
        double minutesFromTs = ts.TotalMinutes;
        Console.WriteLine(minutesFromTs);
        Console.Read();
    }

Both give me 46 min and not 480 min...

Remove grid, background color, and top and right borders from ggplot2

Recent updates to ggplot (0.9.2+) have overhauled the syntax for themes. Most notably, opts() is now deprecated, having been replaced by theme(). Sandy's answer will still (as of Jan '12) generates a chart, but causes R to throw a bunch of warnings.

Here's updated code reflecting current ggplot syntax:

library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))

#base ggplot object
p <- ggplot(df, aes(x = a, y = b))

p +
  #plots the points
  geom_point() +

  #theme with white background
  theme_bw() +

  #eliminates background, gridlines, and chart border
  theme(
    plot.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank()
  ) +

  #draws x and y axis line
  theme(axis.line = element_line(color = 'black'))

generates:

plot output

How to manually reload Google Map with JavaScript

You can refresh with this:

map.panBy(0, 0);

Find row in datatable with specific id

Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.

 public  DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
    {
        TempTable = RecordDT_;
        DataView DV = new DataView(TempTable);
        DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
        return DV.ToTable();
    }

and simply call it as shown below;

  DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);

where 5 is the ID. Thanks..

Using success/error/finally/catch with Promises in AngularJS

I think the previous answers are correct, but here is another example (just a f.y.i, success() and error() are deprecated according to AngularJS Main page:

$http
    .get('http://someendpoint/maybe/returns/JSON')
    .then(function(response) {
        return response.data;
    }).catch(function(e) {
        console.log('Error: ', e);
        throw e;
    }).finally(function() {
        console.log('This finally block');
    });

How to set cornerRadius for only top-left and top-right corner of a UIView?

A lovely extension to reuse Yunus Nedim Mehel solution

Swift 2.3

extension UIView {
func roundCornersWithLayerMask(cornerRadii: CGFloat, corners: UIRectCorner) {
    let path = UIBezierPath(roundedRect: bounds,
                            byRoundingCorners: corners,
                            cornerRadii: CGSize(width: cornerRadii, height: cornerRadii))
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.CGPath
    layer.mask = maskLayer
} }

Usage

let view = UIView()
view.roundCornersWithLayerMask(10,[.TopLeft,.TopRight])

Best practices for API versioning?

This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.

Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.

On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.

Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.

This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).

Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.

Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.

A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.

From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.

From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.

However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!

The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:

  • develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).

  • bind to a specific version of the API (which becomes apparent) but only for a limited time

For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):

http://shonzilla/api/customers/1234
http://shonzilla/api/v3.0/customers/1234
http://shonzilla/api/v3/customers/1234

In addition, API clients that still try to point to the old API should be informed to use the latest previous API version, if the API version they're using is obsolete or not supported anymore. So accessing any of the obsolete URIs like these:

http://shonzilla/api/v2.2/customers/1234
http://shonzilla/api/v2.0/customers/1234
http://shonzilla/api/v2/customers/1234
http://shonzilla/api/v1.1/customers/1234
http://shonzilla/api/v1/customers/1234

should return any of the 30x HTTP status codes that indicate redirection that are used in conjunction with Location HTTP header that redirects to the appropriate version of resource URI which remain to be this one:

http://shonzilla/api/customers/1234

There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:

  • 301 Moved permanently indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a versioned resource URI been replaced by a resource permalink.

  • 302 Found indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).

  • other scenarios can be found in Redirection 3xx chapter of HTTP 1.1 specification

How to override application.properties during production in Spring-Boot?

I have found the following has worked for me:

java -jar my-awesome-java-prog.jar --spring.config.location=file:/path-to-config-dir/

with file: added.

LATE EDIT

Of course, this command line is never run as it is in production.

Rather I have

  • [possibly several layers of] shell scripts in source control with place holders for all parts of the command that could change (name of the jar, path to config...)
  • ansible deployment scripts that will deploy the shell scripts and replace the place holders by the actual value.

How do I download a binary file over HTTP?

The simplest way is the platform-specific solution:

 #!/usr/bin/env ruby
`wget http://somedomain.net/flv/sample/sample.flv`

Probably you are searching for:

require 'net/http'
# Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
Net::HTTP.start("somedomain.net") do |http|
    resp = http.get("/flv/sample/sample.flv")
    open("sample.flv", "wb") do |file|
        file.write(resp.body)
    end
end
puts "Done."

Edit: Changed. Thank You.

Edit2: The solution which saves part of a file while downloading:

# instead of http.get
f = open('sample.flv')
begin
    http.request_get('/sample.flv') do |resp|
        resp.read_body do |segment|
            f.write(segment)
        end
    end
ensure
    f.close()
end

jQuery has deprecated synchronous XMLHTTPRequest

This happened to me by having a link to external js outside the head just before the end of the body section. You know, one of these:

<script src="http://somesite.net/js/somefile.js">

It did not have anything to do with JQuery.

You would probably see the same doing something like this:

var script = $("<script></script>");
script.attr("src", basepath + "someotherfile.js");
$(document.body).append(script);

But I haven't tested that idea.

Converting between datetime, Timestamp and datetime64

Some solutions work well for me but numpy will deprecate some parameters. The solution that work better for me is to read the date as a pandas datetime and excract explicitly the year, month and day of a pandas object. The following code works for the most common situation.

def format_dates(dates):
    dt = pd.to_datetime(dates)
    try: return [datetime.date(x.year, x.month, x.day) for x in dt]    
    except TypeError: return datetime.date(dt.year, dt.month, dt.day)

Convert String to Type in C#

If you really want to get the type by name you may use the following:

System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");

Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.

setTimeout or setInterval?

Both setInterval and setTimeout return a timer id that you can use to cancel the execution, that is, before the timeouts are triggered. To cancel you call either clearInterval or clearTimeout like this:

var timeoutId = setTimeout(someFunction, 1000);
clearTimeout(timeoutId);
var intervalId = setInterval(someFunction, 1000),
clearInterval(intervalId);

Also, the timeouts are automatically cancelled when you leave the page or close the browser window.

What is the difference between a HashMap and a TreeMap?

You almost always use HashMap, you should only use TreeMap if you need your keys to be in a specific order.

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

How to sort the letters in a string alphabetically in Python

Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().

from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])

sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']

tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')

We are selecting the last index (-1) of the tuple

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding (or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:

sys.stdout.buffer.write(some_bytes_object)

This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.

Ruby: kind_of? vs. instance_of? vs. is_a?

It is more Ruby-like to ask objects whether they respond to a method you need or not, using respond_to?. This allows both minimal interface and implementation unaware programming.

It is not always applicable of course, thus there is still a possibility to ask about more conservative understanding of "type", which is class or a base class, using the methods you're asking about.

Override devise registrations controller

You can generate views and controllers for devise customization.

Use

rails g devise:controllers users -c=registrations

and

rails g devise:views 

It will copy particular controllers and views from gem to your application.

Next, tell the router to use this controller:

devise_for :users, :controllers => {:registrations => "users/registrations"}

Print debugging info from stored procedure in MySQL

Option 1: Put this in your procedure to print 'comment' to stdout when it runs.

SELECT 'Comment';

Option 2: Put this in your procedure to print a variable with it to stdout:

declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);

This prints myvar is 5 to stdout when the procedure runs.

Option 3, Create a table with one text column called tmptable, and push messages to it:

declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);

You could put the above in a stored procedure, so all you would have to write is this:

CALL log(concat('the value is', myvar));

Which saves a few keystrokes.

Option 4, Log messages to file

select "penguin" as log into outfile '/tmp/result.txt';

There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.

Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.

WCF, Service attribute value in the ServiceHost directive could not be found

This may sound trivial, but worth mentioning: You have to build the service (in Visual Studio) - then a DLL will be created in the bin subfolder.

When the service is "deployed" on a server - that bin folder needs to have that DLL file in it - otherwise this error will be thrown...

Is it possible to put CSS @media rules inline?

Hey I just wrote it.

Now you can use <div style="color: red; @media (max-width: 200px) { color: green }"> or so.

Enjoy.

Drop all data in a pandas dataframe

If your goal is to drop the dataframe, then you need to pass all columns. For me: the best way is to pass a list comprehension to the columns kwarg. This will then work regardless of the different columns in a df.

import pandas as pd

web_stats = {'Day': [1, 2, 3, 4, 2, 6],
             'Visitors': [43, 43, 34, 23, 43, 23],
             'Bounce_Rate': [3, 2, 4, 3, 5, 5]}
df = pd.DataFrame(web_stats)

df.drop(columns=[i for i in check_df.columns])

How to style a disabled checkbox?

If you're trying to stop someone from updating the checkbox so it appears disabled then just use JQuery

$('input[type=checkbox]').click(false);

You can then style the checkbox.

How to set up a PostgreSQL database in Django

Please note that installation of psycopg2 via pip or setup.py requires to have Visual Studio 2008 (more precisely executable file vcvarsall.bat). If you don't have admin rights to install it or set the appropriate PATH variable on Windows, you can download already compiled library from here.

Creating an iframe with given HTML dynamically

Allthough your src = encodeURI should work, I would have gone a different way:

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

As this has no x-domain restraints and is completely done via the iframe handle, you may access and manipulate the contents of the frame later on. All you need to make sure of is, that the contents have been rendered, which will (depending on browser type) start during/after the .write command is issued - but not nescessarily done when close() is called.

A 100% compatible way of doing a callback could be this approach:

<html><body onload="parent.myCallbackFunc(this.window)"></body></html>

Iframes has the onload event, however. Here is an approach to access the inner html as DOM (js):

iframe.onload = function() {
   var div=iframe.contentWindow.document.getElementById('mydiv');
};

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

It's a long time since the question was posted, but I experienced the same issue in a similar scenario. I have a console application and I was consuming a web service and our IIS server where the webservice was placed has windows authentication (NTLM) enabled.

I followed this link and that fixed my problem. Here's the sample code for App.config:

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="Service1Soap">
                <security mode="TransportCredentialOnly">
                    <transport clientCredentialType="Ntlm" proxyCredentialType="None"
                        realm=""/>
                    <message clientCredentialType="UserName" algorithmSuite="Default"/>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost/servicename/service1.asmx" 
            binding="basicHttpBinding" bindingConfiguration="ListsSoap"/>
    </client>
</system.serviceModel>

What does a bitwise shift (left or right) do and what is it used for?

Here is an example:

#include"stdio.h"
#include"conio.h"

void main()
{
    int rm, vivek;
    clrscr();
    printf("Enter any numbers\t(E.g., 1, 2, 5");
    scanf("%d", &rm); // rm = 5(0101) << 2 (two step add zero's), so the value is 10100
    printf("This left shift value%d=%d", rm, rm<<4);
    printf("This right shift value%d=%d", rm, rm>>2);
    getch();
}

For loop in Oracle SQL

You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.

With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.

http://www.dba-oracle.com/t_with_clause.htm

http://www.orafaq.com/node/55

It requires some effort though. Don't be afraid to post a concrete example.

Using simple pseudo table DUAL helps too.

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:

    ObjectMapper mapper = new ObjectMapper();
    String www = "www.sample.pl";
    Weather weather = mapper.readValue(www, Weather.class);

But this will:

    ObjectMapper mapper = new ObjectMapper();
    URL www = new URL("http://www.oracle.com/");
    Weather weather = mapper.readValue(www, Weather.class);

How to move all HTML element children to another parent using JavaScript?

Here's a simple function:

function setParent(el, newParent)
{
    newParent.appendChild(el);
}

el's childNodes are the elements to be moved, newParent is the element el will be moved to, so you would execute the function like:

var l = document.getElementById('old-parent').childNodes.length;
var a = document.getElementById('old-parent');
var b = document.getElementById('new-parent');
for (var i = l; i >= 0; i--)
{
    setParent(a.childNodes[0], b);
}

Here is the Demo

How to count items in JSON object using command line?

A simple solution is to install jshon library :

jshon -l < /tmp/test.json
2

How to set page content to the middle of screen?

Solution for the code you posted:

.center{
    position:absolute;
    width:780px;
    height:650px;
    left:50%;
    top:50%;
    margin-left:-390px;
    margin-top:-325px;
}

<table class="center" width="780" border="0" align="center" cellspacing="2" bordercolor="#000000" bgcolor="#FFCC66">
      <tr>
        <td>
        <table width="100%" border="0">
      <tr>
        <td>
        <table width="100%" border="0">
        <tr>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
            <td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>        
        </tr>
        </table>
        </td>
      </tr>
      <tr>
        <td>
        <table width="100%" border="0">
        <tr>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
            <td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>        
        </tr>
        </table>
        </td>
      </tr>
</table>

--

How this works?

Example: http://jsfiddle.net/953Yj/

<div class="center">
    Lorem ipsum
</div>

.center{
    position:absolute;
    height: X px;
    width: Y px;
    left:50%;
    top:50%;
    margin-top:- X/2 px;
    margin-left:- Y/2 px;
}
  • X would your your height.
  • Y would be your width.

To position the div vertically and horizontally, divide X and Y by 2.

How to convert entire dataframe to numeric while preserving decimals?

> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
     a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
        a         b 
"numeric" "numeric" 

Split array into chunks

This is what i use, it might not be super fast, but it is compact and simple:

_x000D_
_x000D_
let chunksplit = (stream, size) => stream.reduce((chunks, item, idx, arr) => (idx % size == 0) ? [...chunks, arr.slice(idx, idx + size)] : chunks, []);_x000D_
//if the index is a multiple of the chunksize, add new array_x000D_
_x000D_
let testArray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];_x000D_
_x000D_
document.write(JSON.stringify( chunksplit(testArray, 5) ));_x000D_
//using JSON.stringify for the nested arrays to be shown
_x000D_
_x000D_
_x000D_

Ansible - Use default if a variable is not defined

If anybody is looking for an option which handles nested variables, there are several such options in this github issue.

In short, you need to use "default" filter for every level of nested vars. For a variable "a.nested.var" it would look like:

- hosts: 'localhost'
  tasks:
    - debug:
        msg: "{{ ((a | default({})).nested | default({}) ).var | default('bar') }}"

or you could set default values of empty dicts for each level of vars, maybe using "combine" filter. Or use "json_query" filter. But the option I chose seems simpler to me if you have only one level of nesting.

React - Display loading screen while DOM is rendering?

If anyone looking for a drop-in, zero-config and zero-dependencies library for the above use-case, try pace.js (http://github.hubspot.com/pace/docs/welcome/).

It automatically hooks to events (ajax, readyState, history pushstate, js event loop etc) and show a customizable loader.

Worked well with our react/relay projects (handles navigation changes using react-router, relay requests) (Not affliated; had used pace.js for our projects and it worked great)

How to get the selected date of a MonthCalendar control in C#

Using SelectionRange you will get the Start and End date.

private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
    var startDate = monthCalendar1.SelectionRange.Start.ToString("dd MMM yyyy");
    var endDate = monthCalendar1.SelectionRange.End.ToString("dd MMM yyyy");
}

If you want to update the maximum number of days that can be selected, then set MaxSelectionCount property. The default is 7.

// Only allow 21 days to be selected at the same time.
monthCalendar1.MaxSelectionCount = 21;

Unique Key constraints for multiple columns in Entity Framework

I found three ways to solve the problem.

Unique indexes in EntityFramework Core:

First approach:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Entity>()
   .HasIndex(p => new {p.FirstColumn , p.SecondColumn}).IsUnique();
}

The second approach to create Unique Constraints with EF Core by using Alternate Keys.

Examples

One column:

modelBuilder.Entity<Blog>().HasAlternateKey(c => c.SecondColumn).HasName("IX_SingeColumn");

Multiple columns:

modelBuilder.Entity<Entity>().HasAlternateKey(c => new [] {c.FirstColumn, c.SecondColumn}).HasName("IX_MultipleColumns");

EF 6 and below:


First approach:

dbContext.Database.ExecuteSqlCommand(string.Format(
                        @"CREATE UNIQUE INDEX LX_{0} ON {0} ({1})", 
                                 "Entitys", "FirstColumn, SecondColumn"));

This approach is very fast and useful but the main problem is that Entity Framework doesn't know anything about those changes!


Second approach:
I found it in this post but I did not tried by myself.

CreateIndex("Entitys", new string[2] { "FirstColumn", "SecondColumn" },
              true, "IX_Entitys");

The problem of this approach is the following: It needs DbMigration so what do you do if you don't have it?


Third approach:
I think this is the best one but it requires some time to do it. I will just show you the idea behind it: In this link http://code.msdn.microsoft.com/CSASPNETUniqueConstraintInE-d357224a you can find the code for unique key data annotation:

[UniqueKey] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey] // Unique Key 
public int SecondColumn  { get; set;}

// The problem hier
1, 1  = OK 
1 ,2  = NO OK 1 IS UNIQUE

The problem for this approach; How can I combine them? I have an idea to extend this Microsoft implementation for example:

[UniqueKey, 1] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey ,1] // Unique Key 
public int SecondColumn  { get; set;}

Later in the IDatabaseInitializer as described in the Microsoft example you can combine the keys according to the given integer. One thing has to be noted though: If the unique property is of type string then you have to set the MaxLength.

how to use jQuery ajax calls with node.js

Use something like the following on the server side:

http.createServer(function (request, response) {
    if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
        // handle async request
        var u = url.parse(request.url, true); //not needed

        response.writeHead(200, {'content-type':'text/json'})
        response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
    } else {
        // handle sync request (by server index.html)
        if (request.url == '/') {
            response.writeHead(200, {'content-type': 'text/html'})
            util.pump(fs.createReadStream('index.html'), response)
        } 
        else 
        {
            // 404 error
        }
    }
}).listen(31337)

How to sort a dataFrame in python pandas by two or more columns?

As of the 0.17.0 release, the sort method was deprecated in favor of sort_values. sort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:

df.sort_values(['a', 'b'], ascending=[True, False])

You can use the ascending argument of sort:

df.sort(['a', 'b'], ascending=[True, False])

For example:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

As commented by @renadeen

Sort isn't in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.

that is, if you want to reuse df1 as a sorted DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

or

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

jQuery: checking if the value of a field is null (empty)

Try

_x000D_
_x000D_
if( this["person_data[document_type]"].value != '') { _x000D_
  console.log('not empty');_x000D_
}
_x000D_
<input id="person_data[document_type]" value="test" />
_x000D_
_x000D_
_x000D_

What's the fastest algorithm for sorting a linked list?

Mergesort is the best you can do here.

Responsive design with media query : screen size?

The screen widths Bootstrap v3.x uses are as follows:

  • Extra small devices Phones (<768px) / .col-xs-
  • Small devices Tablets (=768px) / .col-sm-
  • Medium devices Desktops (=992px) / .col-md-
  • Large devices Desktops (=1200px) / .col-lg-

So, these are good to use and work well in practice.

How do you add an action to a button programmatically in xcode

Swift answer:

myButton.addTarget(self, action: "click:", for: .touchUpInside)

func click(sender: UIButton) {
    print("click")
}

Documentation: https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget

Count number of occurences for each unique value

If you want to run unique on a data.frame (e.g., train.data), and also get the counts (which can be used as the weight in classifiers), you can do the following:

unique.count = function(train.data, all.numeric=FALSE) {                                                                                                                                                                                                 
  # first convert each row in the data.frame to a string                                                                                                                                                                              
  train.data.str = apply(train.data, 1, function(x) paste(x, collapse=','))                                                                                                                                                           
  # use table to index and count the strings                                                                                                                                                                                          
  train.data.str.t = table(train.data.str)                                                                                                                                                                                            
  # get the unique data string from the row.names                                                                                                                                                                                     
  train.data.str.uniq = row.names(train.data.str.t)                                                                                                                                                                                   
  weight = as.numeric(train.data.str.t)                                                                                                                                                                                               
  # convert the unique data string to data.frame
  if (all.numeric) {
    train.data.uniq = as.data.frame(t(apply(cbind(train.data.str.uniq), 1, 
      function(x) as.numeric(unlist(strsplit(x, split=","))))))                                                                                                    
  } else {
    train.data.uniq = as.data.frame(t(apply(cbind(train.data.str.uniq), 1, 
      function(x) unlist(strsplit(x, split=",")))))                                                                                                    
  }
  names(train.data.uniq) = names(train.data)                                                                                                                                                                                          
  list(data=train.data.uniq, weight=weight)                                                                                                                                                                                           
}  

window.onload vs <body onload=""/>

There is no difference, but you should not use either.

In many browsers, the window.onload event is not triggered until all images have loaded, which is not what you want. Standards based browsers have an event called DOMContentLoaded which fires earlier, but it is not supported by IE (at the time of writing this answer). I'd recommend using a javascript library which supports a cross browser DOMContentLoaded feature, or finding a well written function you can use. jQuery's $(document).ready(), is a good example.

What to put in a python module docstring?

Think about somebody doing help(yourmodule) at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in x.py:

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

then:

>>> import x; help(x)

shows:

Help on module x:

NAME
    x - This module does blah blah.

FILE
    /tmp/x.py

CLASSES
    __builtin__.object
        Blah

    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  
     |  Data and other attributes defined here:
     |  
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).

I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.

Why am I getting "void value not ignored as it ought to be"?

  int a = srand(time(NULL));

The prototype for srand is void srand(unsigned int) (provided you included <stdlib.h>).
This means it returns nothing ... but you're using the value it returns (???) to assign, by initialization, to a.


Edit: this is what you need to do:

#include <stdlib.h> /* srand(), rand() */
#include <time.h>   /* time() */

#define ARRAY_SIZE 1024

void getdata(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        arr[i] = rand();
    }
}

int main(void)
{
    int arr[ARRAY_SIZE];
    srand(time(0));
    getdata(arr, ARRAY_SIZE);
    /* ... */
}

Undefined index error PHP

There should be the problem, when you generate the <form>. I bet the variables $name, $price are NULL or empty string when you echo them into the value of the <input> field. Empty input fields are not sent by the browser, so $_POST will not have their keys.

Anyway, you can check that with isset().

Test variables with the following:

if(isset($_POST['key'])) ? $variable=$_POST['key'] : $variable=NULL

You better set it to NULL, because

NULL value represents a variable with no value.

How does one Display a Hyperlink in React Native App?

Import Linking the module from React Native

import { TouchableOpacity, Linking } from "react-native";

Try it:-

<TouchableOpacity onPress={() => Linking.openURL('http://Facebook.com')}>
     <Text> Facebook </Text>     
</TouchableOpacity>

How to make image hover in css?

You've got an a tag containing an img tag. That's your normal state. You then add a background-image as your hover state, and it's appearing in the background of your a tag - behind the img tag.

You should probably create a CSS sprite and use background positions, but this should get you started:

<div>
    <a href="home.html"></a>
</div>

div a {
    width:  59px;
    height: 59px;
    display: block;
    background-image: url('images/btnhome.png');
}

div a:hover {
    background-image: url('images/btnhomeh.png);
}

This A List Apart Article from 2004 is still relevant, and will give you some background about sprites, and why it's a good idea to use them instead of two different images. It's a lot better written than anything I could explain to you.

How to get the data-id attribute?

This piece of code will return the value of the data attributes eg: data-id, data-time, data-name etc.., I have shown for the id

<a href="#" id="click-demo" data-id="a1">Click</a>

js:

$(this).data("id");

// get the value of the data-id -> a1

$(this).data("id", "a2");

// this will change the data-id -> a2

$(this).data("id");

// get the value of the data-id -> a2

Getting a list item by index

Old question, but I see that this thread was fairly recently active, so I'll go ahead and throw in my two cents:

Pretty much exactly what Mitch said. Assuming proper indexing, you can just go ahead and use square bracket notation as if you were accessing an array. In addition to using the numeric index, though, if your members have specific names, you can often do kind of a simultaneous search/access by typing something like:

var temp = list1["DesiredMember"];

The more you know, right?

Editor does not contain a main type

On reason for an Error of: "Editor does not contain a main type"

Error encountered in: Eclipse Neon

Operating System: Windows 10 Pro

When you copy your source folders over from a thumb-drive and leave out the Eclipse_Projects.metadata folder.

Other than a fresh install, you will have to make sure you merge the files from (Thrumb-drive)F:Eclipse_Projects.metadata.plugins .

These plug-ins are the bits and pieces of library code taken from the SDK when a class is created. I really all depends on what you-----import javax.swing.*;----- into your file. Because your transferring it over make sure to merge the ------Eclipse_Projects.metadata.plugins------ manually with a simple copy and paste, while accepting the skip feature for already present plugins in your Folder.

For windows 10: you can find your working folders following a similar pattern of file hierarchy.

C:Users>Mikes Laptop> workspace > .metadata > .plugins <---merge plugins here

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

There is no "best way" to create an object. Each way has benefits depending on your use case.

The constructor pattern (a function paired with the new operator to invoke it) provides the possibility of using prototypal inheritance, whereas the other ways don't. So if you want prototypal inheritance, then a constructor function is a fine way to go.

However, if you want prototypal inheritance, you may as well use Object.create, which makes the inheritance more obvious.

Creating an object literal (ex: var obj = {foo: "bar"};) works great if you happen to have all the properties you wish to set on hand at creation time.

For setting properties later, the NewObject.property1 syntax is generally preferable to NewObject['property1'] if you know the property name. But the latter is useful when you don't actually have the property's name ahead of time (ex: NewObject[someStringVar]).

Hope this helps!

How to completely uninstall Visual Studio 2010?

Update April 2016 - for VS2013+

Microsoft started to address the issue in late 2015 by releasing VisualStudioUninstaller.

They abandoned the solution for a while; however work has begun again again as of April 2016.

There has finally been an official release for this uninstaller in April 2016 which is described as being "designed to cleanup/scorch all Preview/RC/RTM releases of Visual Studio 2013, Visual Studio 2015 and Visual Studio vNext".


Original Answer - for VS2010, VS2012

Note that the following two solutions still leave traces (such as registry files) and can't really be considered a 'clean' uninstall (see the final section of the answer for a completely clean solution).


Solution 1 - for: VS 2010

There's an uninstaller provided by Microsoft called the Visual Studio 2010 Uninstall Utility. It comes with three options:

  1. Default (VS2010_Uninstall-RTM.ENU.exe)
  2. Full (VS2010_Uninstall-RTM.ENU.exe /full)
  3. Complete (VS2010_Uninstall-RTM.ENU.exe /full /netfx)

The above link explains the uninstaller in greater detail - I recommend reading the comments on the article before using it as some have noted problems (and workarounds) when service packs are installed. Afterwards, use something like CCleaner to remove the leftover registry files.

Here is the link to the download page of the VS2010 UU.


Solution 2 - for: VS 2010, VS 2012

Microsoft provide an uninstall /force feature that removes most remnants of either VS2010 or VS2012 from your computer.

MSDN: How to uninstall Visual Studio 2010/2012. From the link:

Warning: Running this command may remove some packages even if they are still in use like those listed in Optional shared packages.

  1. Download the setup application you used to originally install Visual Studio 2012. If you installed from media, please insert that media.
  2. Open a command prompt. Click Run on the Start menu (Start + R). Type cmd and press OK (Enter).
  3. Type in the full path to the setup application and pass the following command line switches: /uninstall /force Example: D:\vs_ultimate.exe /uninstall /force
  4. Click the Uninstall button and follow the prompts.

Afterwards, use something like CCleaner to remove the leftover registry files.


A completely clean uninstall?

Sadly, the only (current) way to achieve this is to follow dnLL's advice in their answer and perform a complete operating system reinstall. Then, in future, you could use Visual Studio inside a Virtual Machine instead and not have to worry about these issues again.

View stored procedure/function definition in MySQL

something like:

DELIMITER //

CREATE PROCEDURE alluser()
BEGIN
   SELECT *
   FROM users;
END //

DELIMITER ;

than:

SHOW CREATE PROCEDURE alluser

gives result:

'alluser', 'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER', 'CREATE DEFINER=`root`@`localhost` PROCEDURE `alluser`()
BEGIN
   SELECT *
   FROM users;
END'

Assembly code vs Machine code vs Object code?

Assembly code is discussed here.

"An assembly language is a low-level language for programming computers. It implements a symbolic representation of the numeric machine codes and other constants needed to program a particular CPU architecture."

Machine code is discussed here.

"Machine code or machine language is a system of instructions and data executed directly by a computer's central processing unit."

Basically, assembler code is the language and it is translated to object code (the native code that the CPU runs) by an assembler (analogous to a compiler).

Android RecyclerView addition & removal of items

make interface into custom adapter class and handling click event on recycler view..

 onItemClickListner onItemClickListner;

public void setOnItemClickListner(CommentsAdapter.onItemClickListner onItemClickListner) {
    this.onItemClickListner = onItemClickListner;
}

public interface onItemClickListner {
    void onClick(Contact contact);//pass your object types.
}
    @Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    // below code handle click event on recycler view item.
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onItemClickListner.onClick(mContectList.get(position));
        }
    });
}

after define adapter and bind into recycler view called below code..

        adapter.setOnItemClickListner(new CommentsAdapter.onItemClickListner() {
        @Override
        public void onClick(Contact contact) {
            contectList.remove(contectList.get(contectList.indexOf(contact)));
            adapter.notifyDataSetChanged();
        }
    });
}

fatal: could not read Username for 'https://github.com': No such file or directory

This error can also happen when trying to clone an invalid HTTP URL. For example, this is the error I got when trying to clone a GitHub URL that was a few characters off:

$ git clone -v http://github.com/username/repo-name.git
Cloning into 'repo-name'...
Username for 'https://github.com': 
Password for 'https://github.com': 
remote: Repository not found.
fatal: Authentication failed for 'https://github.com/username/repo-name.git/'

It actually happened inside Emacs, though, so the error in Emacs looked like this:

fatal: could not read Username for ’https://github.com’: No such device or address

So instead of a helpful error saying that there was no such repo at that URL, it gave me that, sending me on a wild goose chase until I finally realized that the URL was incorrect.

This is with git version 2.7.4.

I'm posting this here because it happened to me a month ago and again just now, sending me on the same wild goose chase again. >:(

Change Orientation of Bluestack : portrait/landscape mode

New version 4.100.x.xxxx

Try this:

More Apps > Android Settings > Accessibility > Auto-rotate screen = Enabled

enter image description here

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

I had exactly the same issue and it was not cross domain but the same domain. I just added this line to the php file which was handling the ajax request.

<?php header('Access-Control-Allow-Origin: *'); ?>

It worked like a charm. Thanks to the poster

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

How to "wait" a Thread in Android

Don't use wait(), use either android.os.SystemClock.sleep(1000); or Thread.sleep(1000);.

The main difference between them is that Thread.sleep() can be interrupted early -- you'll be told, but it's still not the full second. The android.os call will not wake early.

How to generate the whole database script in MySQL Workbench?

In the top menu of MySQL Workbench click on database and then on forward engineer. In the options menu with which you will be presented, make sure to have "generate insert statements for tables" set.

Chosen Jquery Plugin - getting selected values

As of 2016, you can do this more simply than in any of the answers already given:

$('#myChosenBox').val();

where "myChosenBox" is the id of the original select input. Or, in the change event:

$('#myChosenBox').on('change', function(e, params) {
    alert(e.target.value); // OR
    alert(this.value); // OR
    alert(params.selected); // also in Panagiotis Kousaris' answer
}

In the Chosen doc, in the section near the bottom of the page on triggering events, it says "Chosen triggers a number of standard and custom events on the original select field." One of those standard events is the change event, so you can use it in the same way as you would with a standard select input. You don't have to mess around with using Chosen's applied classes as selectors if you don't want to. (For the change event, that is. Other events are often a different matter.)

Change input text border color without changing its height

Try this

<input type="text"/>

It will display same in all cross browser like mozilla , chrome and internet explorer.

<style>
    input{
       border:2px solid #FF0000;
    }
</style>

Dont add style inline because its not good practise, use class to add style for your input box.

Android ImageView setImageResource in code

you may try this:-

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));

Load different application.yml in SpringBoot Test

One option is to work with profiles. Create a file called application-test.yml, move all properties you need for those tests to that file and then add the @ActiveProfiles annotation to your test class:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
@ActiveProfiles("test") // Like this
public class MyIntTest{
}

Be aware, it will additionally load the application-test.yml, so all properties that are in application.yml are still going to be applied as well. If you don't want that, either use a profile for those as well, or override them in your application-test.yml.

What does -save-dev mean in npm install grunt --save-dev

Documentation from npm for npm install <package-name> --save and npm install <package-name> --save-dev can be found here:

https://docs.npmjs.com/getting-started/using-a-package.json#the-save-and-save-dev-install-flags

A package.json file declares metadata about the module you are developing. Both aforementioned commands modify this package.json file. --save will declare the installed package (in this case, grunt) as a dependency for your module; --save-dev will declare it as a dependency for development of your module.

Ask yourself: will the installed package be required for use of my module, or will it only be required for developing it?

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How can I do an UPDATE statement with JOIN in SQL Server?

The following statement with FROM keyword is used to update multiple rows with a join

UPDATE users 
set users.DivisionId=divisions.DivisionId
from divisions join users on divisions.Name=users.Division

PHP - how to create a newline character?

For any echo statements, I always use <br> inside double quotes.

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

How to draw a filled circle in Java?

/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
    g.setColor(Color.RED);
    g.fillOval(50,50,20,20);
}

g.fillOval(x-axis,y-axis,width,height);

Anaconda Navigator won't launch (windows 10)

I am not sure why but the command below worked for me.

pip install pyqt5

Of course I updated Anaconda and Navigator before running this command.

How do you use global variables or constant values in Ruby?

I think it's local to the file you declared offset. Consider every file to be a method itself.

Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);?

Publish to IIS, setting Environment Variable

This answer was originally written for ASP.NET Core RC1. In RC2 ASP.NET Core moved from generic httpPlafrom handler to aspnetCore specific one. Note that step 3 depends on what version of ASP.NET Core you are using.

Turns out environment variables for ASP.NET Core projects can be set without having to set environment variables for user or having to create multiple commands entries.

  1. Go to your application in IIS and choose Configuration Editor.
  2. Select Configuration Editor
  3. Choose system.webServer/aspNetCore (RC2 and RTM) or system.webServer/httpPlatform (RC1) in Section combobox
  4. Choose Applicationhost.config ... in From combobox.
  5. Right click on enviromentVariables element, select 'environmentVariables' element, then Edit Items. enter image description here
  6. Set your environment variables.
  7. Close the window and click Apply.
  8. Done

This way you do not have to create special users for your pool or create extra commands entries in project.json. Also, adding special commands for each environment breaks "build once, deploy many times" as you will have to call dnu publish separately for each environment, instead of publish once and deploying resulting artifact many times.

Updated for RC2 and RTM, thanks to Mark G and tredder.

How to round up integer division and have int result in Java?

Google's Guava library handles this in the IntMath class:

IntMath.divide(numerator, divisor, RoundingMode.CEILING);

Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.

Is it possible to move/rename files in Git and maintain their history?

git log --follow [file]

will show you the history through renames.

Is it bad to have my virtualenv directory inside my git repository?

If you know which operating systems your application will be running on, I would create one virtualenv for each system and include it in my repository. Then I would make my application detect which system it is running on and use the corresponding virtualenv.

The system could e.g. be identified using the platform module.

In fact, this is what I do with an in-house application I have written, and to which I can quickly add a new system's virtualenv in case it is needed. This way, I do not have to rely on that pip will be able to successfully download the software my application requires. I will also not have to worry about compilation of e.g. psycopg2 which I use.

If you do not know which operating system your application may run on, you are probably better off using pip freeze as suggested in other answers here.

Could not load the Tomcat server configuration

I know it's an old question and it has been solved already but for me the Tomcat conf/tomcat-users.xml file was created with a different encoding from the rest of the configuration files. The first line of that file looked like this:

<?xml version='1.0' encoding='cp65001'?>

All I had to do to solve the issue was change that line for:

<?xml version="1.0" encoding="UTF-8"?>

And voila.

I have no idea what 'cp65001' means or why it was created like that.

Maybe this will help other users facing the same issue.

Add views below toolbar in CoordinatorLayout

As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView.

app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

Regex replace uppercase with lowercase letters

Before searching with regex like [A-Z], you should press the case sensitive button (or Alt+C) (as leemour nicely suggested to be edited in the accepted answer). Just to be clear, I'm leaving a few other examples:

  1. Capitalize words
    • Find: (\s)([a-z]) (\s also matches new lines, i.e. "venuS" => "VenuS")
    • Replace: $1\u$2
  2. Uncapitalize words
    • Find: (\s)([A-Z])
    • Replace: $1\l$2
  3. Remove camel case (e.g. cAmelCAse => camelcAse => camelcase)
    • Find: ([a-z])([A-Z])
    • Replace: $1\l$2
  4. Lowercase letters within words (e.g. LowerCASe => Lowercase)
    • Find: (\w)([A-Z]+)
    • Replace: $1\L$2
    • Alternate Replace: \L$0
  5. Uppercase letters within words (e.g. upperCASe => uPPERCASE)
    • Find: (\w)([A-Z]+)
    • Replace: $1\U$2
  6. Uppercase previous (e.g. upperCase => UPPERCase)
    • Find: (\w+)([A-Z])
    • Replace: \U$1$2
  7. Lowercase previous (e.g. LOWERCase => lowerCase)
    • Find: (\w+)([A-Z])
    • Replace: \L$1$2
  8. Uppercase the rest (e.g. upperCase => upperCASE)
    • Find: ([A-Z])(\w+)
    • Replace: $1\U$2
  9. Lowercase the rest (e.g. lOWERCASE => lOwercase)
    • Find: ([A-Z])(\w+)
    • Replace: $1\L$2
  10. Shift-right-uppercase (e.g. Case => cAse => caSe => casE)
    • Find: ([a-z\s])([A-Z])(\w)
    • Replace: $1\l$2\u$3
  11. Shift-left-uppercase (e.g. CasE => CaSe => CAse => Case)
    • Find: (\w)([A-Z])([a-z\s])
    • Replace: \u$1\l$2$3

Regarding the question (match words with at least one uppercase and one lowercase letter and make them lowercase), leemour's comment-answer is the right answer. Just to clarify, if there is only one group to replace, you can just use ?: in the inner groups (i.e. non capture groups) or avoid creating them at all:

  • Find: ((?:[a-z][A-Z]+)|(?:[A-Z]+[a-z])) OR ([a-z][A-Z]+|[A-Z]+[a-z])
  • Replace: \L$1

2016-06-23 Edit

Tyler suggested by editing this answer an alternate find expression for #4:

  • (\B)([A-Z]+)

According to the documentation, \B will look for a character that is not at the word's boundary (i.e. not at the beginning and not at the end). You can use the Replace All button and it does the exact same thing as if you had (\w)([A-Z]+) as the find expression.

However, the downside of \B is that it does not allow single replacements, perhaps due to the find's "not boundary" restriction (please do edit this if you know the exact reason).

.NET DateTime to SqlDateTime Conversion

Also please remember resolutions [quantum of time] are different.

http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx

SQL one is 3.33 ms and .net one is 100 ns.

Should I write script in the body or the head of the html?

I always put my scripts in the header. My reasons:

  1. I like to separate code and (static) text
  2. I usually load my script from external sources
  3. The same script is used from several pages, so it feels like an include file (which also goes in the header)

How to get client's IP address using JavaScript?

Use ipdata.co.

The API also provides geolocation data and has 10 global endpoints each able to handle >800M requests a day!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
    $("#response").html(response.ip);_x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<pre id="response"></pre>
_x000D_
_x000D_
_x000D_

How to "pretty" format JSON output in Ruby on Rails

If you are using RABL you can configure it as described here to use JSON.pretty_generate:

class PrettyJson
  def self.dump(object)
    JSON.pretty_generate(object, {:indent => "  "})
  end
end

Rabl.configure do |config|
  ...
  config.json_engine = PrettyJson if Rails.env.development?
  ...
end

A problem with using JSON.pretty_generate is that JSON schema validators will no longer be happy with your datetime strings. You can fix those in your config/initializers/rabl_config.rb with:

ActiveSupport::TimeWithZone.class_eval do
  alias_method :orig_to_s, :to_s
  def to_s(format = :default)
    format == :default ? iso8601 : orig_to_s(format)
  end
end

Access VBA | How to replace parts of a string with another string

You could use a function similar to this also, it would allow you to add in different cases where you would like to change values:

Public Function strReplace(varValue As Variant) as Variant

    Select Case varValue

        Case "Avenue"
            strReplace = "Ave"

        Case "North"
            strReplace = "N"

        Case Else
            strReplace = varValue

    End Select

End Function

Then your SQL would read something like:

SELECT strReplace(Address) As Add FROM Tablename

Printing result of mysql query from variable

This will print out the query:

$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";

$dave= mysql_query($query) or die(mysql_error());
print $query;

This will print out the results:

$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";

$dave= mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($dave)){
    foreach($row as $cname => $cvalue){
        print "$cname: $cvalue\t";
    }
    print "\r\n";
}

How do I POST XML data with curl

I prefer the following command-line options:

cat req.xml | curl -X POST -H 'Content-type: text/xml' -d @- http://www.example.com

or

curl -X POST -H 'Content-type: text/xml' -d @req.xml http://www.example.com

or

curl -X POST -H 'Content-type: text/xml'  -d '<XML>data</XML>' http://www.example.com 

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

How to replace multiple white spaces with one white space

While the existing answers are fine, I'd like to point out one approach which doesn't work:

public static string DontUseThisToCollapseSpaces(string text)
{
    while (text.IndexOf("  ") != -1)
    {
        text = text.Replace("  ", " ");
    }
    return text;
}

This can loop forever. Anyone care to guess why? (I only came across this when it was asked as a newsgroup question a few years ago... someone actually ran into it as a problem.)

How to implement and do OCR in a C# project?

Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)

using MODI;
static void Main(string[] args)
{
    DocumentClass myDoc = new DocumentClass();
    myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
    myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);

    foreach (Image anImage in myDoc.Images)
    {
        Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
    }
}

how to concat two columns into one with the existing column name in mysql?

Instead of getting all the table columns using * in your sql statement, you use to specify the table columns you need.

You can use the SQL statement something like:

SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS FIRSTNAME FROM customer;

BTW, why couldn't you use FullName instead of FirstName? Like this:

SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'CUSTOMER NAME' FROM customer;

How to fit Windows Form to any screen resolution?

If you want to set the form size programmatically, set the form's StartPosition property to Manual. Otherwise the form's own positioning and sizing algorithm will interfere with yours. This is why you are experiencing the problems mentioned in your question.

Example: Here is how I resize the form to a size half-way between its original size and the size of the screen's working area. I also center the form in the working area:

public MainView()
{
    InitializeComponent();

    // StartPosition was set to FormStartPosition.Manual in the properties window.
    Rectangle screen = Screen.PrimaryScreen.WorkingArea;
    int w = Width >= screen.Width ? screen.Width : (screen.Width + Width) / 2;
    int h = Height >= screen.Height ? screen.Height : (screen.Height + Height) / 2;
    this.Location = new Point((screen.Width - w) / 2, (screen.Height - h) / 2);
    this.Size = new Size(w, h);
}

Note that setting WindowState to FormWindowState.Maximized alone does not change the size of the restored window. So the window might look good as long as it is maximized, but when restored, the window size and location can still be wrong. So I suggest setting size and location even when you intend to open the window as maximized.

Android: Quit application when press back button

Finish doesn't close the app, it just closes the activity. If this is the launcher activity, then it will close your app; if not, it will go back to the previous activity.

What you can do is use onActivityResult to trigger as many finish() as needed to close all the open activities.

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How to decode jwt token in javascript without using a library?

If you use Node.JS, You can use the native Buffer module by doing :

const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImp0aSI6ImU3YjQ0Mjc4LTZlZDYtNDJlZC05MTZmLWFjZDQzNzhkM2U0YSIsImlhdCI6MTU5NTg3NzUxOCwiZXhwIjoxNTk1ODgxMTE4fQ.WXyDlDMMSJAjOFF9oAU9JrRHg2wio-WolWAkAaY3kg4';
const base64Url = token.split('.')[1];
const decoded = Buffer.from(base64Url, 'base64').toString();
console.log(decoded)

And you're good to go :-)

Change background of LinearLayout in Android

LinearLayout li=(LinearLayout)findViewById(R.id.layoutid);

setting the background color fro ur layout.

li.setBackgroundColor(Color.parseColor("#ffff00"));

this is to set the image which u can store in drawable folder

li.setBackgroundDrawable(drwableItem);

some resource for display purpose animation or img

li.setBackgroundResource(R.id.bckResource);

java.text.ParseException: Unparseable date

I found simple solution to get current date without any parsing error.

Calendar calendar;
calendar = Calendar.getInstance();
String customDate = "" + calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH);

Can I dynamically add HTML within a div tag from C# on load event?

Remember using

myDiv.InnerHtml = "something";

will replace all HTML elements in myDIV. you need to append text to avoid that.In that this may help

myDiv.InnerHtml = "something" + myDiv.InnerText;

any html control in myDiv but not ASP html controls(as they are not rendered yet).

How can I use random numbers in groovy?

There is no such method as java.util.Random.getRandomDigits.

To get a random number use nextInt:

return random.nextInt(10 ** num)

Also you should create the random object once when your application starts:

Random random = new Random()

You should not create a new random object every time you want a new random number. Doing this destroys the randomness.

Codeigniter - multiple database connections

While looking at your code, the only thing I see wrong, is when you try to load the second database:

$DB2=$this->load->database($config);

When you want to retrieve the database object, you have to pass TRUE in the second argument.

From the Codeigniter User Guide:

By setting the second parameter to TRUE (boolean) the function will return the database object.

So, your code should instead be:

$DB2=$this->load->database($config, TRUE);

That will make it work.

How to make a jquery function call after "X" seconds

If you could show the actual page, we, possibly, could help you better.

If you want to trigger the button only after the iframe is loaded, you might want to check if it has been loaded or use the iframe.onload:

<iframe .... onload='buttonWhatever(); '></iframe>


<script type="text/javascript">

    function buttonWhatever() {
        $("#<%=Button1.ClientID%>").click(function (event) {
            $('#<%=TextBox1.ClientID%>').change(function () {
                $('#various3').attr('href', $(this).val());
            });
            $("#<%=Button2.ClientID%>").click();
        });

        function showStickySuccessToast() {
            $().toastmessage('showToast', {
                text: 'Finished Processing!',
                sticky: false,
                position: 'middle-center',
                type: 'success',
                closeText: '',
                close: function () { }
            });
        }
    }

</script>

How to convert string to IP address and vice versa

I'm not sure if I understood the question properly.

Anyway, are you looking for this:

std::string ip ="192.168.1.54";
std::stringstream s(ip);
int a,b,c,d; //to store the 4 ints
char ch; //to temporarily store the '.'
s >> a >> ch >> b >> ch >> c >> ch >> d;
std::cout << a << "  " << b << "  " << c << "  "<< d;

Output:

192  168  1  54

PHP: HTML: send HTML select option attribute in POST

just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:

<form name='add'>
Age: <select name='age'>
     <option value='1_sre'>23</option>
     <option value='2_sam>24</option>
     <option value='5_john>25</option>
     </select>
<input type='submit' name='submit'/>
</form>

How do I do a HTTP GET in Java?

If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.

An example looks like this:

String urlString = "http://wherever.com/someAction?param1=value1&param2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream

Nginx: stat() failed (13: permission denied)

I've just had the same problem on a CentOS 7 box.

Seems I'd hit selinux. Putting selinux into permissive mode (setenforce permissive) has worked round the problem for now. I'll try and get back with a proper fix.

HTTP client timeout and server timeout

go to the url about:config and paste each line:

network.http.keep-alive.timeout;10
network.http.connection-retry-timeout;10
network.http.pipelining.read-timeout;5
network.http.connection-timeout;10

Update query PHP MySQL

First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error() directly after a query to debug.

determine DB2 text string length

Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;

wget command to download a file and save as a different filename

You would use the command Mechanical snail listed. Notice the uppercase O. Full command line to use could be:

wget www.examplesite.com/textfile.txt --output-document=newfile.txt

or

wget www.examplesite.com/textfile.txt -O newfile.txt

Hope that helps.

Fastest way to list all primes below N

Here is a numpy version of Sieve of Eratosthenes having both good complexity (lower than sorting an array of length n) and vectorization. Compared to @unutbu times this just as fast as the packages with 46 microsecons to find all primes below a million.

import numpy as np 
def generate_primes(n):
    is_prime = np.ones(n+1,dtype=bool)
    is_prime[0:2] = False
    for i in range(int(n**0.5)+1):
        if is_prime[i]:
            is_prime[i**2::i]=False
    return np.where(is_prime)[0]

Timings:

import time    
for i in range(2,10):
    timer =time.time()
    generate_primes(10**i)
    print('n = 10^',i,' time =', round(time.time()-timer,6))

>> n = 10^ 2  time = 5.6e-05
>> n = 10^ 3  time = 6.4e-05
>> n = 10^ 4  time = 0.000114
>> n = 10^ 5  time = 0.000593
>> n = 10^ 6  time = 0.00467
>> n = 10^ 7  time = 0.177758
>> n = 10^ 8  time = 1.701312
>> n = 10^ 9  time = 19.322478

toggle show/hide div with button?

Look at jQuery Toggle

HTML:

<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>

jQuery:

jQuery(document).ready(function(){
    jQuery('#hideshow').live('click', function(event) {        
         jQuery('#content').toggle('show');
    });
});

For versions of jQuery 1.7 and newer use

jQuery(document).ready(function(){
    jQuery('#hideshow').on('click', function(event) {        
        jQuery('#content').toggle('show');
    });
});

For reference, kindly check this demo

How do you check if a string is not equal to an object or other string value in java?

Change your code to:

System.out.println("AM or PM?"); 
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

...

if(Hours == 13){
    if (TimeOfDayStringQ.equals("AM")) {
        TimeOfDayStringQ = "PM"; // <--
    } else {
        TimeOfDayStringQ = "AM"; // <--
    }
            Hours = 1;
    }
 }

Format cell if cell contains date less than today

Your first problem was you weren't using your compare symbols correctly.

< less than
> greater than
<= less than or equal to
>= greater than or equal to

To answer your other questions; get the condition to work on every cell in the column and what about blanks?

What about blanks?

Add an extra IF condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())

Condition on every cell in column

enter image description here

from unix timestamp to datetime

If using react:

import Moment from 'react-moment';
Moment.globalFormat = 'D MMM YYYY';

then:

<td><Moment unix>{1370001284}</Moment></td>

Changing Font Size For UITableView Section Headers

For iOS 7 I use this,


-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;

    header.textLabel.font = [UIFont boldSystemFontOfSize:10.0f];
    header.textLabel.textColor = [UIColor orangeColor];
}

Here is Swift 3.0 version with header resizing

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let header = view as? UITableViewHeaderFooterView {
        header.textLabel!.font = UIFont.systemFont(ofSize: 24.0)
        header.textLabel!.textColor = UIColor.orange          
    }
}

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

Android - Package Name convention

But if your Android App is only for personal purpose or created by you alone, you can use:

me.app_name.app

Appending a line break to an output file in a shell script

I'm betting the problem is that Cygwin is writing Unix line endings (LF) to the file, and you're opening it with a program that expects Windows line-endings (CRLF). To determine if this is the case — and for a bit of a hackish workaround — try:

echo "`date` User `whoami` started the script."$'\r' >> output.log

(where the $'\r' at the end is an extra carriage-return; it, plus the Unix line ending, will result in a Windows line ending).

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

How to have conditional elements and keep DRY with Facebook React's JSX?

There is another solution, if component for React:

var Node = require('react-if-comp');
...
render: function() {
    return (
        <div id="page">
            <Node if={this.state.banner}
                  then={<div id="banner">{this.state.banner}</div>} />
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

How to convert a string to utf-8 in Python

  • First, str in Python is represented in Unicode.
  • Second, UTF-8 is an encoding standard to encode Unicode string to bytes. There are many encoding standards out there (e.g. UTF-16, ASCII, SHIFT-JIS, etc.).

When the client sends data to your server and they are using UTF-8, they are sending a bunch of bytes not str.

You received a str because the "library" or "framework" that you are using, has implicitly converted some random bytes to str.

Under the hood, there is just a bunch of bytes. You just need ask the "library" to give you the request content in bytes and you will handle the decoding yourself (if library can't give you then it is trying to do black magic then you shouldn't use it).

  • Decode UTF-8 encoded bytes to str: bs.decode('utf-8')
  • Encode str to UTF-8 bytes: s.encode('utf-8')

How do I turn a C# object into a JSON string in .NET?

In your Lad model class, add an override to the ToString() method that returns a JSON string version of your Lad object.
Note: you will need to import System.Text.Json;

using System.Text.Json;

class MyDate
{
    int year, month, day;
}

class Lad
{
    public string firstName { get; set; };
    public string lastName { get; set; };
    public MyDate dateOfBirth { get; set; };
    public override string ToString() => JsonSerializer.Serialize<Lad>(this);
}

Can an ASP.NET MVC controller return an Image?

You could use the HttpContext.Response and directly write the content to it (WriteFile() might work for you) and then return ContentResult from your action instead of ActionResult.

Disclaimer: I have not tried this, it's based on looking at the available APIs. :-)

How to uninstall/upgrade Angular CLI?

To uninstall it globally just run below command:

npm uninstall -g @angular/cli

Once it is done, clear your cache by running below command:

npm cache clean

Now, to install the latset version of Angular, just run:

npm install -g @angular/cli@latest

For details about Angular CLI, take a look at Angular introduction and CLI guide

Cosine Similarity between 2 Number Lists

All the answers are great for situations where you cannot use NumPy. If you can, here is another approach:

def cosine(x, y):
    dot_products = np.dot(x, y.T)
    norm_products = np.linalg.norm(x) * np.linalg.norm(y)
    return dot_products / (norm_products + EPSILON)

Also bear in mind about EPSILON = 1e-07 to secure the division.

urllib2 and json

Example - sending some data encoded as JSON as a POST data:

import json
import urllib2
data = json.dumps([1, 2, 3])
f = urllib2.urlopen(url, data)
response = f.read()
f.close()

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

Converting string "true" / "false" to boolean value

If you're using the variable result:

result = result == "true";

How to disable 'X-Frame-Options' response header in Spring Security?

Most likely you don't want to deactivate this Header completely, but use SAMEORIGIN. If you are using the Java Configs (Spring Boot) and would like to allow the X-Frame-Options: SAMEORIGIN, then you would need to use the following.


For older Spring Security versions:

http
   .headers()
       .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))

For newer versions like Spring Security 4.0.2:

http
   .headers()
      .frameOptions()
         .sameOrigin();

git: undo all working dir changes including new files

The following works:

git add -A .
git stash
git stash drop stash@{0}

Please note that this will discard both your unstaged and staged local changes. So you should commit anything you want to keep, before you run these commands.

A typical use case: You moved a lot of files or directories around, and then want to get back to the original state.

Credits: https://stackoverflow.com/a/52719/246724

Trigger Change event when the Input value changed programmatically?

If someone is using react, following will be useful:

https://stackoverflow.com/a/62111884/1015678

const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));

ISO C90 forbids mixed declarations and code in C

I think you should move the variable declaration to top of block. I.e.

{
    foo();
    int i = 0;
    bar();
}

to

{
    int i = 0;
    foo();
    bar();
}

Reading a file character by character in C

Either of the two should do the trick -

char *readFile(char *fileName)
{
  FILE *file;
  char *code = malloc(1000 * sizeof(char));
  char *p = code;
  file = fopen(fileName, "r");
  do 
  {
    *p++ = (char)fgetc(file);
  } while(*p != EOF);
  *p = '\0';
  return code;
}

char *readFile(char *fileName)
{
  FILE *file;
  int i = 0;
  char *code = malloc(1000 * sizeof(char));
  file = fopen(fileName, "r");
  do 
  {
    code[i++] = (char)fgetc(file);
  } while(code[i-1] != EOF);
  code[i] = '\0'
  return code;
}

Like the other posters have pointed out, you need to ensure that the file size does not exceed 1000 characters. Also, remember to free the memory when you're done using it.

How to fix Invalid AES key length?

Things to know in general:

  1. Key != Password
    • SecretKeySpec expects a key, not a password. See below
  2. It might be due to a policy restriction that prevents using 32 byte keys. See other answer on that

In your case

The problem is number 1: you are passing the password instead of the key.

AES only supports key sizes of 16, 24 or 32 bytes. You either need to provide exactly that amount or you derive the key from what you type in.

There are different ways to derive the key from a passphrase. Java provides a PBKDF2 implementation for such a purpose.

I used erickson's answer to paint a complete picture (only encryption, since the decryption is similar, but includes splitting the ciphertext):

SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);

KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 256); // AES-256
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] key = f.generateSecret(spec).getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

byte[] ivBytes = new byte[16];
random.nextBytes(ivBytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes);

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encValue = c.doFinal(valueToEnc.getBytes());

byte[] finalCiphertext = new byte[encValue.length+2*16];
System.arraycopy(ivBytes, 0, finalCiphertext, 0, 16);
System.arraycopy(salt, 0, finalCiphertext, 16, 16);
System.arraycopy(encValue, 0, finalCiphertext, 32, encValue.length);

return finalCiphertext;

Other things to keep in mind:

  • Always use a fully qualified Cipher name. AES is not appropriate in such a case, because different JVMs/JCE providers may use different defaults for mode of operation and padding. Use AES/CBC/PKCS5Padding. Don't use ECB mode, because it is not semantically secure.
  • If you don't use ECB mode then you need to send the IV along with the ciphertext. This is usually done by prefixing the IV to the ciphertext byte array. The IV is automatically created for you and you can get it through cipherInstance.getIV().
  • Whenever you send something, you need to be sure that it wasn't altered along the way. It is hard to implement a encryption with MAC correctly. I recommend you to use an authenticated mode like CCM or GCM.

How can I make my flexbox layout take 100% vertical space?

Let me show you another way that works 100%. I will also add some padding for the example.

<div class = "container">
  <div class = "flex-pad-x">
    <div class = "flex-pad-y">
      <div class = "flex-pad-y">
        <div class = "flex-grow-y">
         Content Centered
        </div>
      </div>
    </div>
  </div>
</div>

.container {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  width: 100%;
  height: 100%;
}

  .flex-pad-x {
    padding: 0px 20px;
    height: 100%;
    display: flex;
  }

  .flex-pad-y {
    padding: 20px 0px;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .flex-grow-y {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
   }

As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.

1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.

Hope this helps

Daniel

getting error while updating Composer

The good solution for this error please run this command

composer install --ignore-platform-reqs

How do I paste multi-line bash codes into terminal and run it all at once?

In addition to backslash, if a line ends with | or && or ||, it will be continued on the next line.

How do I display an alert dialog on Android?

This is definitely help for you. Try this code: On click of a button, you can put one, two or three buttons with an alert dialog...

SingleButtton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        // Creating alert Dialog with one Button

        AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();

        // Setting Dialog Title
        alertDialog.setTitle("Alert Dialog");

        // Setting Dialog Message
        alertDialog.setMessage("Welcome to Android Application");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.tick);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog,int which)
            {
                // Write your code here to execute after dialog    closed
                Toast.makeText(getApplicationContext(),"You clicked on OK", Toast.LENGTH_SHORT).show();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
});

btnAlertTwoBtns.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        // Creating alert Dialog with two Buttons

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Confirm Delete...");

        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want delete this?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.delete);

        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {
                        // Write your code here to execute after dialog
                        Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
                    }
                });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,    int which) {
                        // Write your code here to execute after dialog
                        Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }
});

btnAlertThreeBtns.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        // Creating alert Dialog with three Buttons

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                AlertDialogActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Save File...");

        // Setting Dialog Message
        alertDialog.setMessage("Do you want to save this file?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.save);

        // Setting Positive Yes Button
        alertDialog.setPositiveButton("YES",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                        int which) {
                    // User pressed Cancel button. Write Logic Here
                    Toast.makeText(getApplicationContext(),
                            "You clicked on YES",
                            Toast.LENGTH_SHORT).show();
                }
            });

        // Setting Negative No Button... Neutral means in between yes and cancel button
        alertDialog.setNeutralButton("NO",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                        int which) {
                    // User pressed No button. Write Logic Here
                    Toast.makeText(getApplicationContext(),
                            "You clicked on NO", Toast.LENGTH_SHORT)
                            .show();
                }
            });

        // Setting Positive "Cancel" Button
        alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                        int which) {
                    // User pressed Cancel button. Write Logic Here
                    Toast.makeText(getApplicationContext(),
                            "You clicked on Cancel",
                            Toast.LENGTH_SHORT).show();
                }
            });
        // Showing Alert Message
        alertDialog.show();
    }
});

CSS background-image not working

I faced this problem. My html was as below:

<th style="background-image:url('Image.png');">
</th>

I added "&nbsp" as @shankhan suggested inside th and the image started showing up.

<th style="background-image:url('Image.png');">
   &nbsp;
</th>