Programs & Examples On #Cygwin

Cygwin is a collection of GNU and other Unix-like FOSS tools which run on MS Windows and provide functionality similar to a GNU/Linux distribution while (mostly) conforming to POSIX specifications. Use this tag for questions about developing programs and/or scripts to run in this environment. Questions on the *use* of tools in a Cygwin environment are more appropriate for Super User.

Objective-C for Windows

Also:

The Cocotron is an open source project which aims to implement a cross-platform Objective-C API similar to that described by Apple Inc.'s Cocoa documentation. This includes the AppKit, Foundation, Objective-C runtime and support APIs such as CoreGraphics and CoreFoundation.

http://www.cocotron.org/

.ssh directory not being created

As a slight improvement over the other answers, you can do the mkdir and chmod as a single operation using mkdir's -m switch.

$ mkdir -m 700 ${HOME}/.ssh

Usage

From a Linux system

$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
...
...

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

For those use Msys/MinGW GIT, add this

  export GIT_SSL_CAINFO=/mingw32/ssl/certs/ca-bundle.crt 

How can I set my Cygwin PATH to find javac?

as you write the it with double-quotes, you don't need to escape spaces with \

export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/"

of course this also works:

export PATH=$PATH:/cygdrive/C/Program\ Files/Java/jdk1.6.0_23/bin/

Running a shell script through Cygwin on Windows

Just wanted to add that you can do this to apply dos2unix fix for all files under a directory, as it saved me heaps of time when we had to 'fix' a bunch of our scripts.

find . -type f -exec dos2unix.exe {} \;

I'd do it as a comment to Roman's answer, but I don't have access to commenting yet.

Why does find -exec mv {} ./target/ + not work?

no, the difference between + and \; should be reversed. + appends the files to the end of the exec command then runs the exec command and \; runs the command for each file.

The problem is find . -type f -iname '*.cpp' -exec mv {} ./test/ \+ should be find . -type f -iname '*.cpp' -exec mv {} ./test/ + no need to escape it or terminate the +

xargs I haven't used in a long time but I think works like +.

Split text file into smaller multiple text file using command line

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET /a fcount=100
SET /a llimit=5000
SET /a lcount=%llimit%
FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\q25249516.txt") DO (
 CALL :select
 FOR /f "tokens=1*delims==" %%b IN ('set dfile') DO IF /i "%%b"=="dfile" >>"%%c" ECHO(%%a
)
GOTO :EOF
:select
SET /a lcount+=1
IF %lcount% lss %llimit% GOTO :EOF
SET /a lcount=0
SET /a fcount+=1
SET "dfile=%sourcedir%\file%fcount:~-2%.txt"
GOTO :EOF

Here's a native windows batch that should accomplish the task.

Now I'll not say that it'll be fast (less than 2 minutes for each 5Kline output file) or that it will be immune to batch character-sensitivites. Really depends on the characteristics of your target data.

I used a file named q25249516.txt containing 100Klines of data for my testing.


Revised quicker version

REM

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET /a fcount=199
SET /a llimit=5000
SET /a lcount=%llimit%
FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\q25249516.txt") DO (
 CALL :select
 >>"%sourcedir%\file$$.txt" ECHO(%%a
)
SET /a lcount=%llimit%
:select
SET /a lcount+=1
IF %lcount% lss %llimit% GOTO :EOF
SET /a lcount=0
SET /a fcount+=1
MOVE /y "%sourcedir%\file$$.txt" "%sourcedir%\file%fcount:~-2%.txt" >NUL 2>nul
GOTO :EOF

Note that I used llimit of 50000 for testing. Will overwrite the early file numbers if llimit*100 is gearter than the number of lines in the file (cure by setting fcount to 1999 and use ~3 in place of ~2 in file-renaming line.)

How to navigate to a directory in C:\ with Cygwin?

Something that is worth mentioning here is that Cygwin's cygpath, still does not handle spaced Windows paths properly, especially in Bash scripts running under Cygwin. The trick is to understand how Cygwin interprets quotes in Bash scripts.

The following does not work:

#!/bin/bash
TBDIR="/cygdrive/c/Program\ Files\ \(x86\)/MyDir/"

if [ -d "${TBDIR}" ]; then 
    echo "Found MyDir directory at: ${TBDIR}"
    cd "$TBDIR"
else 
    echo "MyDir program directory not found!"
    echo "Wrong DIR path: ${TBDIR}"
    exit 1
fi

But this does work:

#!/bin/bash
# Cygwin-ism: No quotes!
TBDIR=/cygdrive/c/Program\ Files\ \(x86\)/MyDir/

if [ -d "${TBDIR}" ]; then 
...

As far as I know, there is currently no known workaround using cygpath, that can properly handle spaces in the bash scripting context but you can use quotes in your scripts.

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

apt-get for Cygwin?

Update: you can read the more complex answer, which contains more methods and information.

There exists a couple of scripts, which can be used as simple package managers. But as far as I know, none of them allows you to upgrade packages, because it’s not an easy task on Windows since there is not possible to overwrite files in use. So you have to close all Cygwin instances first and then you can use Cygwin’s native setup.exe (which itself does the upgrade via “replace after reboot” method, when files are in use).


apt-cyg

The best one for me. Simply because it’s one of the most recent. It works correctly for both platforms - x86 and x86_64. There exists a lot of forks with some additional features. For example the kou1okada fork is one of improved versions.


Cygwin’s setup.exe

It has also command line mode. Moreover it allows you to upgrade all installed packages at once.

setup.exe-x86_64.exe -q --packages=bash,vim

Example use:

setup.exe-x86_64.exe -q --packages="bash,vim"

You can create an alias for easier use, for example:

alias cyg-get="/cygdrive/d/path/to/cygwin/setup-x86_64.exe -q -P"

Then you can for example install the Vim package with:

cyg-get vim

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

Appending a line break to an output file in a shell script

Try

echo -en "`date` User `whoami` started the script.\n" >> output.log

Try issuing this multiple times. I hope you are looking for the same output.

Git On Custom SSH Port

git clone ssh://[email protected]:[port]/gitolite-admin

Note that the port number should be there without the square brackets: []

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

Very simple verison of the rebase solution:

Go to the folder where git is installed, such as:

C:\Program Files (x86)\Git\bin

By holding shift and right clicking in the folder, you should be able to open a command prompt as administrator from there (thanks to https://stackoverflow.com/users/355389/darren-lewis for that comment),

Then run:

rebase.exe -b 0x50000000 msys-1.0.dll

This fixed it for me when the restart approach didn't work.

Hope it helps.

Using Cygwin to Compile a C program; Execution error

Look for (that is, cd to)

/cygdrive/c/

that will usually be your C:\


Also look at Using Cygwin, the Lifehacker introduction (June/2006) and, this biomed page at PhysioNet.

Is there an auto increment in sqlite?

One should not specify AUTOINCREMENT keyword near PRIMARY KEY. Example of creating autoincrement primary key and inserting:

$ sqlite3 ex1

CREATE TABLE IF NOT EXISTS room(room_id INTEGER PRIMARY KEY, name VARCHAR(25) NOT NULL, home_id VARCHAR(25) NOT NULL);

INSERT INTO room(name, home_id) VALUES ('test', 'home id test');

INSERT INTO room(name, home_id) VALUES ('test 2', 'home id test 2');

SELECT * FROM room;

will give:

1|test|home id test
2|test 2|home id test 2

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

How can I set up an editor to work with Git on Windows?

Notepad++ works just fine, although I choose to stick with Notepad, -m, or even sometimes the built-in "edit."

The problem you are encountering using Notepad++ is related to how Git is launching the editor executable. My solution to this is to set environment variable EDITOR to a batch file, rather than the actual editor executable, that does the following:

start /WAIT "E:\PortableApps\Notepad++Portable\Notepad++Portable.exe" %*

/WAIT tells the command line session to halt until the application exits, thus you will be able to edit to your heart's content while Git happily waits for you. %* passes all arguments to the batch file through to Notepad++.

C:\src> echo %EDITOR%
C:\tools\runeditor.bat

Where can I download an offline installer of Cygwin?

I maintained rsync copy of the repository in the past.

It wasn't that big. To reduce the sync size I used rsync option --exclude (like I don't need texlive or ruby and they are not essential for base system).

Check:

Than you host this mirror via HTTP/FTP for local or organization installs:

setup.exe -p emacs --site http://localhost/cygwin

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

For Windows 7 using the Git found here (it uses MinGW, not Cygwin):

  1. In the windows explorer, right-click your id_rsa file and select Properties
  2. Select the Security tab and click Edit...
  3. Check the Deny box next to Full Control for all groups EXCEPT Administrators
  4. Retry your Git command

Git on Windows: How do you set up a mergetool?

You may want to add these options too:

git config --global merge.tool p4mergetool
git config --global mergetool.p4merge.cmd 'p4merge $BASE $LOCAL $REMOTE $MERGED'
git config --global mergetool.p4mergetool.trustExitCode false
git config --global mergetool.keepBackup false

Also, I don't know why but the quoting and slash from Milan Gardian's answer screwed things up for me.

How can I change my Cygwin home folder after installation?

I did something quite simple. I did not want to change the windows 7 environment variable. So I directly edited the Cygwin.bat file.

@echo off
SETLOCAL
set HOME=C:\path\to\home
C:
chdir C:\apps\cygwin\bin
bash --login -i
ENDLOCAL

This just starts the local shell with this home directory; that is what I wanted. I am not going to remotely access this, so this worked for me.

Open Cygwin at a specific folder

I had also problem with git, that used to "steal" my cygwin commands - so i needed to run
C:\cygwin\bin\mintty.exe -
but after installing chere and executing chere -i -t mintty -f as admin (see above), you can simply use :
C:\cygwin\bin\mintty.exe -e /bin/xhere /bin/bash.exe "."
I added this in Total Commander as custom button (right click on panel > add ...) and it works very well.

How to cd into a directory with space in the name?

Use the backslash symbol to escape the space

C:\> cd my folder

will be

 C:\> cd my\folder 

Regex (grep) for multi-line search needed

Without the need to install the grep variant pcregrep, you can do multiline search with grep.

$ grep -Pzo "(?s)^(\s*)\N*main.*?{.*?^\1}" *.c

Explanation:

-P activate perl-regexp for grep (a powerful extension of regular expressions)

-z suppress newline at the end of line, substituting it for null character. That is, grep knows where end of line is, but sees the input as one big line.

-o print only matching. Because we're using -z, the whole file is like a single big line, so if there is a match, the entire file would be printed; this way it won't do that.

In regexp:

(?s) activate PCRE_DOTALL, which means that . finds any character or newline

\N find anything except newline, even with PCRE_DOTALL activated

.*? find . in non-greedy mode, that is, stops as soon as possible.

^ find start of line

\1 backreference to the first group (\s*). This is a try to find the same indentation of method.

As you can imagine, this search prints the main method in a C (*.c) source file.

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

If you are interested only in the last X lines, you can use the "tail" command like this.

$ tail -n XXXXX yourlogfile.log >> mycroppedfile.txt

This will save the last XXXXX lines of your log file to a new file called "mycroppedfile.txt"

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

How do I install cURL on cygwin?

Nobody said how to install apt-cyg

in cygwin

lynx -source rawgit.com/transcode-open/apt-cyg/master/apt-cyg > apt-cyg
install apt-cyg /bin

now you can

apt-cyg install curl

For more, see the official github repository of apt-cyg.

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

If you are using windows just go to control panel, click on automatic updates then click on Windows Update Web Site link. Just follow the step. At least this works for me, no more certificates issue i.e whenever I go to https://www.dropbox.com as before.

Cygwin Make bash command not found

I faced the same problem too. Look up to the left side, and select (full). (Make), (gcc) and many others will appear. You will be able to chose the search bar to find them easily.

How do you run a crontab in Cygwin on Windows?

You need to also install cygrunsrv so you can set cron up as a windows service, then run cron-config.

If you want the cron jobs to send email of any output you'll also need to install either exim or ssmtp (before running cron-config.)

See /usr/share/doc/Cygwin/cron-*.README for more details.

Regarding programs without a .exe extension, they are probably shell scripts of some type. If you look at the first line of the file you could see what program you need to use to run them (e.g., "#!/bin/sh"), so you could perhaps execute them from the windows scheduler by calling the shell program (e.g., "C:\cygwin\bin\sh.exe -l /my/cygwin/path/to/prog".)

How do I install cygwin components from the command line?

I wanted a solution for this similar to apt-get --print-uris, but unfortunately apt-cyg doesn't do this. The following is a solution that allowed me to download only the packages I needed, with their dependencies, and copy them to the target for installation. Here is a bash script that parses the output of apt-cyg into a list of URIs:

#!/usr/bin/bash

package=$1
depends=$( \
    apt-cyg depends $package \
    | perl -ne 'while ($x = /> ([^>\s]+)/g) { print "$1\n"; }' \
    | sort \
    | uniq)
depends=$(echo -e "$depends\n$package")
for curpkg in $depends; do
    if ! grep -q "^$curpkg " /etc/setup/installed.db; then
    apt-cyg show $curpkg \
        | perl -ne '
            if ($x = /install: ([^\s]+)/) { 
                print "$1\n"; 
            }
            if (/\[prev\]/) { 
                exit; 
            }'
    fi
done

The above will print out the paths of the packages that need downloading, relative to the cygwin mirror root, omitting any packages that are already installed. To download them, I wrote the output to a file cygwin-packages-list and then used wget:

mirror=http://cygwin.mirror.constant.com/
uris=$(for line in $(cat cygwin-packages-list); do echo "$mirror$line"; done)
wget -x $uris

The installer can then be used to install from a local cache directory. Note that for this to work I needed to copy setup.ini from a previous cygwin package cache to the directory with the downloaded files (otherwise the installer doesn't know what's what).

How to check if running in Cygwin, Mac or Linux?

I guess the uname answer is unbeatable, mainly in terms of cleanliness.

Although it takes a ridiculous time to execute, I found that testing for specific files presence also gives me good and quicker results, since I'm not invoking an executable:

So,

[ -f /usr/bin/cygwin1.dll ] && echo Yep, Cygwin running

just uses a quick Bash file presence check. As I'm on Windows right now, I can't tell you any specific files for Linuxes and Mac OS X from my head, but I'm pretty sure they do exist. :-)

Root user/sudo equivalent in Cygwin?

You probably need to run the cygwin shell as Administrator. You can right click the shortcut and click run as administrator or go into the properties of the shortcut and check it in the compatability section. Just beware.... root permissions can be dangerous.

How do I execute a file in Cygwin?

you should just be able to call it by typing in the file name. You may have to call ./a.exe as the current directory is usually not on the path for security reasons.

What is the difference between Cygwin and MinGW?

To add to the other answers, Cygwin comes with the MinGW libraries and headers and you can compile without linking to the cygwin1.dll by using -mno-cygwin flag with gcc. I greatly prefer this to using plain MinGW and MSYS.

Git push hangs when pushing to Github?

I'm wondering if it's the same thing I had...

  1. Go into Putty
  2. Click on "Default Settings" in the Saved Sessions. Click Load
  3. Go to Connection -> SSH -> Bugs
  4. Set "Chokes on PuTTY's SSH-2 'winadj' requests" to On (instead of Auto)
  5. Go Back to Session in the treeview (top of the list)
  6. Click on "Default Settings" in the Saved Sessions box. Click Save.

This (almost verbatim) comes from :

https://tortoisegit.org/issue/1880

fatal: early EOF fatal: index-pack failed

Make sure your drive has enough space left

'\r': command not found - .bashrc / .bash_profile

As per this gist, the solution is to create a ~/.bash_profile (in HOME directory) that contains:

export SHELLOPTS
set -o igncr

Array vs. Object efficiency in JavaScript

In NodeJS if you know the ID, the looping through the array is very slow compared to object[ID].

const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;

//create data
for(var i=0;i<1000000;i++){
  var getUnique = `${uniqueString()}`;
  if(i===888555) seeking = getUnique;
  arr.push(getUnique);
  obj[getUnique] = true;
}

//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
  if(arr[x]===seeking){
    console.log('Array result:');
    console.timeEnd('arrTimer');
    break;
  }
}

//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');

And the results:

Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms

Even if the seeking ID is the first one in the array/object:

Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms

How to set proper codeigniter base url?

Base URL should be absolute, including the protocol:

$config['base_url'] = "http://somesite.com/somedir/";

If using the URL helper, then base_url() will output the above string.

Passing arguments to base_url() or site_url() will result in the following (assuming $config['index_page'] = "index.php";:

echo base_url('assets/stylesheet.css'); // http://somesite.com/somedir/assets/stylesheet.css
echo site_url('mycontroller/mymethod'); // http://somesite.com/somedir/index.php/mycontroller/mymethod

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;
}

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

No route matches "/users/sign_out" devise rails 3

The problem begin with rails 3.1... in /app/assets/javascript/ just look for application.js.

If the file doesn't exist create a file with that name I don't know why my file disappear or never was created on "rails new app"....

That file is the instance for jquery....

Round up double to 2 decimal places

Consider using NumberFormatter for this purpose, it provides more flexibility if you want to print the percentage sign of the ratio or if you have things like currency and large numbers.

let amount = 10.000001
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
let formattedAmount = formatter.string(from: amount as NSNumber)! 
print(formattedAmount) // 10

Get the key corresponding to the minimum value within a dictionary

For multiple keys which have equal lowest value, you can use a list comprehension:

d = {320:1, 321:0, 322:3, 323:0}

minval = min(d.values())
res = [k for k, v in d.items() if v==minval]

[321, 323]

An equivalent functional version:

res = list(filter(lambda x: d[x]==minval, d))

How to iterate over rows in a DataFrame in Pandas

You should use df.iterrows(). Though iterating row-by-row is not especially efficient since Series objects have to be created.

Flexbox not giving equal width to elements

There is an important bit that is not mentioned in the article to which you linked and that is flex-basis. By default flex-basis is auto.

From the spec:

If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)

Each flex item has a flex-basis which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow) among the items. With auto, that basis is the contents size (or defined size with width, etc.). As a result, items with bigger text within are being given more space overall in your example.

If you want your elements to be completely even, you can set flex-basis: 0. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow.

li {
    flex-grow: 1;
    flex-basis: 0;
    /* ... */
}

This diagram from the spec does a pretty good job of illustrating the point.

And here is a working example with your fiddle.

Multiline for WPF TextBox

The only property corresponding in WPF to the

Winforms property: TextBox.Multiline = true

is the WPF property: TextBox.AcceptsReturn = true.

<TextBox AcceptsReturn="True" ...... />

All other settings, such as VerticalAlignement, WordWrap etc., only control how the TextBox interacts in the UI but do not affect the Multiline behaviour.

How to get max value of a column using Entity Framework?

maxAge = Persons.Max(c => c.age)

or something along those lines.

jQuery exclude elements with certain class in selector

To add some info that helped me today, a jQuery object/this can also be passed in to the .not() selector.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $(".navitem").click(function(){_x000D_
        $(".navitem").removeClass("active");_x000D_
        $(".navitem").not($(this)).addClass("active");_x000D_
    });_x000D_
});
_x000D_
.navitem_x000D_
{_x000D_
    width: 100px;_x000D_
    background: red;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
    text-align: center;_x000D_
}_x000D_
.navitem.active_x000D_
{_x000D_
    background:green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="navitem">Home</div>_x000D_
<div class="navitem">About</div>_x000D_
<div class="navitem">Pricing</div>
_x000D_
_x000D_
_x000D_

The above example can be simplified, but wanted to show the usage of this in the not() selector.

Count the Number of Tables in a SQL Server Database

Try this:

SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

Find files and tar them (with spaces)

Try running:

    find . -type f | xargs -d "\n" tar -czvf backup.tar.gz 

Using AES encryption in C#

Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

After reading your comment on my previous answer I thought I might put this as a separate answer.

Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.

That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with

WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/

This is the jQuery

$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();    
$('.active').show();

    $('#button-next').click(function(){

    $('.active').removeClass('active').addClass('oldActive');    
                   if ( $('.oldActive').is(':last-child')) {
        $('.sp').first().addClass('active');
        }
        else{
        $('.oldActive').next().addClass('active');
        }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();


    });

       $('#button-previous').click(function(){
    $('.active').removeClass('active').addClass('oldActive');    
           if ( $('.oldActive').is(':first-child')) {
        $('.sp').last().addClass('active');
        }
           else{
    $('.oldActive').prev().addClass('active');
           }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();
    });




});

So now the explanation.
Stage 1
1) Load the script on document ready.

2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.

3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;

Stage 2 Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.

2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.

3) We remove the class oldActive because it's no longer needed.

4) fadeOut all of the slides

5) fade In the active slides

Step 3

Same as in step two but using some reverse logic for traversing through the elements backwards.

It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

http://www.eclipse.org/cdt/ ^Give that a try

I have not used the CDT for eclipse but I do use Eclipse Java for Ubuntu 12.04 and it works wonders.

Simulate low network connectivity for Android

There's a simple way of testing low speeds on a real device that seems to have been overlooked. It does require a Mac and an ethernet (or other wired) network connection.

Turn on Wifi sharing on the Mac, turning your computer into a Wifi hotspot, connect your device to this. Use Netlimiter/Charles Proxy or Network Link Conditioner (which you may have already installed) to control the speeds.

For more details and to understand what sort of speeds you should test on check out: http://opensignal.com/blog/2016/02/05/go-slow-how-why-to-test-apps-on-poor-connections/

Ruby on Rails generates model field:type - what are the options for field:type?

Remember to not capitalize your text when writing this command. For example:

Do write:

rails g model product title:string description:text image_url:string price:decimal

Do not write:

rails g Model product title:string description:text image_url:string price:decimal

At least it was a problem to me.

AppFabric installation failed because installer MSI returned with error code : 1603

I had this same error. Just had to install IIS and everything worked.

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

How to process a file in PowerShell line-by-line as a stream

If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:

# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }

# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }

# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }

UPDATE: If you are still not scared then try to use the .NET reader:

$reader = [System.IO.File]::OpenText("my.log")
try {
    for() {
        $line = $reader.ReadLine()
        if ($line -eq $null) { break }
        # process the line
        $line
    }
}
finally {
    $reader.Close()
}

UPDATE 2

There are comments about possibly better / shorter code. There is nothing wrong with the original code with for and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is

$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
    $line
}

Concatenating bits in VHDL

You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:

process(b0,b1,b2,b3)
   variable bcat : std_logic_vector(0 to 3);
begin
   bcat := b0 & b1 & b2 & b3;
   case bcat is
      when "0000" => x <= 1;
      when others => x <= 2;
   end case;
end process;

What are some examples of commonly used practices for naming git branches?

My personal preference is to delete the branch name after I’m done with a topic branch.

Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.

The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.

That makes the output of git branch more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.

Randomize a List<T>

    public static List<T> Randomize<T>(List<T> list)
    {
        List<T> randomizedList = new List<T>();
        Random rnd = new Random();
        while (list.Count > 0)
        {
            int index = rnd.Next(0, list.Count); //pick a random item from the master list
            randomizedList.Add(list[index]); //place it at the end of the randomized list
            list.RemoveAt(index);
        }
        return randomizedList;
    }

Min and max value of input in angular4 application

I succeeded by using a form control. This is my html code :

<md-input-container>
    <input type="number" min="0" max="100" required mdInput placeholder="Charge" [(ngModel)]="rateInput" name="rateInput" [formControl]="rateControl">
    <md-error>Please enter a value between 0 and 100</md-error>
</md-input-container>

And in my Typescript code, I have :

this.rateControl = new FormControl("", [Validators.max(100), Validators.min(0)])

So, if we enter a value higher than 100 or smaller than 0, the material design input become red and the field is not validate. So after, if the value is not good, I don't save when I click on the save button.

Does hosts file exist on the iPhone? How to change it?

Not programming related, but I'll answer anyway. It's in /etc/hosts.

You can change it with a simple text editor such as nano.

(Obviously you would need a jailbroken iphone for this)

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

CURSORS are an option here, but generally frowned upon as they often do not make best use of the query engine. Consider investigating 'SET Based Queries' to see if you can achieve what it is you want to do without using a CURSOR.

How to use DISTINCT and ORDER BY in same SELECT statement?

It can be done using inner query Like this

$query = "SELECT * 
            FROM (SELECT Category  
                FROM currency_rates                 
                ORDER BY id DESC) as rows               
            GROUP BY currency";

ReactJS - .JS vs .JSX

There is none when it comes to file extensions. Your bundler/transpiler/whatever takes care of resolving what type of file contents there is.

There are however some other considerations when deciding what to put into a .js or a .jsx file type. Since JSX isn't standard JavaScript one could argue that anything that is not "plain" JavaScript should go into its own extensions ie., .jsx for JSX and .ts for TypeScript for example.

There's a good discussion here available for read

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

Just to add my $.02 here, I ran into a similar issue just yesterday, where 168 of my tests were missing. I tried most everything in this post - most especially making sure my version(s) of NUnit were the same - all to no avail. I then remembered that I had my tests divided into playlists; and these do not update automatically as you add new tests. So, when I deleted the playlists, BAM!, all of my tests were back once more.

Recommended SQL database design for tags or tagging

I would suggest following design : Item Table: Itemid, taglist1, taglist2
this will be fast and make easy saving and retrieving the data at item level.

In parallel build another table: Tags tag do not make tag unique identifier and if you run out of space in 2nd column which contains lets say 100 items create another row.

Now while searching for items for a tag it will be super fast.

How to cancel an $http request in AngularJS?

If you want to cancel pending requests on stateChangeStart with ui-router, you can use something like this:

// in service

                var deferred = $q.defer();
                var scope = this;
                $http.get(URL, {timeout : deferred.promise, cancel : deferred}).success(function(data){
                    //do something
                    deferred.resolve(dataUsage);
                }).error(function(){
                    deferred.reject();
                });
                return deferred.promise;

// in UIrouter config

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
    //To cancel pending request when change state
       angular.forEach($http.pendingRequests, function(request) {
          if (request.cancel && request.timeout) {
             request.cancel.resolve();
          }
       });
    });

Passing std::string by Value or Reference

I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.

Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

Overriding interface property type defined in Typescript d.ts file

You can't change the type of an existing property.

You can add a property:

interface A {
    newProperty: any;
}

But changing a type of existing one:

interface A {
    property: any;
}

Results in an error:

Subsequent variable declarations must have the same type. Variable 'property' must be of type 'number', but here has type 'any'

You can of course have your own interface which extends an existing one. In that case, you can override a type only to a compatible type, for example:

interface A {
    x: string | number;
}

interface B extends A {
    x: number;
}

By the way, you probably should avoid using Object as a type, instead use the type any.

In the docs for the any type it states:

The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation. You might expect Object to play a similar role, as it does in other languages. But variables of type Object only allow you to assign any value to them - you can’t call arbitrary methods on them, even ones that actually exist:

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

javascript toISOString() ignores timezone offset

moment.js FTW!!!

Just convert your date to a moment and manipulate it however you please:

var d = new Date(twDate);
var m = moment(d).format();
console.log(m);
// example output:
// 2016-01-08T00:00:00-06:00

http://momentjs.com/docs/

SQL Server default character encoding

SELECT DATABASEPROPERTYEX('DBName', 'Collation') SQLCollation;

Where DBName is your database name.

How to use "svn export" command to get a single file from the repository?

I know the OP was asking about doing the export from the command line, but just in case this is helpful to anyone else out there...

You could just let Eclipse (plus one of the plugins discussed here) do the work for you.

Obviously, downloading Eclipse just for doing a single export is overkill, but if you are already using it for development, you can also do an svn export simply from your IDE's context menu when browsing an SVN repository.

Advantages:

  • easier for those not so familiar with using SVN at the command-line level (but you can learn about what happens at the command-line level by looking at the SVN console with a range of commands)
  • you'd already have your SVN details set up and wouldn't have to worry about authenticating, etc.
  • you don't have to worry about mistyping the URL, or remembering the order of parameters
  • you can specify in a dialog which directory you'd like to export to
  • you can specify in a dialog whether you'd like to export from TRUNK/HEAD or use a specific revision

jQuery: how to find first visible input/select/textarea excluding buttons?

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):

$('form').find(':text,textarea,select').filter(':visible:first')

Some projects cannot be imported because they already exist in the workspace error in Eclipse

In my case i had deleted the resources directory from my .metadata.plugins:

  1. Go to your workspace
  2. Enter .metadata.plugins
  3. Delete : org.eclipse.core.resources directory

enter image description here

Finding what methods a Python object has

Open a Bash shell (Ctrl + Alt + T on Ubuntu). Start a Python 3 shell in it. Create an object to observe the methods of. Just add a dot after it and press Tab twice and you'll see something like this:

user@note:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> s = "Any object. Now it's a string"
>>> s. # here tab should be pressed twice
s.__add__(           s.__rmod__(          s.istitle(
s.__class__(         s.__rmul__(          s.isupper(
s.__contains__(      s.__setattr__(       s.join(
s.__delattr__(       s.__sizeof__(        s.ljust(
s.__dir__(           s.__str__(           s.lower(
s.__doc__            s.__subclasshook__(  s.lstrip(
s.__eq__(            s.capitalize(        s.maketrans(
s.__format__(        s.casefold(          s.partition(
s.__ge__(            s.center(            s.replace(
s.__getattribute__(  s.count(             s.rfind(
s.__getitem__(       s.encode(            s.rindex(
s.__getnewargs__(    s.endswith(          s.rjust(
s.__gt__(            s.expandtabs(        s.rpartition(
s.__hash__(          s.find(              s.rsplit(
s.__init__(          s.format(            s.rstrip(
s.__iter__(          s.format_map(        s.split(
s.__le__(            s.index(             s.splitlines(
s.__len__(           s.isalnum(           s.startswith(
s.__lt__(            s.isalpha(           s.strip(
s.__mod__(           s.isdecimal(         s.swapcase(
s.__mul__(           s.isdigit(           s.title(
s.__ne__(            s.isidentifier(      s.translate(
s.__new__(           s.islower(           s.upper(
s.__reduce__(        s.isnumeric(         s.zfill(
s.__reduce_ex__(     s.isprintable(
s.__repr__(          s.isspace(

Intro to GPU programming

I think the others have answered your second question. As for the first, the "Hello World" of CUDA, I don't think there is a set standard, but personally, I'd recommend a parallel adder (i.e. a programme that sums N integers).

If you look the "reduction" example in the NVIDIA SDK, the superficially simple task can be extended to demonstrate numerous CUDA considerations such as coalesced reads, memory bank conflicts and loop unrolling.

See this presentation for more info:

http://www.gpgpu.org/sc2007/SC07_CUDA_5_Optimization_Harris.pdf

Multiple Cursors in Sublime Text 2 Windows

Mac Users, let me save you the time:

  • Cmd+a: select the lines you want a cursor
  • Cmd+Shift+l: to create the cursor

How do I add a auto_increment primary key in SQL Server database?

It can be done in a single command. You need to set the IDENTITY property for "auto number":

ALTER TABLE MyTable ADD mytableID int NOT NULL IDENTITY (1,1) PRIMARY KEY

More precisely, to set a named table level constraint:

ALTER TABLE MyTable
   ADD MytableID int NOT NULL IDENTITY (1,1),
   CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (MyTableID)

See ALTER TABLE and IDENTITY on MSDN

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

I've tried everything suggested here but didn't work for me. So in case I can help anyone with a similar issue, every single tutorial I've checked is not updated to work with version 4.

Here is what I've done to make it work

import React from 'react';
import App from './App';

import ReactDOM from 'react-dom';
import {
    HashRouter,
    Route
} from 'react-router-dom';


 ReactDOM.render((
        <HashRouter>
            <div>
                <Route path="/" render={()=><App items={temasArray}/>}/>
            </div>
        </HashRouter >
    ), document.getElementById('root'));

That's the only way I have managed to make it work without any errors or warnings.

In case you want to pass props to your component for me the easiest way is this one:

 <Route path="/" render={()=><App items={temasArray}/>}/>

Log4j output not displayed in Eclipse console

A simple log4j.properties file can look like this:

log4j.rootCategory=debug,console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.out
log4j.appender.console.immediateFlush=true
log4j.appender.console.encoding=UTF-8
log4j.appender.console.threshold=info

log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d [%t] %-5p %c - %m%n

Place it in your class path (target/classes folder). Or you if you have a Maven project, place it under your src/main/resources and Eclipse will copy it to your class path.

Without a configuration file, you should see an Eclipse warning in the console like this:

log4j:WARN No appenders could be found for logger.
log4j:WARN Please initialize the log4j system properly.

Android - How to download a file from a webserver

Apart from using AsyncTask you can put the operation in runnable-

Runnable r=new Runnable()
{

public void run()
{
///-------network operation code
}
};

//--------call r in this way--
Thread t=new Thread(r);`enter code here`
t.start();

Also put the UI work in a haldler..such as updating a textview etc..

Why can't I declare static methods in an interface?

The reason lies in the design-principle, that java does not allow multiple inheritance. The problem with multiple inheritance can be illustrated by the following example:

public class A {
   public method x() {...}
}
public class B {
   public method x() {...}
}
public class C extends A, B { ... }

Now what happens if you call C.x()? Will be A.x() or B.x() executed? Every language with multiple inheritance has to solve this problem.

Interfaces allow in Java some sort of restricted multiple inheritance. To avoid the problem above, they are not allowed to have methods. If we look at the same problem with interfaces and static methods:

public interface A {
   public static method x() {...}
}
public interface B {
   public static method x() {...}
}
public class C implements A, B { ... }

Same problem here, what happen if you call C.x()?

git: Your branch is ahead by X commits

git fetch will resolve this for you

If my understanding is correct, your local (cached) origin/master is out of date. This command will update the repository state from the server.

How do I debug a stand-alone VBScript script?

For posterity, here's Microsoft's article KB308364 on the subject. This no longer exists on their website, it is from an archive.

How to debug Windows Script Host, VBScript, and JScript files

SUMMARY

The purpose of this article is to explain how to debug Windows Script Host (WSH) scripts, which can be written in any ActiveX script language (as long as the proper language engine is installed), but which, by default, are written in VBScript and JScript. There are certain flags in the registry and, depending on the debugger used, certain required procedures to enable debugging.

MORE INFORMATION

To debug WSH scripts in Microsoft Visual InterDev, the Microsoft Script Debugger, or any other debugger, use the following command-line syntax to start the script:

wscript.exe //d <path to WSH file>
           This code informs the user when a runtime error has occurred and gives the user a choice to debug the application. Also, the //x flag

can be used, as follows, to throw an immediate exception, which starts the debugger immediately after the script starts running:

wscript.exe //d //x <path to WSH file>
           After a debug condition exists, the following registry key determines which debugger will be used:

HKEY_CLASSES_ROOT\CLSID\{834128A2-51F4-11D0-8F20-00805F2CD064}\LocalServer32

The script debugger should be Msscrdbg.exe, and the Visual InterDev debugger should be Mdm.exe.

If Visual InterDev is the default debugger, make sure that just-in-time (JIT) functionality is enabled. To do this, follow these steps:

  1. Start Visual InterDev.

  2. On the Tools menu, click Options.

  3. Click Debugger, and then ensure that the Just-In-Time options are selected for both the General and Script categories.

Additionally, if you are trying to debug a .wsf file, make sure that the following registry key is set to 1:

HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug

PROPERTIES

Article ID: 308364 - Last Review: June 19, 2014 - Revision: 3.0

Keywords: kbdswmanage2003swept kbinfo KB308364

Body of Http.DELETE request in Angular2

Below is the relevant code example for Angular 2/4/5 projects:

let headers = new Headers({
  'Content-Type': 'application/json'
});

let options = new RequestOptions({
  headers: headers,
  body: {
    id: 123
  }
});

return this.http.delete("http//delete.example.com/delete", options)
  .map((response: Response) => {
    return response.json()
  })
  .catch(err => {
    return err;
  });

Notice that body is passed through RequestOptions

How to create a windows service from java app

I always just use sc.exe (see http://support.microsoft.com/kb/251192). It should be installed on XP from SP1, and if it's not in your flavor of Vista, you can download load it with the Vista resource kit.

I haven't done anything too complicated with Java, but using either a fully qualified command line argument (x:\java.exe ....) or creating a script with Ant to include depencies and set parameters works fine for me.

Append data frames together in a for loop

x <- c(1:10) 

# empty data frame with variables ----

df <- data.frame(x1=character(),
                     y1=character())

for (i in x) {
  a1 <- c(x1 == paste0("The number is ",x[i]),y1 == paste0("This is another number ", x[i]))
  df <- rbind(df,a1)
}

names(df) <- c("st_column","nd_column")
View(df)

that might be a good way to do so....

Maven version with a property

If you're using Maven 3, one option to work around this problem is to use the versions plugin http://www.mojohaus.org/versions-maven-plugin/

Specifically the commands,

mvn versions:set -DnewVersion=2.0-RELEASE
mvn versions:commit

This will update the parent and child poms to 2.0-RELEASE. You can run this as a build step before.

Unlike the release plugin, it doesn't try to talk to your source control

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

Yes, statics are generally bad - generally, but in this case, the static is the most secure code you can write. Since the security context associates a Principal with the currently running thread, the most secure code would access the static from the thread as directly as possible. Hiding the access behind a wrapper class that is injected provides an attacker with more points to attack. They wouldn't need access to the code (which they would have a hard time changing if the jar was signed), they just need a way to override the configuration, which can be done at runtime or slipping some XML onto the classpath. Even using annotation injection in the signed code would be overridable with external XML. Such XML could inject the running system with a rogue principal. This is probably why Spring is doing something so un-Spring-like in this case.

Multi-gradient shapes

I don't think you can do this in XML (at least not in Android), but I've found a good solution posted here that looks like it'd be a great help!

ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient lg = new LinearGradient(0, 0, width, height,
            new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
            new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);
        return lg;
    }
};

PaintDrawable p=new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);

Basically, the int array allows you to select multiple color stops, and the following float array defines where those stops are positioned (from 0 to 1). You can then, as stated, just use this as a standard Drawable.

Edit: Here's how you could use this in your scenario. Let's say you have a Button defined in XML like so:

<Button
    android:id="@+id/thebutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Press Me!"
    />

You'd then put something like this in your onCreate() method:

Button theButton = (Button)findViewById(R.id.thebutton);
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient lg = new LinearGradient(0, 0, 0, theButton.getHeight(),
            new int[] { 
                Color.LIGHT_GREEN, 
                Color.WHITE, 
                Color.MID_GREEN, 
                Color.DARK_GREEN }, //substitute the correct colors for these
            new float[] {
                0, 0.45f, 0.55f, 1 },
            Shader.TileMode.REPEAT);
         return lg;
    }
};
PaintDrawable p = new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
theButton.setBackground((Drawable)p);

I cannot test this at the moment, this is code from my head, but basically just replace, or add stops for the colors that you need. Basically, in my example, you would start with a light green, fade to white slightly before the center (to give a fade, rather than a harsh transition), fade from white to mid green between 45% and 55%, then fade from mid green to dark green from 55% to the end. This may not look exactly like your shape (Right now, I have no way of testing these colors), but you can modify this to replicate your example.

Edit: Also, the 0, 0, 0, theButton.getHeight() refers to the x0, y0, x1, y1 coordinates of the gradient. So basically, it starts at x = 0 (left side), y = 0 (top), and stretches to x = 0 (we're wanting a vertical gradient, so no left to right angle is necessary), y = the height of the button. So the gradient goes at a 90 degree angle from the top of the button to the bottom of the button.

Edit: Okay, so I have one more idea that works, haha. Right now it works in XML, but should be doable for shapes in Java as well. It's kind of complex, and I imagine there's a way to simplify it into a single shape, but this is what I've got for now:

green_horizontal_gradient.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <corners
        android:radius="3dp"
        />
    <gradient
        android:angle="0"
        android:startColor="#FF63a34a"
        android:endColor="#FF477b36"
        android:type="linear"
        />    
</shape>

half_overlay.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <solid
        android:color="#40000000"
        />
</shape>

layer_list.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <item
        android:drawable="@drawable/green_horizontal_gradient"
        android:id="@+id/green_gradient"
        />
    <item
        android:drawable="@drawable/half_overlay"
        android:id="@+id/half_overlay"
        android:top="50dp"
        />
</layer-list>

test.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    >
    <TextView
        android:id="@+id/image_test"
        android:background="@drawable/layer_list"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:gravity="center"
        android:text="Layer List Drawable!"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        android:textSize="26sp"     
        />
</RelativeLayout>

Okay, so basically I've created a shape gradient in XML for the horizontal green gradient, set at a 0 degree angle, going from the top area's left green color, to the right green color. Next, I made a shape rectangle with a half transparent gray. I'm pretty sure that could be inlined into the layer-list XML, obviating this extra file, but I'm not sure how. But okay, then the kind of hacky part comes in on the layer_list XML file. I put the green gradient as the bottom layer, then put the half overlay as the second layer, offset from the top by 50dp. Obviously you'd want this number to always be half of whatever your view size is, though, and not a fixed 50dp. I don't think you can use percentages, though. From there, I just inserted a TextView into my test.xml layout, using the layer_list.xml file as my background. I set the height to 100dp (twice the size of the offset of the overlay), resulting in the following:

alt text

Tada!

One more edit: I've realized you can just embed the shapes into the layer list drawable as items, meaning you don't need 3 separate XML files any more! You can achieve the same result combining them like so:

layer_list.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <item>
        <shape
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle"
            >
            <corners
                android:radius="3dp"
                />
            <gradient
                android:angle="0"
                android:startColor="#FF63a34a"
                android:endColor="#FF477b36"
                android:type="linear"
                />    
        </shape>
    </item>
    <item
        android:top="50dp" 
        >
        <shape
            android:shape="rectangle"
            >
            <solid
                android:color="#40000000"
                />
        </shape>            
    </item>
</layer-list>

You can layer as many items as you like this way! I may try to play around and see if I can get a more versatile result through Java.

I think this is the last edit...: Okay, so you can definitely fix the positioning through Java, like the following:

    TextView tv = (TextView)findViewById(R.id.image_test);
    LayerDrawable ld = (LayerDrawable)tv.getBackground();
    int topInset = tv.getHeight() / 2 ; //does not work!
    ld.setLayerInset(1, 0, topInset, 0, 0);
    tv.setBackgroundDrawable(ld);

However! This leads to yet another annoying problem in that you cannot measure the TextView until after it has been drawn. I'm not quite sure yet how you can accomplish this...but manually inserting a number for topInset does work.

I lied, one more edit

Okay, found out how to manually update this layer drawable to match the height of the container, full description can be found here. This code should go in your onCreate() method:

final TextView tv = (TextView)findViewById(R.id.image_test);
        ViewTreeObserver vto = tv.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                LayerDrawable ld = (LayerDrawable)tv.getBackground();
                ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0);
            }
        });

And I'm done! Whew! :)

Remove substring from the string

If it is a the end of the string, you can also use chomp:

"hello".chomp("llo")     #=> "he"

Copy text from nano editor to shell

The thread is quite old, but today I humbled around with the same question and all the mentioned solutions above did not help. As I wished to copy long lines my solution is - acording to what @themisterunknown wrote above - outside nano. I used awk!

awk '{ if (NR==87) print $0 }' filename

where NR==[line number] and $0 is complete line.

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

Query error with ambiguous column name in SQL

if you join 2 or more tables and they have similar names for their columns sql server wants you to qualify columns which they belong.

SELECT  ev.[ID]
    ,[Description]
    FROM   [Events] as ev 
    LEFT JOIN  [Units] as un ON ev.UnitID = un.UnitId  

if Events and Units tables has same column name (ID) SQL server wants you to use aliases.

Environment Specific application.properties file in Spring Boot application

we can do like this:

in application.yml:

spring:
  profiles:
    active: test //modify here to switch between environments
    include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
  port: 5000

and in application-local.yml:

server:
  address: 0.0.0.0
  port: 8080

then spring boot will start our app as we wish to.

IIS AppPoolIdentity and file system write access permissions

The ApplicationPoolIdentity is assigned membership of the Users group as well as the IIS_IUSRS group. On first glance this may look somewhat worrying, however the Users group has somewhat limited NTFS rights.

For example, if you try and create a folder in the C:\Windows folder then you'll find that you can't. The ApplicationPoolIdentity still needs to be able to read files from the windows system folders (otherwise how else would the worker process be able to dynamically load essential DLL's).

With regard to your observations about being able to write to your c:\dump folder. If you take a look at the permissions in the Advanced Security Settings, you'll see the following:

enter image description here

See that Special permission being inherited from c:\:

enter image description here

That's the reason your site's ApplicationPoolIdentity can read and write to that folder. That right is being inherited from the c:\ drive.

In a shared environment where you possibly have several hundred sites, each with their own application pool and Application Pool Identity, you would store the site folders in a folder or volume that has had the Users group removed and the permissions set such that only Administrators and the SYSTEM account have access (with inheritance).

You would then individually assign the requisite permissions each IIS AppPool\[name] requires on it's site root folder.

You should also ensure that any folders you create where you store potentially sensitive files or data have the Users group removed. You should also make sure that any applications that you install don't store sensitive data in their c:\program files\[app name] folders and that they use the user profile folders instead.

So yes, on first glance it looks like the ApplicationPoolIdentity has more rights than it should, but it actually has no more rights than it's group membership dictates.

An ApplicationPoolIdentity's group membership can be examined using the SysInternals Process Explorer tool. Find the worker process that is running with the Application Pool Identity you're interested in (you will have to add the User Name column to the list of columns to display:

enter image description here

For example, I have a pool here named 900300 which has an Application Pool Identity of IIS APPPOOL\900300. Right clicking on properties for the process and selecting the Security tab we see:

enter image description here

As we can see IIS APPPOOL\900300 is a member of the Users group.

You have not concluded your merge (MERGE_HEAD exists)

Try changing any temporary file. Like just remove any space or add space and then commit and push that file.

git add 'temporary_change_file'

git commit -m "git issue resolving"

git push origin develop

And then try git pull,

git pull origin develop

Hope this might help you.

How to Scroll Down - JQuery

    jQuery(function ($) {
        $('li#linkss').find('a').on('click', function (e) {
            var
                link_href = $(this).attr('href')
                , $linkElem = $(link_href)
                , $linkElem_scroll = $linkElem.get(0) && $linkElem.position().top - 115;
            $('html, body')
                .animate({
                    scrollTop: $linkElem_scroll
                }, 'slow');
            e.preventDefault();
        });
    });

How to redirect a URL path in IIS?

Here's the config for ISAPI_Rewrite 3:

RewriteBase /

RewriteCond %{HTTP_HOST} ^mysite.org.uk$ [NC]

RewriteRule ^stuff/(.+)$ http://stuff.mysite.org.uk/$1 [NC,R=301,L]

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

Between execution of left != null and queue.add(left) another thread could have changed the value of left to null.

To work around this you have several options. Here are some:

  1. Use a local variable with smart cast:

     val node = left
     if (node != null) {
         queue.add(node)
     }
    
  2. Use a safe call such as one of the following:

     left?.let { node -> queue.add(node) }
     left?.let { queue.add(it) }
     left?.let(queue::add)
    
  3. Use the Elvis operator with return to return early from the enclosing function:

     queue.add(left ?: return)
    

    Note that break and continue can be used similarly for checks within loops.

find difference between two text files with one item per line

With GNU sed:

sed 's#[^^]#[&]#g;s#\^#\\^#g;s#^#/^#;s#$#$/d#' file1 | sed -f- file2

How it works:

The first sed produces an output like this:

/^[d][s][f]$/d
/^[s][d][f][s][d]$/d
/^[d][s][f][s][d][f]$/d

Then it is used as a sed script by the second sed.

Identify if a string is a number

If you want to catch a broader spectrum of numbers, à la PHP's is_numeric, you can use the following:

// From PHP documentation for is_numeric
// (http://php.net/manual/en/function.is-numeric.php)

// Finds whether the given variable is numeric.

// Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
// exponential part. Thus +0123.45e6 is a valid numeric value.

// Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
static readonly Regex _isNumericRegex =
    new Regex(  "^(" +
                /*Hex*/ @"0x[0-9a-f]+"  + "|" +
                /*Bin*/ @"0b[01]+"      + "|" + 
                /*Oct*/ @"0[0-7]*"      + "|" +
                /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" + 
                ")$" );
static bool IsNumeric( string value )
{
    return _isNumericRegex.IsMatch( value );
}

Unit Test:

static void IsNumericTest()
{
    string[] l_unitTests = new string[] { 
        "123",      /* TRUE */
        "abc",      /* FALSE */
        "12.3",     /* TRUE */
        "+12.3",    /* TRUE */
        "-12.3",    /* TRUE */
        "1.23e2",   /* TRUE */
        "-1e23",    /* TRUE */
        "1.2ef",    /* FALSE */
        "0x0",      /* TRUE */
        "0xfff",    /* TRUE */
        "0xf1f",    /* TRUE */
        "0xf1g",    /* FALSE */
        "0123",     /* TRUE */
        "0999",     /* FALSE (not octal) */
        "+0999",    /* TRUE (forced decimal) */
        "0b0101",   /* TRUE */
        "0b0102"    /* FALSE */
    };

    foreach ( string l_unitTest in l_unitTests )
        Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );

    Console.ReadKey( true );
}

Keep in mind that just because a value is numeric doesn't mean it can be converted to a numeric type. For example, "999999999999999999999999999999.9999999999" is a perfeclty valid numeric value, but it won't fit into a .NET numeric type (not one defined in the standard library, that is).

Get startup type of Windows service using PowerShell

In PowerShell you can use the command Set-Service:

Set-Service -Name Winmgmt -StartupType Manual

I haven't found a PowerShell command to view the startup type though. One would assume that the command Get-Service would provide that, but it doesn't seem to.

How to make IPython notebook matplotlib plot inline

If your matplotlib version is above 1.4, it is also possible to use

IPython 3.x and above

%matplotlib notebook

import matplotlib.pyplot as plt

older versions

%matplotlib nbagg

import matplotlib.pyplot as plt

Both will activate the nbagg backend, which enables interactivity.

Example plot with the nbagg backend

How to get value from form field in django framework?

Take your pick:

def my_view(request):

    if request.method == 'POST':
        print request.POST.get('my_field')

        form = MyForm(request.POST)

        print form['my_field'].value()
        print form.data['my_field']

        if form.is_valid():

            print form.cleaned_data['my_field']
            print form.instance.my_field

            form.save()
            print form.instance.id  # now this one can access id/pk

Note: the field is accessed as soon as it's available.

How to check python anaconda version installed on Windows 10 PC?

On the anaconda prompt, do a

  • conda -V or conda --version to get the conda version.
  • python -V or python --version to get the python version.
  • conda list anaconda$ to get the Anaconda version.
  • conda list to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).
  • conda info to get all the current environment details.
  • conda info --envs To see a list of all your environments

Detailed description here, download cheat sheet from here

Install gitk on Mac

There are two ways to fix this:

  1. Unix Way (simple and recommended)
  2. Homebrew Way

1. Unix Way: In 4 simple steps

  1. Execute which git in the terminal to know the location of your git executable. Open that directory & locate gitk inside the bin folder. Copy the path --- typically /usr/local/git/bin
  2. Edit your ~/.bash_profile to add the location of local git & gitk in the paths or, simply copy-pasta from the sample written below.

Sample bash_profile:

# enabling gitk
export PATH=/usr/local/git/bin:$PATH

If you don't have a bash_profile want to learn how to create one, then click here.

  1. This step is relevant if you're using El Capitan or higher & you run into an unknown color name “lime” error. Locate gitk executable (typically at /usr/local/bin/gitk), take a backup & open it in a text editor. Find all occurences of lime in the file & replace them with "#99FF00".
  2. Reload bash: source ~/.bash_profile

Now, run gitk


2. HomeBrew way

Updates - If you do not have homebrew on your mac, get it installed first. It may require sudo privileges.

  • brew update
  • brew doctor
  • brew link git
  • added /usr/local/Cellar/git/2.4.0/bin to path & then reload bash & run gitk
  • No luck yet? Proceed further.
  • Run which git & observe if git is still linked to /usr/bin/git
  • If yes, then open the directory & locate the was a binary executable.
  • Take its backup, may be save with a name git.bak & delete the original file
  • Reload the terminal - source ~/.bash_profile

Running CMD command in PowerShell

For those who may need this info:

I figured out that you can pretty much run a command that's in your PATH from a PS script, and it should work.

Sometimes you may have to pre-launch this command with cmd.exe /c

Examples

Calling git from a PS script

I had to repackage a git client wrapped in Chocolatey (for those who may not know, it's a kind of app-store for Windows) which massively uses PS scripts.

I found out that, once git is in the PATH, commands like

$ca_bundle = git config --get http.sslCAInfo

will store the location of git crt file in $ca_bundle variable.

Looking for an App

Another example that is a combination of the present SO post and this SO post is the use of where command

$java_exe = cmd.exe /c where java

will store the location of java.exe file in $java_exe variable.

Convert an integer to a float number

Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:

uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        alias for uint8
rune        alias for int32

Which means that you need to use float64(integer_value).

Splitting on first occurrence

From the docs:

str.split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

s.split('mango', 1)[1]

How to check type of object in Python?

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).

Upgrading Node.js to latest version

just try this on your terminal :

nvm install node --reinstall-packages-from=node

it should do the trick.

later, run node --version to check the version that you have.

Find and replace string values in list

Beside list comprehension, you can try map

>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

Make footer stick to bottom of page correctly

The simplest solution is to use min-height on the <html> tag and position the <footer> with position:absolute;

Demo: jsfiddle and SO snippet:

_x000D_
_x000D_
html {_x000D_
    position: relative;_x000D_
    min-height: 100%;_x000D_
}_x000D_
_x000D_
body {_x000D_
    margin: 0 0 100px;_x000D_
    /* bottom = footer height */_x000D_
    padding: 25px;_x000D_
}_x000D_
_x000D_
footer {_x000D_
    background-color: orange;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    bottom: 0;_x000D_
    height: 100px;_x000D_
    width: 100%;_x000D_
    overflow: hidden;_x000D_
}
_x000D_
<article>_x000D_
    <!-- or <div class="container">, etc. -->_x000D_
    <h1>James Dean CSS Sticky Footer</h1>_x000D_
    <p>Blah blah blah blah</p>_x000D_
    <p>More blah blah blah</p>_x000D_
</article>_x000D_
<footer>_x000D_
    <h1>Footer Content</h1>_x000D_
</footer>
_x000D_
_x000D_
_x000D_

How do I split a string in Rust?

There's also split_whitespace()

fn main() {
    let words: Vec<&str> = "   foo   bar\t\nbaz   ".split_whitespace().collect();
    println!("{:?}", words);
    // ["foo", "bar", "baz"] 
}

Easiest way to ignore blank lines when reading a file in Python

If you want you can just put what you had in a list comprehension:

names_list = [line for line in open("names.txt", "r").read().splitlines() if line]

or

all_lines = open("names.txt", "r").read().splitlines()
names_list = [name for name in all_lines if name]

splitlines() has already removed the line endings.

I don't think those are as clear as just looping explicitly though:

names_list = []
with open('names.txt', 'r') as _:
    for line in _:
        line = line.strip()
        if line:
            names_list.append(line)

Edit:

Although, filter looks quite readable and concise:

names_list = filter(None, open("names.txt", "r").read().splitlines())

How to parse XML using vba

This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.

You can find more on MSXML2.DOMDocument at the following sites:

Set the maximum character length of a UITextField in Swift

Simply just check with the number of characters in the string

  1. Add a delegate to view controller ans asign delegate
    class YorsClassName : UITextFieldDelegate {

    }
  1. check the number of chars allowed for textfield
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text?.count == 1 {
        return false
    }
    return true
}

Note: Here I checked for only char allowed in textField

Cannot perform runtime binding on a null reference, But it is NOT a null reference

This exception is also thrown when a non-existent property is being updated dynamically, using reflection.

If one is using reflection to dynamically update property values, it's worth checking to make sure the passed PropertyName is identical to the actual property.

In my case, I was attempting to update Employee.firstName, but the property was actually Employee.FirstName.

Worth keeping in mind. :)

SQL WITH clause example

The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.

Syntax For The SQL WITH Clause

The following is the syntax of the SQL WITH clause when using a single sub-query alias.

WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]

When using multiple sub-query aliases, the syntax is as follows.

WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]

In the syntax documentation above, the occurrences of alias_name is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.

For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx

UINavigationBar custom back button without title

You don't have access to the navigation backButtonItem with the way you want, you need to create your own back button like below:

- (void)loadView
{
    [super loadView];
    UIButton *backButton = [[UIButton alloc] initWithFrame: CGRectMake(0, 0, 44.0f, 30.0f)];
    [backButton setImage:[UIImage imageNamed:@"back.png"]  forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(popVC) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
}

And off course:

- (void) popVC{
  [self.navigationController popViewControllerAnimated:YES];
}

Limit characters displayed in span

You can do this with jQuery :

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  _x000D_
  $('.claimedRight').each(function (f) {_x000D_
_x000D_
      var newstr = $(this).text().substring(0,20);_x000D_
      $(this).text(newstr);_x000D_
_x000D_
    });_x000D_
})
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <title></title>_x000D_
    <script         src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
    <span class="claimedRight" maxlength="20">Hello this is the first test string. _x000D_
    </span><br>_x000D_
    <span class="claimedRight" maxlength="20">Hello this is the second test string. _x000D_
    </span>_x000D_
    _x000D_
    _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to create an HTML button that acts like a link?

If it's the visual appearance of a button you're looking for in a basic HTML anchor tag then you can use the Twitter Bootstrap framework to format any of the following common HTML type links/buttons to appear as a button. Please note the visual differences between version 2, 3 or 4 of the framework:

<a class="btn" href="">Link</a>
<button class="btn" type="submit">Button</button>
<input class="btn" type="button" value="Input">
<input class="btn" type="submit" value="Submit">

Bootstrap (v4) sample appearance:

Sample output of Boostrap v4 buttons

Bootstrap (v3) sample appearance:

Sample output of Boostrap v3 buttons

Bootstrap (v2) sample appearance:

Sample output of Boostrap v2 buttons

Convert string to date in bash

date only work with GNU date (usually comes with Linux)

for OS X, two choices:

  1. change command (verified)

    #!/bin/sh
    #DATE=20090801204150
    #date -jf "%Y%m%d%H%M%S" $DATE "+date \"%A,%_d %B %Y %H:%M:%S\""
    date "Saturday, 1 August 2009 20:41:50"
    

    http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html

  2. Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html

Python: Continuing to next iteration in outer loop

I just did something like this. My solution for this was to replace the interior for loop with a list comprehension.

for ii in range(200):
    done = any([op(ii, jj) for jj in range(200, 400)])
    ...block0...
    if done:
        continue
    ...block1...

where op is some boolean operator acting on a combination of ii and jj. In my case, if any of the operations returned true, I was done.

This is really not that different from breaking the code out into a function, but I thought that using the "any" operator to do a logical OR on a list of booleans and doing the logic all in one line was interesting. It also avoids the function call.

Catching an exception while using a Python 'with' statement

Catching an exception while using a Python 'with' statement

The with statement has been available without the __future__ import since Python 2.6. You can get it as early as Python 2.5 (but at this point it's time to upgrade!) with:

from __future__ import with_statement

Here's the closest thing to correct that you have. You're almost there, but with doesn't have an except clause:

with open("a.txt") as f: 
    print(f.readlines())
except:                    # <- with doesn't have an except clause.
    print('oops')

A context manager's __exit__ method, if it returns False will reraise the error when it finishes. If it returns True, it will suppress it. The open builtin's __exit__ doesn't return True, so you just need to nest it in a try, except block:

try:
    with open("a.txt") as f:
        print(f.readlines())
except Exception as error: 
    print('oops')

And standard boilerplate: don't use a bare except: which catches BaseException and every other possible exception and warning. Be at least as specific as Exception, and for this error, perhaps catch IOError. Only catch errors you're prepared to handle.

So in this case, you'd do:

>>> try:
...     with open("a.txt") as f:
...         print(f.readlines())
... except IOError as error: 
...     print('oops')
... 
oops

How do include paths work in Visual Studio?

@RichieHindle solution is now deprecated as of Visual Studio 2012. As the VS studio prompt now states:

VC++ Directories are now available as a user property sheet that is added by default to all projects.

To set an include path you now must right-click a project and go to:

Properties/VC++ Directories/General/Include Directories

Screenshot: enter image description here

Pure CSS scroll animation

Use anchor links and the scroll-behavior property (MDN reference) for the scrolling container:

scroll-behavior: smooth;

Browser support: Firefox 36+, Chrome 61+ (therefore also Edge 79+) and Opera 48+.

Intenet Explorer, non-Chromium Edge and (so far) Safari do not support scroll-behavior and simply "jump" to the link target.

Example usage:

<head>
  <style type="text/css">
    html {
      scroll-behavior: smooth;
    }
  </style>
</head>
<body id="body">
  <a href="#foo">Go to foo!</a>

  <!-- Some content -->

  <div id="foo">That's foo.</div>
  <a href="#body">Back to top</a>
</body>

Here's a Fiddle.

And here's also a Fiddle with both horizontal and vertical scrolling.

bash: pip: command not found

(Context: My OS is Amazon linux using AWS. It seems similar to RedHat but it's stripped down a bit, it seems.)

Exit the shell, then open a new shell. The pip command now works.

That's what solved the problem at this location.

You might want to know as well: The pip commands to install software then needed to be written like this example (jupyter for example) to work correctly on my system:

pip install jupyter --user

Specifically, note the lack of sudo, and the presence of --user

Would be real nice if pip docs had said anything about all this, but that would take typing in more characters I guess.

Is there a way to detect if a browser window is not currently active?

var visibilityChange = (function (window) {
    var inView = false;
    return function (fn) {
        window.onfocus = window.onblur = window.onpageshow = window.onpagehide = function (e) {
            if ({focus:1, pageshow:1}[e.type]) {
                if (inView) return;
                fn("visible");
                inView = true;
            } else if (inView) {
                fn("hidden");
                inView = false;
            }
        };
    };
}(this));

visibilityChange(function (state) {
    console.log(state);
});

http://jsfiddle.net/ARTsinn/JTxQY/

How to get correct timestamp in C#

Your mistake is using new DateTime(), which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:

String timeStamp = GetTimestamp(new DateTime());

to this:

String timeStamp = GetTimestamp(DateTime.Now);

How do I check (at runtime) if one class is a subclass of another?

You can use the builtin issubclass. But type checking is usually seen as unneccessary because you can use duck-typing.

No connection could be made because the target machine actively refused it 127.0.0.1:3446

I had a similar problem rejecting localhost and 127.0.0.1. cmd(admin) netstat -anb found the port running on 169.254.80.80 (dont know were that ip came from because my network ip was 10.0.0.5. after putting in this IP it worked. This Gives correct IP:

IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine(ipAddress.ToString());

Count table rows

We have another way to find out the number of rows in a table without running a select query on that table.

Every MySQL instance has information_schema database. If you run the following query, it will give complete details about the table including the approximate number of rows in that table.

select * from information_schema.TABLES where table_name = 'table_name'\G

Google maps API V3 - multiple markers on exact same spot

This is more of a stopgap 'quick and dirty' solution similar to the one Matthew Fox suggests, this time using JavaScript.

In JavaScript you can just offset the lat and long of all of your locations by adding a small random offset to both e.g.

myLocation[i].Latitude+ = (Math.random() / 25000)

(I found that dividing by 25000 gives enough separation but doesn't move the marker significantly from the exact location e.g. a specific address)

This makes a reasonably good job of offsetting them from one another, but only after you've zoomed in closely. When zoomed out, it still won't be clear that there are multiple options for the location.

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

How to annotate MYSQL autoincrement field with JPA annotations

same as pascal answered, just if you need to use .AUTO for some reason you just need to add in your application properties:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto = update

No assembly found containing an OwinStartupAttribute Error

Check if you have the Startup class created in your project. This is an example:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof({project_name}.Startup))]

namespace AuctionPortal
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Convert python datetime to epoch with strftime

import time
from datetime import datetime
now = datetime.now()

time.mktime(now.timetuple())

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

C++11 thread-safe queue

According to the standard condition_variables are allowed to wakeup spuriously, even if the event hasn't occured. In case of a spurious wakeup it will return cv_status::no_timeout (since it woke up instead of timing out), even though it hasn't been notified. The correct solution for this is of course to check if the wakeup was actually legit before proceding.

The details are specified in the standard §30.5.1 [thread.condition.condvar]:

—The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) speci?ed by abs_time, or spuriously.

...

Returns: cv_status::timeout if the absolute timeout (30.2.4) speci?edby abs_time expired, other-ise cv_status::no_timeout.

How To Use DateTimePicker In WPF?

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

Bootstrap control with multiple "data-toggle"

Just for complement @Roman Holzner answer...

In my case, I have a button that shows the tooltip and it should remain disabled until furthermore actions. Using his approach, the modal works even if the button is disabled, because its call is outside the button - I'm in a Laravel blade file, just to be clear :)

<span data-toggle="modal" data-target="#confirm-delete" data-href="{{ $e->id }}">
    <button name="delete" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Excluir Entrada" disabled>
        <i class="fa fa-trash fa-fw"></i>
    </button>
</span>

So if you want to show the modal only when the button is active, you should change the order of the tags:

<span data-toggle="tooltip" data-placement="bottom" title="Excluir Entrada" disabled>
    <button name="delete" class="btn btn-default" data-href="{{ $e->id }}" data-toggle="modal" data-target="#confirm-delete" disabled>
        <i class="fa fa-trash fa-fw"></i>
    </button>
</span>

If you want to test it out, change the attribute with a JQuery code:

$('button[name=delete]').attr('disabled', false);

How do I set the request timeout for one controller action in an asp.net mvc application

<location path="ControllerName/ActionName">
    <system.web>
        <httpRuntime executionTimeout="1000"/>
    </system.web>
</location>

Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.

Create a pointer to two-dimensional array

You can always avoid fiddling around with the compiler by declaring the array as linear and doing the (row,col) to array index calculation by yourself.

static uint8_t l_matrix[200];

void test(int row, int col, uint8_t val)

{

   uint8_t* matrix_ptr = l_matrix;
   matrix_ptr [col+y*row] = val; // to assign a value

}

this is what the compiler would have done anyway.

Change auto increment starting number?

Procedure to auto fix AUTO_INCREMENT value of table

DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(64))
BEGIN
    DECLARE _max_stmt VARCHAR(1024);
    DECLARE _stmt VARCHAR(1024);    
    SET @inc := 0;

    SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(`id`), 0) + 1 INTO @inc FROM ', _table);
    PREPARE _max_stmt FROM @MAX_SQL;
    EXECUTE _max_stmt;
    DEALLOCATE PREPARE _max_stmt;

    SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT =  ', @inc);
    PREPARE _stmt FROM @SQL;
    EXECUTE _stmt;
    DEALLOCATE PREPARE _stmt;
END//
DELIMITER ;

CALL update_auto_increment('your_table_name')

bootstrap 3 tabs not working properly

Make sure your jquery is inserted BEFORE bootstrap js file:

<script src="jquery.min.js" type="text/javascript"></script>
<link href="bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script src="bootstrap.min.js" type="text/javascript"></script>

What is a PDB file?

I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.

Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace string. I included the PDB file in the executable folder and now all is fine.

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

use the "onmouseup" property with each option element. it's verbose, but should work. also, depending on what your function is actually doing, you could arrange things a little differently, assuming the number is important in the handler:

<select>
<option onmouseup="handler()" value="1">1</option>  //get selected element in handler
<option onmouseup="handler(2)" value="2">2</option>  //explicitly send the value as argument
<option onmouseup="handler(this.value)" value="3">3</option> //same as above, but using the element's value property and allowing for dynamic option value. you could also send "this.innerHTML" or "this.textContent" to the handler, making option value unnecessary
</select>

How to fix "Headers already sent" error in PHP

Sometimes when the dev process has both WIN work stations and LINUX systems (hosting) and in the code you do not see any output before the related line, it could be the formatting of the file and the lack of Unix LF (linefeed) line ending.

What we usually do in order to quickly fix this, is rename the file and on the LINUX system create a new file instead of the renamed one, and then copy the content into that. Many times this solve the issue as some of the files that were created in WIN once moved to the hosting cause this issue.

This fix is an easy fix for sites we manage by FTP and sometimes can save our new team members some time.

VBoxManage: error: Failed to create the host-only adapter

For macOS Mojave, this solution worked:

sudo "/Library/Application Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh" restart

Download single files from GitHub

This method works for Windows as I have never used MAC so I don't know what are the alternate keys in MAC for the keys which I'm going to mention below.

Let's talk about the CSV files. IF you want to download the CSV file:

  1. Go to that particular dataset that you want to download and click on it.
  2. You will see "Raw" button on the top right side of the dataset.
  3. Press "Alt" and then left click the "Raw" button.
  4. The whole CSV will download in your system.

Remeber, you have to press Alt and left click simultaneously. Just clicking the "Raw" button will open up the CSV in the browser.

I hope that helps.

AngularJS: How to clear query parameters in the URL?

For Angular >2 , You can pass null to all the params you want to clear

this.router.navigate(['/yourRoute'], {queryParams:{params1: null, param2: null}})

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

I was tried the below query it's works for me exactly

 with cte as(

   select ROW_NUMBER() over (order by repairid) as'RN', [RepairProductId] from [Ws_RepairList]
  )
  update CTE set [RepairProductId]= ISNULL([RepairProductId]+convert(nvarchar(10),RN),0) from cte

How to wait till the response comes from the $http request, in angularjs?

You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)

An example implementation would be like:

myApp.factory('myService', function($http) {

    var getData = function() {

        // Angular $http() and then() both return promises themselves 
        return $http({method:"GET", url:"/my/url"}).then(function(result){

            // What we return here is the data that will be accessible 
            // to us after the promise resolves
            return result.data;
        });
    };


    return { getData: getData };
});


function myFunction($scope, myService) {
    var myDataPromise = myService.getData();
    myDataPromise.then(function(result) {  

       // this is only run after getData() resolves
       $scope.data = result;
       console.log("data.name"+$scope.data.name);
    });
}

Edit: Regarding Sujoys comment that What do I need to do so that myFuction() call won't return till .then() function finishes execution.

function myFunction($scope, myService) { 
    var myDataPromise = myService.getData(); 
    myDataPromise.then(function(result) { 
         $scope.data = result; 
         console.log("data.name"+$scope.data.name); 
    }); 
    console.log("This will get printed before data.name inside then. And I don't want that."); 
 }

Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.

With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)

How to convert from []byte to int in Go Programming

var bs []byte
value, _ := strconv.ParseInt(string(bs), 10, 64)

How to set Spinner Default by its Value instead of Position?

Finally, i solved the problem by using following way, in which the position of the spinner can be get by its string

private int getPostiton(String locationid,Cursor cursor)
{
    int i;
    cursor.moveToFirst(); 
    for(i=0;i< cursor.getCount()-1;i++)
    {  

        String locationVal = cursor.getString(cursor.getColumnIndex(RoadMoveDataBase.LT_LOCATION));  
        if(locationVal.equals(locationid))
        { 
            position = i+1;  
            break;
        }
        else
        {
            position = 0;
        }
        cursor.moveToNext();  
    } 

Calling the method

    Spinner location2 = (Spinner)findViewById(R.id.spinner1);
    int location2id = getPostiton(cursor.getString(3),cursor);
    location2.setSelection(location2id);

I hope it will help for some one..

How do I add more members to my ENUM-type column in MySQL?

ALTER TABLE
    `table_name`
MODIFY COLUMN
    `column_name2` enum(
        'existing_value1',
        'existing_value2',
        'new_value1',
        'new_value2'
    )
NOT NULL AFTER `column_name1`;

How to determine the current language of a wordpress page when using polylang?

Simple:

if(pll_current_language() == 'en'){
   //do your work here
}

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Single controller with multiple GET methods in ASP.NET Web API

None of the above examples worked for my personal needs. The below is what I ended up doing.

 public class ContainsConstraint : IHttpRouteConstraint
{       
    public string[] array { get; set; }
    public bool match { get; set; }

    /// <summary>
    /// Check if param contains any of values listed in array.
    /// </summary>
    /// <param name="param">The param to test.</param>
    /// <param name="array">The items to compare against.</param>
    /// <param name="match">Whether we are matching or NOT matching.</param>
    public ContainsConstraint(string[] array, bool match)
    {

        this.array = array;
        this.match = match;
    }

    public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
    {
        if (values == null) // shouldn't ever hit this.                   
            return true;

        if (!values.ContainsKey(parameterName)) // make sure the parameter is there.
            return true;

        if (string.IsNullOrEmpty(values[parameterName].ToString())) // if the param key is empty in this case "action" add the method so it doesn't hit other methods like "GetStatus"
            values[parameterName] = request.Method.ToString();

        bool contains = array.Contains(values[parameterName]); // this is an extension but all we are doing here is check if string array contains value you can create exten like this or use LINQ or whatever u like.

        if (contains == match) // checking if we want it to match or we don't want it to match
            return true;
        return false;             

    }

To use the above in your route use:

config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { action = RouteParameter.Optional, id = RouteParameter.Optional}, new { action = new ContainsConstraint( new string[] { "GET", "PUT", "DELETE", "POST" }, true) });

What happens is the constraint kind of fakes in the method so that this route will only match the default GET, POST, PUT and DELETE methods. The "true" there says we want to check for a match of the items in array. If it were false you'd be saying exclude those in the strYou can then use routes above this default method like:

config.Routes.MapHttpRoute("GetStatus", "{controller}/status/{status}", new { action = "GetStatus" });

In the above it is essentially looking for the following URL => http://www.domain.com/Account/Status/Active or something like that.

Beyond the above I'm not sure I'd get too crazy. At the end of the day it should be per resource. But I do see a need to map friendly urls for various reasons. I'm feeling pretty certain as Web Api evolves there will be some sort of provision. If time I'll build a more permanent solution and post.

Netbeans - Error: Could not find or load main class

try this it work out for me perfectly go to project and right click on your java file at the right corner, go to properties, go to run, go to browse, and then select Main class. now you can run your program again.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

You probably want to have a list of supported encodings. For each file, try each encoding in turn, maybe starting with UTF-8. Every time you catch the MalformedInputException, try the next encoding.

First Heroku deploy failed `error code=H10`

I was deploying python Django framework when I got this error because I forget to put my app name web: gunicorn plaindjango.wsgi:application --log-file - instead of plaindjango

Distribution certificate / private key not installed

EDIT: I thought that the other computer is dead so I'm fixing my answer:

You should export the certificate from the first computer with it's private key and import it in the new computer.

I prefer the iCloud way, backup to iCloud and get it in the new computer.

If you can't do it with some reason, you can revoke the certificate in Apple developers site, then let Xcode to create a new one for you, it'll also create a fresh new private key and store it in your Keychain, just be sure to back it up in your preferred way

Conditional formatting using AND() function

COLUMN() and ROW() won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.

For instance, if you want to use this conditional formating on a range begining on cell A1, you can try:

`COLUMN(A1)` and `ROW(A1)`

Excel will automatically adapt the conditional formating to the current cell.

Margin on child element moves parent element

The margin of the elements contained within .child are collapsing.

<html>
<style type="text/css" media="screen">
    #parent {background:#dadada;}
    #child {background:red; margin-top:17px;}
</style>
<body>
<div id="parent">

    <p>&amp;</p>

    <div id="child">
        <p>&amp;</p>    
    </div>

</div>
</body>
</html>

In this example, p is receiving a margin from the browser default styles. Browser default font-size is typically 16px. By having a margin-top of more than 16px on #child you start to notice it's position move.

How to embed HTML into IPython output?

Related: While constructing a class, def _repr_html_(self): ... can be used to create a custom HTML representation of its instances:

class Foo:
    def _repr_html_(self):
        return "Hello <b>World</b>!"

o = Foo()
o

will render as:

Hello World!

For more info refer to IPython's docs.

An advanced example:

from html import escape # Python 3 only :-)

class Todo:
    def __init__(self):
        self.items = []

    def add(self, text, completed):
        self.items.append({'text': text, 'completed': completed})

    def _repr_html_(self):
        return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
            "?" if item['completed'] else "?",
            escape(item['text'])
        ) for item in self.items))

my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)

my_todo

Will render:

  1. ? Buy milk
  2. ? Do homework
  3. ? Play video games

Can VS Code run on Android?

There is a browser-based implementation of VSC that allows you to run it on a browser on your Android (or any other) device. Check it out here:

https://stackblitz.com/

Reactjs - Form input validation

I've taken your code and adapted it with library react-form-with-constraints: https://codepen.io/tkrotoff/pen/LLraZp

const {
  FormWithConstraints,
  FieldFeedbacks,
  FieldFeedback
} = ReactFormWithConstraints;

class Form extends React.Component {
  handleChange = e => {
    this.form.validateFields(e.target);
  }

  contactSubmit = e => {
    e.preventDefault();

    this.form.validateFields();

    if (!this.form.isValid()) {
      console.log('form is invalid: do not submit');
    } else {
      console.log('form is valid: submit');
    }
  }

  render() {
    return (
      <FormWithConstraints
        ref={form => this.form = form}
        onSubmit={this.contactSubmit}
        noValidate>

        <div className="col-md-6">
          <input name="name" size="30" placeholder="Name"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="name">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input type="email" name="email" size="30" placeholder="Email"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="email">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="phone" size="30" placeholder="Phone"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="phone">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="address" size="30" placeholder="Address"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="address">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </div>

        <div className="col-md-6">
          <textarea name="comments" cols="40" rows="20" placeholder="Message"
                    required minLength={5} maxLength={50}
                    onChange={this.handleChange}
                    className="form-control" />
          <FieldFeedbacks for="comments">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </div>

        <div className="col-md-12">
          <button className="btn btn-lg btn-primary">Send Message</button>
        </div>
      </FormWithConstraints>
    );
  }
}

Screenshot:

form validation screenshot

This is a quick hack. For a proper demo, check https://github.com/tkrotoff/react-form-with-constraints#examples

Get just the filename from a path in a Bash script

$ source_file_filename_no_ext=${source_file%.*}
$ echo ${source_file_filename_no_ext##*/}

Does List<T> guarantee insertion order?

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

According to MSDN:

...List "Represents a strongly typed list of objects that can be accessed by index."

The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.

You might be getting odd results from your code if you're moving the item later in the list, as your Remove() will move all of the other items down one place before the call to Insert().

Can you boil your code down to something small enough to post?

Fixing a systemd service 203/EXEC failure (no such file or directory)

To simplify, make sure to add a hash bang to the top of your ExecStart script, i.e.

#!/bin/bash

python -u alwayson.py    

How to check if an element does NOT have a specific class?

sdleihssirhc's answer is of course the correct one for the case in the question, but just as a reference if you need to select elements that don't have a certain class, you can use the not selector:

// select all divs that don't have class test
$( 'div' ).not( ".test" );
$( 'div:not(.test)' );  // <-- alternative 

Moment.js - how do I get the number of years since a date, not rounded up?

This method is easy and powerful.

Value is a date and "DD-MM-YYYY" is the mask of the date.

moment().diff(moment(value, "DD-MM-YYYY"), 'years');

Java maximum memory on Windows XP

First, using a page-file when you have 4 GB of RAM is useless. Windows can't access more than 4GB (actually, less because of memory holes) so the page file is not used.

Second, the address space is split in 2, half for kernel, half for user mode. If you need more RAM for your applications use the /3GB option in boot.ini (make sure java.exe is marked as "large address aware" (google for more info).

Third, I think you can't allocate the full 2 GB of address space because java wastes some memory internally (for threads, JIT compiler, VM initialization, etc). Use the /3GB switch for more.

Received an invalid column length from the bcp client for colid 6

I know this post is old but I ran into this same issue and finally figured out a solution to determine which column was causing the problem and report it back as needed. I determined that colid returned in the SqlException is not zero based so you need to subtract 1 from it to get the value. After that it is used as the index of the _sortedColumnMappings ArrayList of the SqlBulkCopy instance not the index of the column mappings that were added to the SqlBulkCopy instance. One thing to note is that SqlBulkCopy will stop on the first error received so this may not be the only issue but at least helps to figure it out.

try
{
    bulkCopy.WriteToServer(importTable);
    sqlTran.Commit();
}    
catch (SqlException ex)
{
    if (ex.Message.Contains("Received an invalid column length from the bcp client for colid"))
    {
        string pattern = @"\d+";
        Match match = Regex.Match(ex.Message.ToString(), pattern);
        var index = Convert.ToInt32(match.Value) -1;

        FieldInfo fi = typeof(SqlBulkCopy).GetField("_sortedColumnMappings", BindingFlags.NonPublic | BindingFlags.Instance);
        var sortedColumns = fi.GetValue(bulkCopy);
        var items = (Object[])sortedColumns.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sortedColumns);

        FieldInfo itemdata = items[index].GetType().GetField("_metadata", BindingFlags.NonPublic | BindingFlags.Instance);
        var metadata = itemdata.GetValue(items[index]);

        var column = metadata.GetType().GetField("column", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
        var length = metadata.GetType().GetField("length", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
        throw new DataFormatException(String.Format("Column: {0} contains data with a length greater than: {1}", column, length));
    }

    throw;
}

How can I run multiple npm scripts in parallel?

Use a package called concurrently.

npm i concurrently --save-dev

Then setup your npm run dev task as so:

"dev": "concurrently --kill-others \"npm run start-watch\" \"npm run wp-server\""

Using mysql concat() in WHERE clause?

What you have should work but can be reduced to:

select * from table where concat_ws(' ',first_name,last_name) 
like '%$search_term%';

Can you provide an example name and search term where this doesn't work?

CSS position absolute full width problem

I have similar situation. In my case, it doesn't have a parent with position:relative. Just paste my solution here for those that might need.

position: fixed;
left: 0;
right: 0;

c# - approach for saving user settings in a WPF application?

  1. In all the places I've worked, database has been mandatory because of application support. As Adam said, the user might not be at his desk or the machine might be off, or you might want to quickly change someone's configuration or assign a new-joiner a default (or team member's) config.

  2. If the settings are likely to grow as new versions of the application are released, you might want to store the data as blobs which can then be deserialized by the application. This is especially useful if you use something like Prism which discovers modules, as you can't know what settings a module will return. The blobs could be keyed by username/machine composite key. That way you can have different settings for every machine.

  3. I've not used the in-built Settings class much so I'll abstain from commenting. :)

Get pixel's RGB using PIL

Not PIL, but imageio.imread might still be interesting:

import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)

gives

(480, 640, 3)

so it is (height, width, channels). So the pixel at position (x, y) is

color = tuple(im[y][x])
r, g, b = color

Outdated

scipy.misc.imread is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

While doing production config i got the permission issue.I tried below solution to resolve the issue.

Error Message

ubuntu@node1:~$ docker run hello-world
docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.38/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.

Solution: permissions of the socket indicated in the error message, /var/run/docker.sock:

ubuntu@ip-172-31-21-106:/var/run$ ls -lrth docker.sock
srw-rw---- 1 root root 0 Oct 17 11:08 docker.sock
ubuntu@ip-172-31-21-106:/var/run$ sudo chmod 666 /var/run/docker.sock
ubuntu@ip-172-31-21-106:/var/run$ ls -lrth docker.sock
srw-rw-rw- 1 root root 0 Oct 17 11:08 docker.sock

After changes permission for docket.sock then execute below command to check permissions.

ubuntu@ip-172-31-21-106:/var/run$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
1b930d010525: Pull complete
Digest: sha256:c3b4ada4687bbaa170745b3e4dd8ac3f194ca95b2d0518b417fb47e5879d9b5f
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

How to install OpenJDK 11 on Windows?

Use the Chocolatey packet manager. It's a command-line tool similar to npm. Once you have installed it, use

choco install openjdk

in an elevated command prompt to install OpenJDK.

To update an installed version to the latest version, type

choco upgrade openjdk

Pretty simple to use and especially helpful to upgrade to the latest version. No manual fiddling with path environment variables.

cannot find zip-align when publishing app

With the SDK update to 20, version 20 of the build and platform tools and 23 of the sdk tolls, Google has moved a lot of things.

Gradle (if you are using Android Studio) however has not yet been updated to reflect those changes, as stated in other Answers copying the zipalign binary to /sdk/tools/ should do the trick for now.

UPDATE: since Android Studio 0.8.1 got released the issue seems fixed now…
you only need to update your build.gradle and it should work fine again

compileSdkVersion 20

buildToolsVersion "20.0.0"

targetSdkVersion 20

and if you use any compat or support library

compile 'com.android.support:appcompat-v7:20.+'

compile 'com.android.support:support-v4:20.+'

window.open(url, '_blank'); not working on iMac/Safari

The correct syntax is window.open(URL,WindowTitle,'_blank') All the arguments in the open must be strings. They are not mandatory, and window can be dropped. So just newWin=open() works as well, if you plan to populate newWin.document by yourself. BUT you MUST use all the three arguments, and the third one set to '_blank' for opening a new true window and not a tab.

Bootstrap 3 - jumbotron background image effect

I think what you are looking for is to keep the background image fixed and just move the content on scroll. For that you have to simply use the following css property :

background-attachment: fixed;

Making an iframe responsive

Getting Started

Due to browser security constraints, you will have to include the Javascript file both in the “parent” page, as well as in the page being embedded through an iframe (“child”).

In the current version, the parent page must include the latest version of jQuery. There is no dependency on jQuery for the child page functionality. In future versions, we would like to remove the dependency on jQuery for the parent as well.

Note: the “xdomain” parameter in the makeResponsive() function call is optional.

Code Sample <!-- Activate responsiveness in the "child" page --><script src="/js/jquery.responsiveiframe.js"></script><script> var ri = responsiveIframe(); ri.allowResponsiveEmbedding();</script> <!-- Corresponding code in the "parent" page --><script src="/js/jquery.js"></script><script src="/js/jquery.responsiveiframe.js"></script><script> ;(function($){ $(function(){ $('#myIframeID').responsiveIframe({ xdomain: '*'}); }); })(jQuery);</script>

How does one set up the Visual Studio Code compiler/debugger to GCC?

For Windows:

  1. Install MinGW or Dev C++
  2. Open Environment Variables
  3. In System Variable select Path -> Edit -> New
  4. Copy this C:\Program Files (x86)\Dev-Cpp\MinGW64\bin to the New window. (If you have MinGW installed copy its /bin path).
  5. To check if you have added it successfully: Open CMD -> Type "gcc" and it should return: gcc: fatal error: no input files compilation terminated.
  6. Install C/C++ for Visual Studio Code && C/C++ Compile Run || Code Runner
  7. If you installed only C/C++ Compile Run extension you can compile your program using F6/F7
  8. If you installed the second extension you can compile your program using the button in the top bar.

Screenshot: Hello World compiled in VS Code

Choosing the default value of an Enum type without having to change values

If you define the Default enum as the enum with the smallest value you can use this:

public enum MyEnum { His = -1, Hers = -2, Mine = -4, Theirs = -3 }

var firstEnum = ((MyEnum[])Enum.GetValues(typeof(MyEnum)))[0];

firstEnum == Mine.

This doesn't assume that the enum has a zero value.

Global keyboard capture in C# application

Stephen Toub wrote a great article on implementing global keyboard hooks in C#:

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class InterceptKeys
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main()
    {
        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            Console.WriteLine((Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
        LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);
}

Global variables in Javascript across multiple files

You can make a json object like:

globalVariable={example_attribute:"SomeValue"}; 

in fileA.js

And access it from fileB.js like: globalVariable.example_attribute

What is a postback?

Postback is essentially when a form is submitted to the same page or script (.php .asp etc) as you are currently on to proccesses the data rather than sending you to a new page.

An example could be a page on a forum (viewpage.php), where you submit a comment and it is submitted to the same page (viewpage.php) and you would then see it with the new content added.

See: http://en.wikipedia.org/wiki/Postback

Set language for syntax highlighting in Visual Studio Code

Another reason why people might struggle to get Syntax Highlighting working is because they don't have the appropriate syntax package installed. While some default syntax packages come pre-installed (like Swift, C, JS, CSS), others may not be available.

To solve this you can Cmd + Shift + P ? "install Extensions" and look for the language you want to add, say "Scala".

enter image description here

Find the suitable Syntax package, install it and reload. This will pick up the correct syntax for your files with the predefined extension, i.e. .scala in this case.

On top of that you might want VS Code to treat all files with certain custom extensions as your preferred language of choice. Let's say you want to highlight all *.es files as JavaScript, then just open "User Settings" (Cmd + Shift + P ? "User Settings") and configure your custom files association like so:

  "files.associations": {
    "*.es": "javascript"
  },

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

Although there's CSS defines a text-wrap property, it's not supported by any major browser, but maybe vastly supported white-space property solves your problem.

Node.js EACCES error when listening on most ports

I had a similar problem that it was denying to run on port 8080, but also any other.

Turns out, it was because the env.local file it read contained comments after the variable names like:

PORT=8080 # The port the server runs at

And it interpreted it like that, trying to use port "8080 # The port the server runs at", which is obviously an invalid port (-1). Removing the comments entirely solved it.

Using Windows 10 and Git Bash by the way.


I know it's not exactly the problem described here, but it might help someone out there. I landed on this question searching for the problem for my answer, so... maybe?

How to create file execute mode permissions in Git on Windows?

There's no need to do this in two commits, you can add the file and mark it executable in a single commit:

C:\Temp\TestRepo>touch foo.sh

C:\Temp\TestRepo>git add foo.sh

C:\Temp\TestRepo>git ls-files --stage
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0       foo.sh

As you note, after adding, the mode is 0644 (ie, not executable). However, we can mark it as executable before committing:

C:\Temp\TestRepo>git update-index --chmod=+x foo.sh

C:\Temp\TestRepo>git ls-files --stage
100755 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0       foo.sh

And now the file is mode 0755 (executable).

C:\Temp\TestRepo>git commit -m"Executable!"
[master (root-commit) 1f7a57a] Executable!
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100755 foo.sh

And now we have a single commit with a single executable file.

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})

For VB.NET this syntax would be accomplished using the dot, ., which in that language is default syntax for all anonymous types:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })

can't start MySql in Mac OS 10.6 Snow Leopard

YOU MUST REINSTALL mySQL after upgrading to Snow Leopard and remove any previous versions as well as previous startup from the preference panel. install 86_64 10.5...I find the others did not work for me.

  1. Download MySQL version Mac OS X 10.5 (x86_64) located at http://dev.mysql.com/downloads/mysql/5.4.html#macosx-dmg
  2. Install startup Item (follow instructions)
  3. Then install the beta version (follow instructions)
  4. If you want the start up in the Preference Panel...install mySQL.prefpane I find that SQL does not run from the terminal unless you start mySQL in the preference panel.

'module' object has no attribute 'DataFrame'

I have faced similar problem, 'int' object has no attribute 'DataFrame',

This was because i have mistakenly used pd as a variable in my code and assigned an integer to it, while using the same pd as my pandas dataframe object by declaring - import pandas as pd.

I realized this, and changed my variable to something else, and fixed the error.

How can I present a file for download from an MVC controller?

To force the download of a PDF file, instead of being handled by the browser's PDF plugin:

public ActionResult DownloadPDF()
{
    return File("~/Content/MyFile.pdf", "application/pdf", "MyRenamedFile.pdf");
}

If you want to let the browser handle by its default behavior (plugin or download), just send two parameters.

public ActionResult DownloadPDF()
{
    return File("~/Content/MyFile.pdf", "application/pdf");
}

You'll need to use the third parameter to specify a name for the file on the browser dialog.

UPDATE: Charlino is right, when passing the third parameter (download filename) Content-Disposition: attachment; gets added to the Http Response Header. My solution was to send application\force-download as the mime-type, but this generates a problem with the filename of the download so the third parameter is required to send a good filename, therefore eliminating the need to force a download.

Turn off warnings and errors on PHP and MySQL

Always show errors on a testing server. Never show errors on a production server.

Write a script to determine whether the page is on a local, testing, or live server, and set $state to "local", "testing", or "live". Then:

if( $state == "local" || $state == "testing" )
{
    ini_set( "display_errors", "1" );
    error_reporting( E_ALL & ~E_NOTICE );
}
else
{
    error_reporting( 0 );
}

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

After following @Neelam Verma's answer or @dawid's answer, which has the same end result as @Neelam Verma's answer, difference being that @dawid's answer starts with the drag and drop of the file into the Xcode project and @Neelam Verma's answer starts with a file already a part of the Xcode project, I still could not get NSBundle.mainBundle().pathForResource("file-title", ofType:"type") to find my video file.

I thought maybe because I had my file was in a Group nested in the Xcode project that this was the cause, so I moved the video file to the root of my Xcode project, still no luck, this was my code:

 guard let path = NSBundle.mainBundle().pathForResource("testVid1", ofType:"mp4") else {
        print("Invalid video path")
        return
    }

Originally, this was the name of my file: testVid1.MP4, renaming the video file to testVid1.mp4 fixed my issue, so, at least the ofType string argument is case sensitive.

Create a .txt file if doesn't exist, and if it does append a new line

File.AppendAllText adds a string to a file. It also creates a text file if the file does not exist. If you don't need to read content, it's very efficient. The use case is logging.

File.AppendAllText("C:\\log.txt", "hello world\n");

Java string to date conversion

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date;
try {
    date = dateFormat.parse("2013-12-4");
    System.out.println(date.toString()); // Wed Dec 04 00:00:00 CST 2013

    String output = dateFormat.format(date);
    System.out.println(output); // 2013-12-04
} 
catch (ParseException e) {
    e.printStackTrace();
}

It works fine for me.

C program to check little vs. big endian

The following will do.

unsigned int x = 1;
printf ("%d", (int) (((char *)&x)[0]));

And setting &x to char * will enable you to access the individual bytes of the integer, and the ordering of bytes will depend on the endianness of the system.

Eclipse Java Missing required source folder: 'src'

In eclipse, you must be careful to create a "source folder" (File->New->Source Folder). This way, it's automatically on your classpath, and, more importantly, Eclipse knows that these are compilable files. It's picky that way.

Android: how to refresh ListView contents?

To those still having problems, I solved it this way:

List<Item> newItems = databaseHandler.getItems();
ListArrayAdapter.clear();
ListArrayAdapter.addAll(newItems);
ListArrayAdapter.notifyDataSetChanged();
databaseHandler.close();

I first cleared the data from the adapter, then added the new collection of items, and only then set notifyDataSetChanged(); This was not clear for me at first, so I wanted to point this out. Take note that without calling notifyDataSetChanged() the view won't be updated.

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

Found the solution after some searching.

You need to add a <meta> tag in your <head> containing name="theme-color", with your HEX code as the content value. For example:

<meta name="theme-color" content="#999999" />

Update:

If the android device has native dark-mode enabled, then this meta tag is ignored.

Chrome for Android does not use the color on devices with native dark-mode enabled.

source: https://caniuse.com/#search=theme-color

Read and write to binary files in C?

Reading and writing binary files is pretty much the same as any other file, the only difference is how you open it:

unsigned char buffer[10];
FILE *ptr;

ptr = fopen("test.bin","rb");  // r for read, b for binary

fread(buffer,sizeof(buffer),1,ptr); // read 10 bytes to our buffer

You said you can read it, but it's not outputting correctly... keep in mind that when you "output" this data, you're not reading ASCII, so it's not like printing a string to the screen:

for(int i = 0; i<10; i++)
    printf("%u ", buffer[i]); // prints a series of bytes

Writing to a file is pretty much the same, with the exception that you're using fwrite() instead of fread():

FILE *write_ptr;

write_ptr = fopen("test.bin","wb");  // w for write, b for binary

fwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer

Since we're talking Linux.. there's an easy way to do a sanity check. Install hexdump on your system (if it's not already on there) and dump your file:

mike@mike-VirtualBox:~/C$ hexdump test.bin
0000000 457f 464c 0102 0001 0000 0000 0000 0000
0000010 0001 003e 0001 0000 0000 0000 0000 0000
...

Now compare that to your output:

mike@mike-VirtualBox:~/C$ ./a.out 
127 69 76 70 2 1 1 0 0 0

hmm, maybe change the printf to a %x to make this a little clearer:

mike@mike-VirtualBox:~/C$ ./a.out 
7F 45 4C 46 2 1 1 0 0 0

Hey, look! The data matches up now*. Awesome, we must be reading the binary file correctly!

*Note the bytes are just swapped on the output but that data is correct, you can adjust for this sort of thing

Count the items from a IEnumerable<T> without iterating?

Alternatively you can do the following:

Tables.ToList<string>().Count;

Centering FontAwesome icons vertically and horizontally

If you are using twitter Bootstrap add the class text-center to your code.

<div class='login-icon'><i class="icon-lock text-center"></i></div>

Is there a RegExp.escape function in JavaScript?

Most of the expressions here solve single specific use cases.

That's okay, but I prefer an "always works" approach.

function regExpEscape(literal_string) {
    return literal_string.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
}

This will "fully escape" a literal string for any of the following uses in regular expressions:

  • Insertion in a regular expression. E.g. new RegExp(regExpEscape(str))
  • Insertion in a character class. E.g. new RegExp('[' + regExpEscape(str) + ']')
  • Insertion in integer count specifier. E.g. new RegExp('x{1,' + regExpEscape(str) + '}')
  • Execution in non-JavaScript regular expression engines.

Special Characters Covered:

  • -: Creates a character range in a character class.
  • [ / ]: Starts / ends a character class.
  • { / }: Starts / ends a numeration specifier.
  • ( / ): Starts / ends a group.
  • * / + / ?: Specifies repetition type.
  • .: Matches any character.
  • \: Escapes characters, and starts entities.
  • ^: Specifies start of matching zone, and negates matching in a character class.
  • $: Specifies end of matching zone.
  • |: Specifies alternation.
  • #: Specifies comment in free spacing mode.
  • \s: Ignored in free spacing mode.
  • ,: Separates values in numeration specifier.
  • /: Starts or ends expression.
  • :: Completes special group types, and part of Perl-style character classes.
  • !: Negates zero-width group.
  • < / =: Part of zero-width group specifications.

Notes:

  • / is not strictly necessary in any flavor of regular expression. However, it protects in case someone (shudder) does eval("/" + pattern + "/");.
  • , ensures that if the string is meant to be an integer in the numerical specifier, it will properly cause a RegExp compiling error instead of silently compiling wrong.
  • #, and \s do not need to be escaped in JavaScript, but do in many other flavors. They are escaped here in case the regular expression will later be passed to another program.

If you also need to future-proof the regular expression against potential additions to the JavaScript regex engine capabilities, I recommend using the more paranoid:

function regExpEscapeFuture(literal_string) {
    return literal_string.replace(/[^A-Za-z0-9_]/g, '\\$&');
}

This function escapes every character except those explicitly guaranteed not be used for syntax in future regular expression flavors.


For the truly sanitation-keen, consider this edge case:

var s = '';
new RegExp('(choice1|choice2|' + regExpEscape(s) + ')');

This should compile fine in JavaScript, but will not in some other flavors. If intending to pass to another flavor, the null case of s === '' should be independently checked, like so:

var s = '';
new RegExp('(choice1|choice2' + (s ? '|' + regExpEscape(s) : '') + ')');

How do I delete a Git branch locally and remotely?

A one-liner command to delete both local, and remote:

D=branch-name; git branch -D $D; git push origin :$D

Or add the alias below to your ~/.gitconfig. Usage: git kill branch-name

[alias]
    kill = "!f(){ git branch -D \"$1\";  git push origin --delete \"$1\"; };f"

How do you monitor network traffic on the iPhone?

A general solution would be to use a linux box (could be in a virtual machine) configured as a transparent proxy to intercept the traffic, and then analyse it using wireshark or tcpdump or whatever you like. Perhaps MacOS can do this also, I haven't tried.

Or if you can run the app in the simulator, you can probably monitor the traffic on your own machine.

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

How to generate .json file with PHP?

Here i have mentioned the simple syntex for create json file and print the array value inside the json file in pretty manner.

$array = array('name' => $name,'id' => $id,'url' => $url);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT));   // here it will print the array pretty
fclose($fp);

Hope it will works for you....

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Does this answer your question?

I have never used reinterpret_cast, and wonder whether running into a case that needs it isn't a smell of bad design. In the code base I work on dynamic_cast is used a lot. The difference with static_cast is that a dynamic_cast does runtime checking which may (safer) or may not (more overhead) be what you want (see msdn).

Using getResources() in non-activity class

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

How do I share variables between different .c files?

The 2nd file needs to know about the existance of your variable. To do this you declare the variable again but use the keyword extern in front of it. This tells the compiler that the variable is available but declared somewhere else, thus prevent instanciating it (again, which would cause clashes when linking). While you can put the extern declaration in the C file itself it's common style to have an accompanying header (i.e. .h) file for each .c file that provides functions or variables to others which hold the extern declaration. This way you avoid copying the extern declaration, especially if it's used in multiple other files. The same applies for functions, though you don't need the keyword extern for them.

That way you would have at least three files: the source file that declares the variable, it's acompanying header that does the extern declaration and the second source file that #includes the header to gain access to the exported variable (or any other symbol exported in the header). Of course you need all source files (or the appropriate object files) when trying to link something like that, as the linker needs to resolve the symbol which is only possible if it actually exists in the files linked.

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

And just to give you yet another option, you can use NOT ISNULL(archived) as your WHERE filter.

batch file Copy files with certain extensions from multiple directories into one directory

Just use the XCOPY command with recursive option

xcopy c:\*.doc k:\mybackup /sy

/s will make it "recursive"

What is an AssertionError? In which case should I throw it from my own code?

I'm really late to party here, but most of the answers seem to be about the whys and whens of using assertions in general, rather than using AssertionError in particular.

assert and throw new AssertionError() are very similar and serve the same conceptual purpose, but there are differences.

  1. throw new AssertionError() will throw the exception regardless of whether assertions are enabled for the jvm (i.e., through the -ea switch).
  2. The compiler knows that throw new AssertionError() will exit the block, so using it will let you avoid certain compiler errors that assert will not.

For example:

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            throw new AssertionError();
        }
        System.out.println("n = " + n);
    }

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            assert false;
        }
        System.out.println("n = " + n);
    }

The first block, above, compiles just fine. The second block does not compile, because the compiler cannot guarantee that n has been initialized by the time the code tries to print it out.

How to read a PEM RSA private key from .NET

The stuff between the

-----BEGIN RSA PRIVATE KEY---- 

and

-----END RSA PRIVATE KEY----- 

is the base64 encoding of a PKCS#8 PrivateKeyInfo (unless it says RSA ENCRYPTED PRIVATE KEY in which case it is a EncryptedPrivateKeyInfo).

It is not that hard to decode manually, but otherwise your best bet is to P/Invoke to CryptImportPKCS8.


Update: The CryptImportPKCS8 function is no longer available for use as of Windows Server 2008 and Windows Vista. Instead, use the PFXImportCertStore function.

Sort a List of objects by multiple fields

Yes, you absolutely can do this. For example:

public class PersonComparator implements Comparator<Person>
{
    public int compare(Person p1, Person p2)
    {
        // Assume no nulls, and simple ordinal comparisons

        // First by campus - stop if this gives a result.
        int campusResult = p1.getCampus().compareTo(p2.getCampus());
        if (campusResult != 0)
        {
            return campusResult;
        }

        // Next by faculty
        int facultyResult = p1.getFaculty().compareTo(p2.getFaculty());
        if (facultyResult != 0)
        {
            return facultyResult;
        }

        // Finally by building
        return p1.getBuilding().compareTo(p2.getBuilding());
    }
}

Basically you're saying, "If I can tell which one comes first just by looking at the campus (before they come from different campuses, and the campus is the most important field) then I'll just return that result. Otherwise, I'll continue on to compare faculties. Again, stop if that's enough to tell them apart. Otherwise, (if the campus and faculty are the same for both people) just use the result of comparing them by building."

How to use mouseover and mouseout in Angular 6

CSS solution works without a glitch!

https://www.w3schools.com/code/tryit.asp?filename=GJ4PCJMVQ4LN https://www.w3schools.com/code/tryit.asp?filename=GJ4PPLCCEBRG

_x000D_
_x000D_
.col-info:hover>.popoverIcon {
    visibility: visible;
  }
}

.popoverIcon {
  visibility: hidden;
}
_x000D_
<div *ngFor="let i of [1,2,3,4]">

  <div class="col-info">
    <span class=" popoverIcon ">Show {{i}}</span>
  </div>

</div>
_x000D_
_x000D_
_x000D_

Difference between two dates in years, months, days in JavaScript

I used this simple code to get difference in Years, Months, days with current date.

var sdt = new Date('1972-11-30');
var difdt = new Date(new Date() - sdt);
alert((difdt.toISOString().slice(0, 4) - 1970) + "Y " + (difdt.getMonth()+1) + "M " + difdt.getDate() + "D");

PostgreSQL JOIN data from 3 tables

Maybe the following is what you are looking for:

SELECT name, pathfilename
  FROM table1
  NATURAL JOIN table2
  NATURAL JOIN table3
  WHERE name = 'John';

invalid command code ., despite escaping periods, using sed

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

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

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

See this.