Programs & Examples On #Exit

Exiting, quitting, or halting refers to the termination of a process or program.

Android: Quit application when press back button

Instead of finish() call super.onBackPressed()

What is the difference between exit and return?

In C, there's not much difference when used in the startup function of the program (which can be main(), wmain(), _tmain() or the default name used by your compiler).

If you return in main(), control goes back to the _start() function in the C library which originally started your program, which then calls exit() anyways. So it really doesn't matter which one you use.

How to exit when back button is pressed?

Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.

If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).

If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.

Automatic exit from Bash shell script on error

To exit the script as soon as one of the commands failed, add this at the beginning:

set -e

This causes the script to exit immediately when some command that is not part of some test (like in a if [ ... ] condition or a && construct) exits with a non-zero exit code.

Is there a method that tells my program to quit?

Please note that the solutions based on sys.exit() or any Exception may not work in a multi-threaded environment.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. (doc)

This answer from Alex Martelli for more details.

How do I exit a while loop in Java?

if you write while(true). its means that loop will not stop in any situation for stop this loop you have to use break statement between while block.


 * @author Ankit Sood Apr 20, 2017
public class Demo {

     * The main method.
     * @param args
     *            the arguments
    public static void main(String[] args) {
        /* Initialize while loop */
        while (true) {
            * You have to declare some condition to stop while loop 

            * In which situation or condition you want to terminate while loop.
            * conditions like: if(condition){break}, if(var==10){break} etc... 

            /* break keyword is for stop while loop */


How do I make a C++ console program exit?

exit(0); // at the end of main function before closing curly braces

Closing Application with Exit button

Don't ever put an Exit button on an Android app. Let the OS decide when to kill your Activity. Learn about the Android Activity lifecycle and implement any necessary callbacks.

Get exit code for command in bash/ksh

Below is the fixed code:

safeRunCommand() {
  typeset cmnd="$*"
  typeset ret_code

  echo cmnd=$cmnd
  eval $cmnd
  if [ $ret_code != 0 ]; then
    printf "Error : [%d] when executing command: '$cmnd'" $ret_code
    exit $ret_code

command="ls -l | grep p"
safeRunCommand "$command"

Now if you look into this code few things that I changed are:

  • use of typeset is not necessary but a good practice. It make cmnd and ret_code local to safeRunCommand
  • use of ret_code is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
  • pass the command with quotes surrounding the command like safeRunCommand "$command". If you dont then cmnd will get only the value ls and not ls -l. And it is even more important if your command contains pipes.
  • you can use typeset cmnd="$*" instead of typeset cmnd="$1" if you want to keep the spaces. You can try with both depending upon how complex is your command argument.
  • eval is used to evaluate so that command containing pipes can work fine

NOTE: Do remember some commands give 1 as return code even though there is no error like grep. If grep found something it will return 0 else 1.

I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.

How to exit if a command failed?

You can also use, if you want to preserve exit error status, and have a readable file with one command per line:

my_command1 || exit $?
my_command2 || exit $?

This, however will not print any additional error message. But in some cases, the error will be printed by the failed command anyway.

break/exit script

Edit: Seems the OP is running a long script, in that case one only needs to wrap the part of the script after the quality control with

if (n >= 500) {

.... long running code here


If breaking out of a function, you'll probably just want return(), either explicitly or implicitly.

For example, an explicit double return

foo <- function(x) {
  if(x < 10) {
  } else {
    xx <- seq_len(x)
    xx <- cumsum(xx)
  xx ## return(xx) is implied here

> foo(5)
[1] 0
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55

By return() being implied, I mean that the last line is as if you'd done return(xx), but it is slightly more efficient to leave off the call to return().

Some consider using multiple returns bad style; in long functions, keeping track of where the function exits can become difficult or error prone. Hence an alternative is to have a single return point, but change the return object using the if () else () clause. Such a modification to foo() would be

foo <- function(x) {
  ## out is NA or cumsum(xx) depending on x
  out <- if(x < 10) {
  } else {
    xx <- seq_len(x)
  out ## return(out) is implied here

> foo(5)
[1] NA
> foo(10)
 [1]  1  3  6 10 15 21 28 36 45 55

How to Exit a Method without Exiting the Program?

I would use return null; to indicate that there is no data to be returned

How to properly exit a C# application?

I would either one of the following:


for a winform or


for a console application (works on winforms too).


exit application when click button - iOS

You can use exit method to quit an ios app :


You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

How to terminate the script in JavaScript?

throw "";

Is a misuse of the concept but probably the only option. And, yes, you will have to reset all event listeners, just like the accepted answer mentions. You would also need a single point of entry if I am right.

On the top of it: You want a page which reports to you by email as soon as it throws - you can use for example Raven/Sentry for this. But that means, you produce yourself false positives. In such case, you also need to update the default handler to filter such events out or set such events on ignore on Sentry's dashboard.


This does not work during the loading of the page. It stops decoding of the page as well. So you cannot really use it to offer user a javascript-free variant of your page.


Stops execution only with debugger opened. Works great, but not a deliverable.

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

Instead of if construct, you can leverage the short-circuit evaluation:

#!/usr/bin/env bash

echo $[1+1]
echo $[2/0]              # division by 0 but execution of script proceeds
echo $[3+1]
(echo $[4/0]) || exit $? # script halted with code 1 returned from `echo`
echo $[5+1]

Note the pair of parentheses which is necessary because of priority of alternation operator. $? is a special variable set to exit code of most recently called command.

Correct way to quit a Qt program?

QApplication is derived from QCoreApplication and thereby inherits quit() which is a public slot of QCoreApplication, so there is no difference between QApplication::quit() and QCoreApplication::quit().

As we can read in the documentation of QCoreApplication::quit() it "tells the application to exit with return code 0 (success).". If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call QCoreApplication::exit() because you can provide a non-zero returnCode which, by convention, indicates an error.

It is important to note that "if the event loop is not running, this function (QCoreApplication::exit()) does nothing", so in that case you should call exit(EXIT_FAILURE).

How to exit from the application and show the home screen?

if you want to exit application put this code under your function

public void yourFunction()


//For an instance, if you want to exit an application on double click of a 
//button,then the following code can be used.
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 2) {
        // do something on back.
        From Android 16+ you can use the following:


    return super.onKeyDown(keyCode, event);

How to use sys.exit() in Python

sys.exit() raises a SystemExit exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit

How to stop C++ console application from exiting immediately?


#include <cstdio>

    int main(){
        // code...
        return 0;

for some reason there is usually 1 character possible to read with getchar already in stdin when you run a program. so the first getchar reads this character, and the second getchar waits for user (your) input before exiting the program. And after a program exits most of terminals, especially on Windows close terminal immediately. so what we aim to is a simple way of preventing a program from finishing after it outputs everything. Of course there are more complex and clean ways to solve this, but this is the simplest.

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Exit a Script On Error

Here is the way to do it:


    echo >&2 '
*** ABORTED ***
    echo "An error occurred. Exiting..." >&2
    exit 1

trap 'abort' 0

set -e

# Add your script below....
# If an error occurs, the abort() function will be called.
# ===> Your script goes here
# Done!
trap : 0

echo >&2 '
*** DONE *** 

Stopping a JavaScript function when a certain condition is met

Return is how you exit out of a function body. You are using the correct approach.

I suppose, depending on how your application is structured, you could also use throw. That would typically require that your calls to your function are wrapped in a try / catch block.

What is the command to exit a Console application in C#?

Console applications will exit when the main function has finished running. A "return" will achieve this.

    static void Main(string[] args)
        while (true)
            Console.WriteLine("I'm running!");
            return; //This will exit the console application's running thread

If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:


Checking Bash exit status of several commands efficiently

You can use @john-kugelman 's awesome solution found above on non-RedHat systems by commenting out this line in his code:

. /etc/init.d/functions

Then, paste the below code at the end. Full disclosure: This is just a direct copy & paste of the relevant bits of the above mentioned file taken from Centos 7.

Tested on MacOS and Ubuntu 18.04.

MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

echo_success() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
    echo -n $"  OK  "
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 0

echo_failure() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo -n $"FAILED"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 1

echo_passed() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo -n $"PASSED"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 1

echo_warning() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo -n $"WARNING"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    return 1

Ruby - ignore "exit" in code

loop {   begin   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

How to exit a function in bash


return [n]

From help return

return: return [n]

Return from a shell function.

Causes a function or sourced script to exit with the return value
specified by N.  If N is omitted, the return status is that of the
last command executed within the function or script.

Exit Status:
Returns N, or failure if the shell is not executing a function or script.

When should we call System.exit in Java

System.exit() can be used to run shutdown hooks before the program quits. This is a convenient way to handle shutdown in bigger programs, where all parts of the program can't (and shouldn't) be aware of each other. Then, if someone wants to quit, he can simply call System.exit(), and the shutdown hooks (if properly set up) take care of doing all necessary shutdown ceremonies such as closing files, releasing resources etc.

"This method never returns normally." means just that the method won't return; once a thread goes there, it won't come back.

Another, maybe more common, way to quit a program is to simply to reach the end of the main method. But if there are any non-daemon threads running, they will not be shut down and thus the JVM will not exit. Thus, if you have any such non-daemon threads, you need some other means (than the shutdown hooks) to shut down all non-daemon threads and release other resources. If there are no other non-daemon threads, returning from main will shut down the JVM and will call the shutdown hooks.

For some reason shutdown hooks seem to be an undervalued and misunderstood mechanism, and people are reinventing the wheel with all kind of proprietary custom hacks to quit their programs. I would encourage using shutdown hooks; it's all there in the standard Runtime that you'll be using anyway.

What are the differences in die() and exit() in PHP?

Functionally, they are identical. So to choose which one to use is totally a personal preference. Semantically in English, they are different. Die sounds negative. When I have a function which returns JSON data to the client and terminate the program, it can be awful if I call this function jsonDie(), and it is more appropriate to call it jsonExit(). For that reason, I always use exit instead of die.

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

Application.Exit() kills your application but there are some instances that it won't close the application.

End is better than Application.Exit().

How do I abort the execution of a Python script?

You can either use:

import sys


raise SystemExit(...)

The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).

Difference between return 1, return 0, return -1 and exit?

return in function return execution back to caller and exit from function terminates the program.

in main function return 0 or exit(0) are same but if you write exit(0) in different function then you program will exit from that position.

returning different values like return 1 or return -1 means that program is returning error .

When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.

How to exit from Python without traceback?

You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).

Try something like this in your main routine:

import sys, traceback

def main():
        do main program stuff here
    except KeyboardInterrupt:
        print "Shutdown requested...exiting"
    except Exception:

if __name__ == "__main__":

Equivalent VB keyword for 'break'

In case you're inside a Sub of Function and you want to exit it, you can use :

Exit Sub


Exit Function 

Difference between return and exit in Bash functions

If you convert a Bash script into a function, you typically replace exit N with return N. The code that calls the function will treat the return value the same as it would an exit code from a subprocess.

Using exit inside the function will force the entire script to end.

SQL Server - stop or break execution of a SQL script

Further refinig Sglasses method, the above lines force the use of SQLCMD mode, and either treminates the scirpt if not using SQLCMD mode or uses :on error exit to exit on any error
CONTEXT_INFO is used to keep track of the state.

SET CONTEXT_INFO  0x1 --Just to make sure everything's ok
--treminate the script on any error. (Requires SQLCMD mode)
:on error exit 
--If not in SQLCMD mode the above line will generate an error, so the next line won't hit
--make sure to use SQLCMD mode ( :on error needs that)
    SELECT 'This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!'
    RAISERROR('This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!',16,1) WITH NOWAIT 
    WAITFOR DELAY '02:00'; --wait for the user to read the message, and terminate the script manually


Using HTML and Local Images Within UIWebView

In Swift 3:

webView.loadHTMLString("<img src=\"myImg.jpg\">", baseURL: Bundle.main.bundleURL)

This worked for me even when the image was inside of a folder without any modifications.

How to delete stuff printed to console by System.out.println()?

this solution is applicable if you want to remove some System.out.println() output. It restricts that output to print on console and print other outputs.

PrintStream ps = System.out;
System.setOut(new PrintStream(new OutputStream() {
   public void write(int b) throws IOException {}

System.out.println("It will not print");

//To again enable it.

System.out.println("It will print");

chart.js load totally new data

When creating the chart object you need to save the instance in a variable.

var currentChart = new Chart(ctx, ...);

And before loading new data, you need to destroy it:


Build error: "The process cannot access the file because it is being used by another process"

I solved this by deleting the folder bin\Debug and, possibly, restarting VS

NumPy first and last element from array

I ended here, because I googled for "python first and last element of array", and found everything else but this. So here's the answer to the title question:

a = [1,2,3]
a[0] # first element (returns 1)
a[-1] # last element (returns 3)

Difference between char* and const char*?


char *str = "Hello";
str[0] = 'M'  //Warning may be issued by compiler, and will cause segmentation fault upon running the programme

The above sets str to point to the literal value "Hello" which is hard-coded in the program's binary image, which is flagged as read-only in memory, means any change in this String literal is illegal and that would throw segmentation faults.


const char *str = "Hello";
str[0] = 'M'  //Compile time error


char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".

How organize uploaded media in WP?

The plugin Media File Manager advanced is amazing and allow you to create folders and subfolders very easily and move files with a simple drag & drop.

Check it at:

How to fix git error: RPC failed; curl 56 GnuTLS

Simply executing command

git init

before cloning resolved it for me.

MongoDB: How to find the exact version of installed MongoDB


Start the console and execute this:



Open a shell console and do:

$ mongod --version

It will show you something like

$ mongod --version
db version v3.0.2

Difference between break and continue in PHP?

break will exit the loop, while continue will start the next cycle of the loop immediately.

Xcode 10: A valid provisioning profile for this executable was not found

In my case, here are the steps that I resolve the problems:

  1. Go to this folder: ~/Library/MobileDevice/Provisioning Profiles/
  2. Remove all the provisioning profile
  3. In Xcode 10 menu > Product > Clean Build Folder
  4. In Xcode 10 menu > Xcode > Preferences > Account > Download Manual Profiles
  5. In Xcode 10 menu > Product > Build / Archive

The reason to take the steps above is to remove the old provisioning profiles that messed up the building process.

Dynamic loading of images in WPF

In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".

        this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
             + Assembly.GetExecutingAssembly().GetName().Name 
             + ";component/" 
             + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function if anybody would like it...

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
    if (assembly == null)
        assembly = Assembly.GetCallingAssembly();

    if (pathInApplication[0] == '/')
        pathInApplication = pathInApplication.Substring(1);
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 


        this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])


for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

Try changing the contentInset property that UITableView inherits from UIScrollView.

self.tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);

It's a workaround, but it works

Using CSS to insert text

Just code it like this:

.OwnerJoe {
  //other things here
    content: "Joe's Task: ";

Get property value from C# dynamic object by string (reflection?)

Use the following code to get Name and Value of a dynamic object's property.

dynamic d = new { Property1= "Value1", Property2= "Value2"};

var properties = d.GetType().GetProperties();
foreach (var property in properties)
    var PropertyName=property.Name; 
//You get "Property1" as a result

  var PropetyValue=d.GetType().GetProperty(property.Name).GetValue(d, null); 
//You get "Value1" as a result

// you can use the PropertyName and Value here

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

I 'tripped' across my solution after 2 days...XCODE 4.0

I've just upgraded to XCode 4.0 and this code signing issue has been a stunning frustrastion. And I've been doing this for over a year various if you are having problems, you are not alone.

I have recertified, reprovisioned, drag and dropped, manually edit the project file, deleted PROVISIIONING paths, stopped/started XCODE, stopped started keychain, checked spelling, checked bundle ID's, check my birth certificate, the phase of the moon, and taught my dog morse code...none of it worked!!!!

--bottom line---

  1. Goto Targets... Build Settings tab
  2. Go to the Code Signing identity block
    • Check Debug AND Distribution have the same code signing information my case "IPhone Distribution:, dont let DEBUG be blank or not filled in.

If the Debug mode was not the same, it failed the Distribution mode as well...go figure. Hope that helps someone...

Figure: This shows how to find the relevant settings in XCode 4.5.

enter image description here

IBOutlet and IBAction

An Outlet is a link from code to UI. If you want to show or hide an UI element, if you want to get the text of a textfield or enable or disable an element (or a hundred other things) you have to define an outlet of that object in the sources and link that outlet through the “interface object” to the UI element. After that you can use the outlet just like any other variable in your coding.

IBAction – a special method triggered by user-interface objects. Interface Builder recognizes them.

@interface Controller
  IBOutlet id textField; // links to TextField UI object

- (IBAction)doAction:(id)sender; // e.g. called when button pushed

For further information please refer Apple Docs

Is there a CSS parent selector?

As mentioned by a couple of others, there isn't a way to style an element's parent/s using just CSS but the following works with jQuery:

$("").parents('li').css("property", "value");

How to advance to the next form input when the current input has a value?

Needed to emulate the tab functionality a while ago, and now I've released it as a library that uses .

EmulateTab: A jQuery plugin to emulate tabbing between elements on a page.

You can see how it works in the demo.

if (myTextHasBeenFilledWithText) {
  // Tab to the next input after #my-text-input

GROUP BY + CASE statement

For TSQL I like to encapsulate case statements in an outer apply. This prevents me from having to have the case statement written twice, allows reference to the case statement by alias in future joins and avoids the need for positional references.

COUNT(*) MyCount 
FROM attempt attempt, prod_hw_id prod_hw_id, model model
WHERE time >= '2013-11-06 00:00:00'  
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
     CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END result
    ) oa    
group by,, 
order by, attempt.type, oa.result;

How to create a Calendar table for 100 years in Sql

Here is a generic script you can use in SQL server. just amend the start and end dates:

IF EXISTS (SELECT * FROM information_schema.tables WHERE Table_Name = 'Calendar' AND Table_Type = 'BASE TABLE')
DROP TABLE [Calendar]

    [CalendarDate] DATETIME

SET @StartDate = GETDATE()
SET @EndDate = DATEADD(d, 365, @StartDate)

WHILE @StartDate <= @EndDate
             INSERT INTO [Calendar]

             SET @StartDate = DATEADD(dd, 1, @StartDate)

If you want a more advanced calendar here is one I found on the net a while ago:

-- We put our auxiliary tables and stuff in a separate schema
-- One of the great new things in SQL Server 2005

CREATE FUNCTION Auxiliary.Computus
-- Computus (Latin for computation) is the calculation of the date of
-- Easter in the Christian calendar
-- I'm using the Meeus/Jones/Butcher Gregorian algorithm
    @Y INT -- The year we are calculating easter sunday for
@a INT,
@b INT,
@c INT,
@d INT,
@e INT,
@f INT,
@g INT,
@h INT,
@i INT,
@k INT,
@m INT

SET @a = @Y % 19
SET @b = @Y / 100
SET @c = @Y % 100
SET @d = @b / 4
SET @e = @b % 4
SET @f = (@b + 8) / 25
SET @g = (@b - @f + 1) / 3
SET @h = (19 * @a + @b - @d - @g + 15) % 30
SET @i = @c / 4
SET @k = @c % 4
SET @L = (32 + 2 * @e + 2 * @i - @h - @k) % 7
SET @m = (@a + 11 * @h + 22 * @L) / 451
RETURN(DATEADD(month, ((@h + @L - 7 * @m + 114) / 31)-1, cast(cast(@Y AS VARCHAR) AS Datetime)) + ((@h + @L - 7 * @m + 114) % 31))

CREATE TABLE [Auxiliary].[Calendar] (
-- This is the calendar table
  [Date] datetime NOT NULL,
  [Year] int NOT NULL,
  [Quarter] int NOT NULL,
  [Month] int NOT NULL,
  [Week] int NOT NULL,
  [Day] int NOT NULL,
  [DayOfYear] int NOT NULL,
  [Weekday] int NOT NULL,
  [Fiscal_Year] int NOT NULL,
  [Fiscal_Quarter] int NOT NULL,
  [Fiscal_Month] int NOT NULL,
  [KindOfDay] varchar(10) NOT NULL,
  [Description] varchar(50) NULL,

ALTER TABLE [Auxiliary].[Calendar]
-- In Celkoish style I'm manic about constraints (Never use em ;-))

ADD CONSTRAINT [Calendar_ck] CHECK (  ([Year] > 1900)
AND ([Quarter] BETWEEN 1 AND 4)
AND ([Month] BETWEEN 1 AND 12)
AND ([Week]  BETWEEN 1 AND 53)
AND ([Day] BETWEEN 1 AND 31)
AND ([DayOfYear] BETWEEN 1 AND 366)
AND ([Weekday] BETWEEN 1 AND 7)
AND ([Fiscal_Year] > 1900)
AND ([Fiscal_Quarter] BETWEEN 1 AND 4)
AND ([Fiscal_Month] BETWEEN 1 AND 12)

-- I want my table to contain datedata acording to ISO 8601
-- thus first day of a week is monday
WITH Dates(Date)
-- A recursive CTE that produce all dates between 1999 and 2020-12-31
SELECT cast('1999' AS DateTime) Date -- SQL Server supports the ISO 8601 format so this is an unambigious shortcut for 1999-01-01
UNION ALL                            --
SELECT (Date + 1) AS Date
FROM Dates
Date < cast('2021' AS DateTime) -1

DatesAndThursdayInWeek(Date, Thursday)
-- The weeks can be found by counting the thursdays in a year so we find
-- the thursday in the week for a particular date
CASE DATEPART(weekday,Date)
WHEN 1 THEN Date + 3
WHEN 2 THEN Date + 2
WHEN 3 THEN Date + 1
WHEN 5 THEN Date - 1
WHEN 6 THEN Date - 2
WHEN 7 THEN Date - 3
END AS Thursday
FROM Dates

Weeks(Week, Thursday)
-- Now we produce the weeknumers for the thursdays
-- ROW_NUMBER is new to SQL Server 2005
SELECT ROW_NUMBER() OVER(partition by year(Date) order by Date) Week, Thursday
FROM DatesAndThursdayInWeek
WHERE DATEPART(weekday,Date) = 4
INSERT INTO Auxiliary.Calendar
YEAR(d.Date) AS Year,
DATEPART(Quarter, d.Date) AS Quarter,
MONTH(d.Date) AS Month,
DAY(d.Date) AS Day,
DATEPART(DayOfYear, d.Date) AS DayOfYear,
DATEPART(Weekday, d.Date) AS Weekday,

-- Fiscal year may be different to the actual year in Norway the are the same
YEAR(d.Date) AS Fiscal_Year,
DATEPART(Quarter, d.Date) AS Fiscal_Quarter,
MONTH(d.Date) AS Fiscal_Month,

-- Holidays in Norway
-- For other countries and states: Wikipedia - List of holidays by country
    WHEN (DATEPART(DayOfYear, d.Date) = 1)          -- New Year's Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-7)  -- Palm Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-3)  -- Maundy Thursday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-2)  -- Good Friday
    OR (d.Date = Auxiliary.Computus(YEAR(Date)))    -- Easter Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+39) -- Ascension Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+49) -- Pentecost
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+50) -- Whitmonday
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      -- Labour day
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     -- Constitution day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    -- Cristmas day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    -- Boxing day
    WHEN DATEPART(Weekday, d.Date) = 6 THEN 'SATURDAY'
    WHEN DATEPART(Weekday, d.Date) = 7 THEN 'SUNDAY'
END KindOfDay,
-- Description of holidays in Norway
    WHEN (DATEPART(DayOfYear, d.Date) = 1)            THEN 'New Year''s Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-7)  THEN 'Palm Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-3)  THEN 'Maundy Thursday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-2)  THEN 'Good Friday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date)))    THEN 'Easter Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+39) THEN 'Ascension Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+49) THEN 'Pentecost'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+50) THEN 'Whitmonday'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      THEN 'Labour day'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     THEN 'Constitution day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    THEN 'Cristmas day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    THEN 'Boxing day'
END Description

FROM DatesAndThursdayInWeek d
-- This join is for getting the week into the result set
     inner join Weeks w
     on d.Thursday = w.Thursday


CREATE FUNCTION Auxiliary.Numbers
@AFrom INT,
@AIncrement INT
WITH Numbers(n)
SELECT (n + @AIncrement) AS n
FROM Numbers
n < @ATo
INSERT @RetNumbers
SELECT n from Numbers

CREATE FUNCTION Auxiliary.iNumbers
@AFrom INT,
@AIncrement INT
WITH Numbers(n)
SELECT (n + @AIncrement) AS n
FROM Numbers
n < @ATo
SELECT n AS Number from Numbers

What is the list of valid @SuppressWarnings warning names in Java?

I just want to add that there is a master list of IntelliJ suppress parameters at:

It looks fairly comprehensive. Partial:

Warning Description - Warning Name

"Magic character" MagicCharacter 
"Magic number" MagicNumber 
'' method does not use parameter ComparatorMethodParameterNotUsed 
'Connection.prepare*()' call with non-constant string JDBCPrepareStatementWithNonConstantString 
'Iterator.hasNext()' which calls 'next()' IteratorHasNextCallsIteratorNext 
'' which can't throw 'NoSuchElementException' IteratorNextCanNotThrowNoSuchElementException 
'Statement.execute()' call with non-constant string JDBCExecuteWithNonConstantString 
'String.equals("")' StringEqualsEmptyString 
'StringBuffer' may be 'StringBuilder' (JDK 5.0 only) StringBufferMayBeStringBuilder 
'StringBuffer.toString()' in concatenation StringBufferToStringInConcatenation 
'assert' statement AssertStatement 
'assertEquals()' between objects of inconvertible types AssertEqualsBetweenInconvertibleTypes 
'await()' not in loop AwaitNotInLoop 
'await()' without corresponding 'signal()' AwaitWithoutCorrespondingSignal 
'break' statement BreakStatement 
'break' statement with label BreakStatementWithLabel 
'catch' generic class CatchGenericClass 
'clone()' does not call 'super.clone()' CloneDoesntCallSuperClone

Confirm Password with jQuery Validate

        rules : {
            password : {
                minlength : 5
            password_confirm : {
                minlength : 5,
                equalTo : '[name="password"]'

In general, you will not use id="password" like this. So, you can use [name="password"] instead of "#password"

What is the difference between concurrency and parallelism?

Explanation from this source was helpful for me:

Concurrency is related to how an application handles multiple tasks it works on. An application may process one task at at time (sequentially) or work on multiple tasks at the same time (concurrently).

Parallelism on the other hand, is related to how an application handles each individual task. An application may process the task serially from start to end, or split the task up into subtasks which can be completed in parallel.

As you can see, an application can be concurrent, but not parallel. This means that it processes more than one task at the same time, but the tasks are not broken down into subtasks.

An application can also be parallel but not concurrent. This means that the application only works on one task at a time, and this task is broken down into subtasks which can be processed in parallel.

Additionally, an application can be neither concurrent nor parallel. This means that it works on only one task at a time, and the task is never broken down into subtasks for parallel execution.

Finally, an application can also be both concurrent and parallel, in that it both works on multiple tasks at the same time, and also breaks each task down into subtasks for parallel execution. However, some of the benefits of concurrency and parallelism may be lost in this scenario, as the CPUs in the computer are already kept reasonably busy with either concurrency or parallelism alone. Combining it may lead to only a small performance gain or even performance loss.

How to remove unique key from mysql table

For those who don't know how to get index_name which mentioned in Devart's answer, or key_name which mentioned in Uday Sawant's answer, you can get it like this:

SHOW INDEX FROM table_name;

This will show all indexes for the given table, then you can pick name of the index or unique key that you want to remove.

No server in windows>preferences

Follow the below steps:

1.Goto Help -> Install new Software
2.Give address and name as your choice.
3.Search for Java EE and choose 1.Eclipse Java EE Developer Tools 
4.Search for JST and choose 2.JST Server Adapters 3.JST Server Adapters 
5.Click next and accept the license agreement.

Find the server option in the window-->preferences and add server as you need

Laravel - display a PDF file in storage without forcing download?

Ben Swinburne answer was so helpful.

The code below is for those who have their PDF file in database like me.

$pdf = DB::table('exportfiles')->select('pdf')->where('user_id', $user_id)->first();

return Response::make(base64_decode( $pdf->pdf), 200, [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'inline; filename="'.$filename.'"',

Where $pdf->pdf is the file column in database.

Get all variables sent with POST?

you should be able to access them from $_POST variable:

foreach ($_POST as $param_name => $param_val) {
    echo "Param: $param_name; Value: $param_val<br />\n";

Visual Studio "Could not copy" .... during build

In my case it was Resharper Unit Tests runner (plus NUnit tests, never had such problem with MsTests). After killing the process, was able to rebuild process, without restarting OS or VS2013.

Other test runners, like xUnit can cause the same issue.

What helps then is to check if you can add a Dispose pattern, for example if you're adding a DbFixture and the database contacts isn't disposed properly. That will cause the assembly files being locked even if the tests completed.

Note that you can just add IDisposable interface to your DbFixture and let IntelliSense add the Dispose pattern. Then, dispose the related contained propertys and explicitly assign them to null.

That will help to end the tests in a clean way and unlock related locked files as soon as the tests ended.

Example (DBFixture is used by xUnit tests):

public class DbFixture: IDisposable
    private bool disposedValue;
    public ServiceProvider ServiceProvider { get; private set; }
    public DbFixture()
        // initializes ServiceProvider
    protected virtual void Dispose(bool disposing)
        if (!disposedValue)
            if (disposing)
                // dispose managed state (managed objects)
                ServiceProvider = null;

            // TODO: free unmanaged resources (unmanaged objects) and override finalizer
            // TODO: set large fields to null
            disposedValue = true;

    // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
    // ~DbFixture()
    // {
    //     // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
    //     Dispose(disposing: false);
    // }

    public void Dispose()
        // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
        Dispose(disposing: true);

The same pattern you need for the test class itself - it needs its own Dispose method (as shown for the DbFixture class above):

   public SQL_Tests(ITestOutputHelper output)
        this.Output = output;
        var fixture = new DbFixture(); // NOTE: MS Dependency injection framework didn't initialize when the fixture was a constructor param, hence it is here
        _serviceProvider = fixture.ServiceProvider;
    } // method

So it needs to dispose its local property _serviceProvider in its own Dispose method, because the test class constructor SQL_Tests instanciated it.

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine:


Set database timeout in Entity Framework

Try this on your context:

public class MyDatabase : DbContext
    public MyDatabase ()
        : base(ContextHelper.CreateConnection("Connection string"), true)
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180; // seconds

If you want to define the timeout in the connection string, use the Connection Timeout parameter like in the following connection string:


<add name="AdventureWorksEntities"
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />


Source: How to: Define the Connection String

Perl regular expression (using a variable as a search string with Perl operator characters included)

Use the quotemeta function:

$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";

print "wee" if ($text_to_search =~ /$search_string/);

jQuery: more than one handler for same event

You should be able to use chaining to execute the events in sequence, e.g.:

  .bind('click',function(event) {
  .bind('click',function(event) {
    alert('Hello again!');
  .bind('click',function(event) {
    alert('Hello yet again!');

I guess the below code is doing the same

      .click(function(event) {
      .click(function(event) {
        alert('Hello again!');
      .click(function(event) {
        alert('Hello yet again!');


TFM also says:

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

css with background image without repeating the image

body {
    background: url(images/image_name.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

Here is a good solution to get your image to cover the full area of the web app perfectly

How to get current user in core

Perhaps I didn't see the answer, but this is how I do it.

  1. .Net Core --> Properties --> launchSettings.json

You need to have change these values

"windowsAuthentication": true, // needs to be true
"anonymousAuthentication": false,  // needs to be false 

Startup.cs --> ConfigureServices(...)

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

MVC or Web Api Controller

private readonly IHttpContextAccessor _httpContextAccessor;
//constructor then
_httpContextAccessor = httpContextAccessor;

Controller method:

string userName = _httpContextAccessor.HttpContext.User.Identity.Name;

Result is userName e.g. = Domain\username

Add a UIView above all, even the navigation bar

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

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

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

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

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

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

And simply use it like this:


VBA code to set date format for a specific column as "yyyy-mm-dd"

You are applying the formatting to the workbook that has the code, not the added workbook. You'll want to get in the habit of fully qualifying sheet and range references. The code below does that and works for me in Excel 2010:

Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
    .Range("A1") = "Acctdate"
    .Range("B1") = "Ledger"
    .Range("C1") = "CY"
    .Range("D1") = "BusinessUnit"
    .Range("E1") = "OperatingUnit"
    .Range("F1") = "LOB"
    .Range("G1") = "Account"
    .Range("H1") = "TreatyCode"
    .Range("I1") = "Amount"
    .Range("J1") = "TransactionCurrency"
    .Range("K1") = "USDEquivalentAmount"
    .Range("L1") = "KeyCol"
    .Range("A2", "A50000").Value = Me.TextBox3.Value
    .Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub

Installing PIL with pip

  • First you should run this sudo apt-get build-dep python-imaging which will give you all the dependencies that you might need

  • Then run sudo apt-get update && sudo apt-get -y upgrade

  • Followed by sudo apt-get install python-pip

  • And then finally install Pil pip install pillow

Batch file to perform start, run, %TEMP% and delete all

@echo off
RD %TEMP%\. /S /Q

explorer %temp%

This batch can run from anywhere. RD stands for Remove Directory but this can remove both folders and files which available to delete.

PHP: trying to create a new line with "\n"

If you want to write plain text, you must ensure the content type is set to Content-Type: text/plain. Example:

header('Content-Type: text/plain');

If you are dealing with HTML, you have two options. One is to inset a new line using <br> (Or <br /> for XHTML). The other is to put the plain text in a <pre> element (In this case "pre" stands for preformatted).

Why is Spring's ApplicationContext.getBean considered bad?

I mentioned this in a comment on the other question, but the whole idea of Inversion of Control is to have none of your classes know or care how they get the objects they depend on. This makes it easy to change what type of implementation of a given dependency you use at any time. It also makes the classes easy to test, as you can provide mock implementations of dependencies. Finally, it makes the classes simpler and more focused on their core responsibility.

Calling ApplicationContext.getBean() is not Inversion of Control! While it's still easy to change what implemenation is configured for the given bean name, the class now relies directly on Spring to provide that dependency and can't get it any other way. You can't just make your own mock implementation in a test class and pass that to it yourself. This basically defeats Spring's purpose as a dependency injection container.

Everywhere you want to say:

MyClass myClass = applicationContext.getBean("myClass");

you should instead, for example, declare a method:

public void setMyClass(MyClass myClass) {
   this.myClass = myClass;

And then in your configuration:

<bean id="myClass" class="MyClass">...</bean>

<bean id="myOtherClass" class="MyOtherClass">
   <property name="myClass" ref="myClass"/>

Spring will then automatically inject myClass into myOtherClass.

Declare everything in this way, and at the root of it all have something like:

<bean id="myApplication" class="MyApplication">
   <property name="myCentralClass" ref="myCentralClass"/>
   <property name="myOtherCentralClass" ref="myOtherCentralClass"/>

MyApplication is the most central class, and depends at least indirectly on every other service in your program. When bootstrapping, in your main method, you can call applicationContext.getBean("myApplication") but you should not need to call getBean() anywhere else!

SQL Server query to find all permissions/access for all users in a database

A simple query that shows only whether you are a SysAdmin or not :

IF IS_SRVROLEMEMBER ('sysadmin') = 1  
   print 'Current user''s login is a member of the sysadmin role'  
ELSE IF IS_SRVROLEMEMBER ('sysadmin') = 0  
   print 'Current user''s login is NOT a member of the sysadmin role'  
   print 'ERROR: The server role specified is not valid.';

C++ undefined reference to defined function

If you are including a library which depends on another library, then the order of inclusion is also important:

g++ -o MyApp MyMain.o -lMyLib1 -lMyLib2

In this case, it is okay if MyLib1 depends on MyLib2. However, if there reverse is true, you will get undefined references.

Difference between acceptance test and functional test?

The difference is between testing the problem and the solution. Software is a solution to a problem, both can be tested.

The functional test confirms the software performs a function within the boundaries of how you've solved the problem. This is an integral part of developing software, comparable to the testing that is done on mass produced product before it leaves the factory. A functional test verifies that the product actually works as you (the developer) think it does.

Acceptance tests verify the product actually solves the problem it was made to solve. This can best be done by the user (customer), for instance performing his/her tasks that the software assists with. If the software passes this real world test, it's accepted to replace the previous solution. This acceptance test can sometimes only be done properly in production, especially if you have anonymous customers (e.g. a website). Thus a new feature will only be accepted after days or weeks of use.

Functional testing - test the product, verifying that it has the qualities you've designed or build (functions, speed, errors, consistency, etc.)

Acceptance testing - test the product in its context, this requires (simulation of) human interaction, test it has the desired effect on the original problem(s).

SQL Views - no variables?

You could use WITH to define your expressions. Then do a simple Sub-SELECT to access those definitions.

  WITH MyVars (SomeVar, Var2)
  AS (
      'something' AS 'SomeVar',
      123 AS 'Var2'

  FROM MyTable
  WHERE x = (SELECT SomeVar FROM MyVars)

check if variable is dataframe

Use the built-in isinstance() function.

import pandas as pd

def f(var):
    if isinstance(var, pd.DataFrame):
        print("do stuff")

What is the best way to access redux store outside a react component?

Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute the global window space.


const store = createStore(myReducer);
export store;


const store = createStore(myReducer);
export default store;


import {store} from './MyStore'

or if you used default

import store from './MyStore'

For Multiple Store Use Cases

If you need multiple instances of a store, export a factory function. I would recommend making it async (returning a promise).

async function getUserStore (userId) {
   // check if user store exists and return or create it.
export getUserStore

On the client (in an async block)

import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

Changing specific text's color using NSMutableAttributedString in Swift

I see you have answered the question somewhat, but to provide a slightly more concise way without using regex to answer to the title question:

To change the colour of a length of text you need to know the start and end index of the coloured-to-be characters in the string e.g.

var main_string = "Hello World"
var string_to_color = "World"

var range = (main_string as NSString).rangeOfString(string_to_color)

Then you convert to attributed string and use 'add attribute' with NSForegroundColorAttributeName:

var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

A list of further standard attributes you can set can be found in Apple's documentation

How can I interrupt a running code in R with a keyboard command?

Self Answer (pretty much summary of other's comments and answers):

  • In RStudio, Esc works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).

  • If the process is ran in say ubuntu shell (and this is not R specific), for example using:

    Rscript my_file.R

    Ctrl + c kills the process

    Ctrl + z suspends the process

  • Within R shell, Ctrl + C kills helps you escape it

How to remove all click event handlers using jQuery?

You would use off() to remove an event like so:


but this will remove all click events bound to this element. If the function with SaveQuestion is the only event bound then the above will do it. If not do the following:

$("#saveBtn").off("click").click(function() { saveQuestion(id); });

Can I make 'git diff' only the line numbers AND changed file names?

Line numbers as in number of changed lines or the actual line numbers containing the changes? If you want the number of changed lines, use git diff --stat. This gives you a display like this:

[me@somehost:~/newsite:master]> git diff --stat
 whatever/views/ |    8 ++++++++
 1 files changed, 8 insertions(+), 0 deletions(-)

There is no option to get the line numbers of the changes themselves.

Rank function in MySQL

@Sam, your point is excellent in concept but I think you misunderstood what the MySQL docs are saying on the referenced page -- or I misunderstand :-) -- and I just wanted to add this so that if someone feels uncomfortable with the @Daniel's answer they'll be more reassured or at least dig a little deeper.

You see the "@curRank := @curRank + 1 AS rank" inside the SELECT is not "one statement", it's one "atomic" part of the statement so it should be safe.

The document you reference goes on to show examples where the same user-defined variable in 2 (atomic) parts of the statement, for example, "SELECT @curRank, @curRank := @curRank + 1 AS rank".

One might argue that @curRank is used twice in @Daniel's answer: (1) the "@curRank := @curRank + 1 AS rank" and (2) the "(SELECT @curRank := 0) r" but since the second usage is part of the FROM clause, I'm pretty sure it is guaranteed to be evaluated first; essentially making it a second, and preceding, statement.

In fact, on that same MySQL docs page you referenced, you'll see the same solution in the comments -- it could be where @Daniel got it from; yeah, I know that it's the comments but it is comments on the official docs page and that does carry some weight.

What does \d+ mean in regular expression terms?

\d means 'digit'. + means, '1 or more times'. So \d+ means one or more digit. It will match 12 and 1.

No resource identifier found for attribute '...' in package ''

this helps for me:

on your build.gradle:

implementation ''

How can I exclude multiple folders using Get-ChildItem -exclude?

may be in your case you could reach this with the following:

    mv excluded_dir ..\
    ls -R 
    mv ..\excluded_dir .

Query Mongodb on month, day, year... of a datetime

If you want to search for documents that belong to a specific month, make sure to query like this:

// Anything greater than this month and less than the next month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 7, 1)}});

Avoid quering like below as much as possible.

// This may not find document with date as the last date of the month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 6, 30)}});

// don't do this too
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lte: new Date(2015, 6, 30)}});

How to iterate object keys using *ngFor

You have to create custom pipe.

import { Injectable, Pipe } from '@angular/core';
   name: 'keyobject'
export class Keyobject {

transform(value, args:string[]):any {
    let keys = [];
    for (let key in value) {
        keys.push({key: key, value: value[key]});
    return keys;

And then use it in your *ngFor

*ngFor="let item of data | keyobject"

Scala best way of turning a Collection into a Map-by-key?

c map (_.getP) zip c

Works well and is very intuitiv

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top =;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top =;
var left = offsets.left;

Each GROUP BY expression must contain at least one column that is not an outer reference

Here's a simple query to find company name who has a medicine type of A and makes more than 2.

    WHERE type='A' 

What is the best way to test for an empty string with jquery-out-of-the-box?

The link you gave seems to be attempting something different to the test you are trying to avoid repeating.

if (a == null || a=='')

tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).

The test you described can be replaced by:

if (!a)

Because in javascript, an empty string, and null, both evaluate to false in a boolean context.

Color Tint UIButton Image

If you have a custom button with a background image.You can set the tint color of your button and override the image with following .

In assets select the button background you want to set tint color.

In the attribute inspector of the image set the value render as to "Template Image"

enter image description here

Now whenever you setbutton.tintColor = you button will be shown in red.

Creating an instance using the class name and calling constructor

You can use reflections

return Class.forName(className).getConstructor(String.class).newInstance(arg);

Maven: mvn command not found

mvn -version

export PATH=$PATH:/opt/apache-maven-3.6.0/bin

PHP cURL not working - WAMP on Windows 7 64 bit

The steps are as follows:

  1. Close WAMP (if running)
  2. Navigate to WAMP\bin\php\<your version of PHP>
  3. Edit file php.ini
  4. Search for curl, uncomment extension=php_curl.dll
  5. Navigate to WAMP\bin\Apache\<your version of Apache>\bin\
  6. Edit file php.ini
  7. Search for curl, uncomment extension=php_curl.dll
  8. Save both
  9. Restart WAMP

How to get the file path from URI?

Here is the answer to the question here

Actually we have to get it from the sharable ContentProvider of Camera Application.

EDIT . Copying answer that worked for me

private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String result = cursor.getString(column_index);
return result;


npm install won't install devDependencies

Make sure your package.json is valid...

I had the following error...

npm WARN Invalid name: "blah blah blah"

and that, similarly, caused devDependencies not to be installed.

FYI, changing the package.json "name" to blah-blah-blah fixed it.

Predicate Delegates in C#

Leading on from Andrew's answer with regards to c#2 and c#3 ... you can also do them inline for a one off search function (see below).

using System;
using System.Collections.Generic;

class Program
    static void Main()
        List<int> list = new List<int> { 1, 2, 3 };

        List<int> newList = list.FindAll(delegate(int arg)
                               return arg> 2;

Hope this helps.

What does ellipsize mean in android?

android:ellipsize added in API Level 1. An ellipsis is three periods in a row. (...) .

In your Xml

       android:text="Hi I am Amiyo, you can see how to ellipse works."
       android:ellipsize = "end"  

At this point, the ellipsis will not display yet as a TextView is set to automatically expand on default when new text is entered. You will need to limit the TextView in some way. Do do this, you can use either add to your TextView a scrollHorizontally, minLines, or maxLines to have the ellipsis display.

To make the ellipse:

    at the end: this is how it would.   
    use: android:ellipsize = "end"


 in the middle:
 use: android:ellipsize = "middle"


 at the start:
 use: android:ellipsize = "start"


 to have no ellipse
 use: android:ellipsize = "none"

Note Please :

Do not use android:singeLine = "true", it is deprecated.
android:maxLines = "1" will not display the three dots (...)
android:lines = "1" will not display the three dots (...)

For more details you can visit here

get list of packages installed in Anaconda

To check if a specific package is installed:

conda list html5lib

which outputs something like this if installed:

# packages in environment at C:\ProgramData\Anaconda3:
# Name                    Version                   Build  Channel
html5lib                  1.0.1                    py37_0

or something like this if not installed:

# packages in environment at C:\ProgramData\Anaconda3:
# Name                    Version                   Build  Channel

you don't need to type the exact package name. Partial matches are supported:

conda list html

This outputs all installed packages containing 'html':

# packages in environment at C:\ProgramData\Anaconda3:
# Name                    Version                   Build  Channel
html5lib                  1.0.1                    py37_0
sphinxcontrib-htmlhelp    1.0.2                      py_0
sphinxcontrib-serializinghtml 1.1.3                      py_0

Regular expression search replace in Sublime Text 2

Note that if you use more than 9 capture groups you have to use the syntax ${10}.

$10 or \10 or \{10} will not work.

How to compare datetime with only date in SQL Server

According to your query Select * from [User] U where U.DateCreated = '2014-02-07'

SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220 with 2014-02-07 00:00:00.000 for equality). that's why result of comparison is false

Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'.

JavaScript: function returning an object

You can simply do it like this with an object literal:

function makeGamePlayer(name,totalScore,gamesPlayed) {
    return {
        name: name,
        totalscore: totalScore,
        gamesPlayed: gamesPlayed

How to output a comma delimited list in jinja python template?

You want your if check to be:

{% if not loop.last %}
{% endif %}

Note that you can also shorten the code by using If Expression:

{{ ", " if not loop.last else "" }}

Permutations between two lists of unequal length

May be simpler than the simplest one above:

>>> a = ["foo", "bar"]
>>> b = [1, 2, 3]
>>> [(x,y) for x in a for y in b]  # for a list
[('foo', 1), ('foo', 2), ('foo', 3), ('bar', 1), ('bar', 2), ('bar', 3)]
>>> ((x,y) for x in a for y in b)  # for a generator if you worry about memory or time complexity.
<generator object <genexpr> at 0x1048de850>

without any import

Does it matter what extension is used for SQLite database files?

Pretty much down to personal choice. It may make sense to use an extension based on the database scheme you are storing; treat your database schema as a file format, with SQLite simply being an encoding used for that file format. So, you might use .bookmarks if it's storing bookmarks, or .index if it's being used as an index.

If you want to use a generic extension, I'd use .sqlite3 since that is most descriptive of what version of SQLite is needed to work with the database.

Checkout multiple git repos into same Jenkins workspace

Checking out more than one repo at a time in a single workspace is possible with Jenkins + Git Plugin (maybe only in more recent versions?).

In section "Source-Code-Management", do not select "Git", but "Multiple SCMs" and add several git repositories.

Be sure that in all but one you add as an "Additional behavior" the action "Check out to a sub-directory" and specify an individual subdirectory.

How to center cards in bootstrap 4?

i basically suggest equal gap on right and left, and setting width to auto. Here like:

.bmi {         /*my additional class name -for card*/
    margin-left: 18%;      
    margin-right: 18%;
    width: auto;

Submit HTML form, perform javascript function (alert then redirect)

Looks like your form is submitting which is the default behaviour, you can stop it with this:

<form action="" method="post" onsubmit="completeAndRedirect();return false;">

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

Solved 403: Forbidden when visiting localhost. Using ports 80,443,3308 (the later to handle conflict with MySQL Server installation) Windows 10, XAMPP 7.4.1, Apache 2.4.x My web files are in a separate folder.

httpd.conf - look for these lines and set it up where you have your files, mine is web folder.

DocumentRoot "C:/web"
<Directory "C:/web">

Changed these 2 lines.

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot "C:/web/project1"
 ServerName project1.localhost
 <Directory "C:/web/project1">
  Order allow,deny
  allow from all

to this

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot "C:/web/project1"
 ServerName project1.localhost
 <Directory "C:/web/project1">
  Require all granted

Add your details in your hosts file C:\Windows\System32\drivers\etc\hosts file localhost project1.localhost

Stop start XAMPP, and click Apache admin (or localhost) and the wonderful XAMPP dashboard now displays! And visit your project at project1.localhost

How do I create ColorStateList programmatically?

Here's an example of how to create a ColorList programmatically in Kotlin:

val colorList = ColorStateList(
                intArrayOf(-android.R.attr.state_enabled),  // Disabled
                intArrayOf(android.R.attr.state_enabled)    // Enabled
                Color.BLACK,     // The color for the Disabled state
                Color.RED        // The color for the Enabled state

document.getElementById(id).focus() is not working for firefox or chrome

Try location.href='#yourId'

Like this:

<button onclick="javascript:location.href='#yourId'">Show</button>

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]



you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          |        |
          1       10

How to view hierarchical package structure in Eclipse package explorer

Package Explorer / View Menu / Package Presentation... / Hierarchical

The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.

Parse an URL in JavaScript

I wrote a javascript url parsing library, URL.js, you can use it for this.


url.parse("").get.img_id === "33"

Psexec "run as (remote) admin"

Use psexec -s

The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.

Increment variable value by 1 ( shell programming)

You can try this :


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

All your settings are stored in the respective .config file.

The .settings file simply provides a strongly typed class for a set of settings that belong together, but the actual settings are stored in app.config or a .config file in your application.

If you add a .settings file, an app.config will be automatically added to house the settings if you don't already have one.

Conversion failed when converting the varchar value to data type int in sql

I got the same error message. In my case, it was due to not using quotes.

Although the column was supposed to have only numbers, it was a Varchar column, and one of the rows had a letter in it.

So I was doing this:

select * from mytable where myid = 1234

While I should be doing this:

select * from mytable where myid = '1234'

If the column had all numbers, the conversion would have worked, but not in this case.

Creating a blurring overlay view

If adds a dark blur view for tableView, this will beautifully make it:

tableView.backgroundColor = .clear
let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = tableView.bounds
blurEffectView.autoresizingMask = [.flexibleHeight, .flexibleWidth]

// Assigning blurEffectView to backgroundView instead of addSubview to tableView makes tableView cell not blocked by blurEffectView 
tableView.backgroundView = blurEffectView

How to keep :active css style after clicking an element

If you want to keep your links to look like they are :active class, you should define :visited class same as :active so if you have a links in .example then you do something like this:

a.example:active, a.example:visited {
/* Put your active state style code here */ }

The Link visited Pseudo Class is used to select visited links as says the name.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

add this at the top of file,

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Instead of explicitly defining the path to the interpreter as in /usr/bin/bash/, by using the env command, the interpreter is searched for and launched from wherever it is first found. This has both upsides and downsides

How to find the serial port number on Mac OS X?

Found the port esp32 was connected to by -

ls /dev/*

You would get a long list and you can find the port you need

Run reg command in cmd (bat file)?

You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)

Python/BeautifulSoup - how to remove all tags from an element?

Code to simply get the contents as text instead of html:

'html_text' parameter is the string which you will pass in this function to get the text

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_text, 'lxml')
text = soup.get_text()

How to print register values in GDB?

p $eax works as of GDB 7.7.1

As of GDB 7.7.1, the command you've tried works:

set $eax = 0
p $eax
# $1 = 0
set $eax = 1
p $eax
# $2 = 1

This syntax can also be used to select between different union members e.g. for ARM floating point registers that can be either floating point or integers:

p $s0.f
p $s0.u

From the docs:

Any name preceded by ‘$’ can be used for a convenience variable, unless it is one of the predefined machine-specific register names.


You can refer to machine register contents, in expressions, as variables with names starting with ‘$’. The names of registers are different for each machine; use info registers to see the names used on your machine.

But I haven't had much luck with control registers so far: OSDev 2012 || 2005 feature request || alt.lang.asm 2013!topic/alt.lang.asm/JC7YS3Wu31I

ARM floating point registers


How can I add a space in between two outputs?

Like this?

 System.out.println(Name + " " + Income);

Create numpy matrix filled with NaNs

Yet another possibility not yet mentioned here is to use NumPy tile:

a = numpy.tile(numpy.nan, (3, 3))

Also gives

array([[ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN]])

I don't know about speed comparison.

"Data too long for column" - why?

In my case this error occurred due to entering data a wrong type for example: if it is a long type column, i tried to enter in string type. so please check your data that you are entering and type are same or not

.append(), prepend(), .after() and .before()

append() & prepend() are for inserting content inside an element (making the content its child) while after() & before() insert content outside an element (making the content its sibling).

How to print all session variables currently set?

Not a simple way, no.

Let's say that by "active" you mean "hasn't passed the maximum lifetime" and hasn't been explicitly destroyed and that you're using the default session handler.

  • First, the maximum lifetime is defined as a php.ini config and is defined in terms of the last activity on the session. So the "expiry" mechanism would have to read the content of the sessions to determine the application-defined expiry.
  • Second, you'd have to manually read the sessions directory and read the files, whose format I don't even know they're in.

If you really need this, you must implement some sort of custom session handler. See session_set_save_handler.

Take also in consideration that you'll have no feedback if the user just closes the browser or moves away from your site without explciitly logging out. Depending on much inactivity you consider the threshold to deem a session "inactive", the number of false positives you'll get may be very high.

Get height of div with no height set in css

Can do this in jQuery. Try all options .height(), .innerHeight() or .outerHeight().

$('document').ready(function() {
    $('#right_div').css({'height': $('#left_div').innerHeight()});

Example Screenshot

enter image description here

Hope this helps. Thanks!!

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

       E.I_EmpName AS EMPNAME,
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
               ' ',
               '') AS WORKDATE,
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 WHERE E.I_EMPID <> '22'

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

Example using Hyperlink in WPF

Hope this help someone as well.

using System.Diagnostics;
using System.Windows.Documents;

namespace Helpers.Controls
    public class HyperlinkEx : Hyperlink
        protected override void OnClick()

            Process p = new Process()
                StartInfo = new ProcessStartInfo()
                    FileName = this.NavigateUri.AbsoluteUri

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

It takes some time to return results, easily many tens of seconds, but wmic works well and can be scripted:

wmic product where "Name like '%Word%'" get Name, Version, IdentifyingNumber


IdentifyingNumber                       Name                                      Version
{90140000-001B-0409-0000-0000000FF1CE}  Microsoft Office Word MUI (English) 2010  14.0.6029.1000

The IdentifingNumber is the ProductCode. I didn't see a property for UpgradeCode, but perhaps it might be buried under something else. See for many other examples, including uninstall:

wmic path win32_product where "name = 'HP Software Update'" call Uninstall

How to set custom favicon in Express?

If you want a solution that does not involve external files, and does not use express.static (for example, a super-light one file webserver and site) you can use serve-favicon and encode your favicon.ico file as Base64. Like this:

const favicon = require('serve-favicon');
const imgBuffer = new Buffer.from('IMAGE_AS_BASE64_STRING_GOES_HERE', 'base64');
// assuming app is already defined

Replace IMAGE_AS_BASE64_STRING_GOES_HERE with the result of encoding your favicon file as Base64. There are lots of sites that can do that online, have a search.

Note you may need to restart the server and/or browser to see it working on localhost, and a hard refresh/clear browser cache to see it working on the web.

Set initially selected item in Select list in Angular2

Okay, so I figured out what the problem was, and the approach I believe works best. In my case, because the two objects weren't identical from a Javascript perspective, as in: they may have shared the same values, but they were different actual objects, e.g. originalObject was instantiated entirely separately from objects which was essentially an array of reference data (to populate the dropdown).

I found that the approach that worked best for me was to compare a unique property of the objects, rather than directly compare the two entire objects. This comparison is done in the bound property selected:

<select [ngModel]="originalObject">
    <option *ngFor="let object of objects" [ngValue]="object" [selected]="object.uniqueId === originalObject.uniqueId">{{}}</option>

Does VBA have Dictionary Structure?

VBA does not have an internal implementation of a dictionary, but from VBA you can still use the dictionary object from MS Scripting Runtime Library.

Dim d
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "aaa"
d.Add "b", "bbb"
d.Add "c", "ccc"

If d.Exists("c") Then
    MsgBox d("c")
End If

How do I escape double quotes in attributes in an XML String in T-SQL?

Wouldn't that be &quot; in xml? i.e.

"hi &quot;mom&quot; lol" 

**edit: ** tested; works fine:

declare @xml xml

 set @xml = '<transaction><item value="hi &quot;mom&quot; lol" 
    ItemId="106"  ItemType="2"  instanceId="215923801"  dataSetId="1" /></transaction>'

select @xml.value('(//item/@value)[1]','varchar(50)')

How do I create/edit a Manifest file?

In Visual Studio 2019 WinForm Projects, it is available under

Project Properties -> Application -> View Windows Settings (button)

enter image description here invalid stream header: 7371007E

If you are sending multiple objects, it's often simplest to put them some kind of holder/collection like an Object[] or List. It saves you having to explicitly check for end of stream and takes care of transmitting explicitly how many objects are in the stream.

EDIT: Now that I formatted the code, I see you already have the messages in an array. Simply write the array to the object stream, and read the array on the server side.

Your "server read method" is only reading one object. If it is called multiple times, you will get an error since it is trying to open several object streams from the same input stream. This will not work, since all objects were written to the same object stream on the client side, so you have to mirror this arrangement on the server side. That is, use one object input stream and read multiple objects from that.

(The error you get is because the objectOutputStream writes a header, which is expected by objectIutputStream. As you are not writing multiple streams, but simply multiple objects, then the next objectInputStream created on the socket input fails to find a second header, and throws an exception.)

To fix it, create the objectInputStream when you accept the socket connection. Pass this objectInputStream to your server read method and read Object from that.

How do I calculate r-squared using Python and Numpy?

A very late reply, but just in case someone needs a ready function for this:



slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y)

as in @Adam Marples's answer.

Open new Terminal Tab from command line (Mac OS X)

Update: This answer gained popularity based on the shell function posted below, which still works as of OSX 10.10 (with the exception of the -g option).
However, a more fully featured, more robust, tested script version is now available at the npm registry as CLI ttab, which also supports iTerm2:

  • If you have Node.js installed, simply run:

    npm install -g ttab

    (depending on how you installed Node.js, you may have to prepend sudo).

  • Otherwise, follow these instructions.

  • Once installed, run ttab -h for concise usage information, or man ttab to view the manual.

Building on the accepted answer, below is a bash convenience function for opening a new tab in the current Terminal window and optionally executing a command (as a bonus, there's a variant function for creating a new window instead).

If a command is specified, its first token will be used as the new tab's title.

Sample invocations:

    # Get command-line help.
newtab -h
    # Simpy open new tab.
    # Open new tab and execute command (quoted parameters are supported).
newtab ls -l "$Home/Library/Application Support"
    # Open a new tab with a given working directory and execute a command;
    # Double-quote the command passed to `eval` and use backslash-escaping inside.
newtab eval "cd ~/Library/Application\ Support; ls"
    # Open new tab, execute commands, close tab.
newtab eval "ls \$HOME/Library/Application\ Support; echo Press a key to exit.; read -s -n 1; exit"
    # Open new tab and execute script.
newtab /path/to/someScript
    # Open new tab, execute script, close tab.
newtab exec /path/to/someScript
    # Open new tab and execute script, but don't activate the new tab.
newtab -G /path/to/someScript

CAVEAT: When you run newtab (or newwin) from a script, the script's initial working folder will be the working folder in the new tab/window, even if you change the working folder inside the script before invoking newtab/newwin - pass eval with a cd command as a workaround (see example above).

Source code (paste into your bash profile, for instance):

# Opens a new tab in the current Terminal window and optionally executes a command.
# When invoked via a function named 'newwin', opens a new Terminal *window* instead.
function newtab {

    # If this function was invoked directly by a function named 'newwin', we open a new *window* instead
    # of a new tab in the existing window.
    local funcName=$FUNCNAME
    local targetType='tab'
    local targetDesc='new tab in the active Terminal window'
    local makeTab=1
    case "${FUNCNAME[1]}" in
            targetDesc='new Terminal window'

    # Command-line help.
    if [[ "$1" == '--help' || "$1" == '-h' ]]; then
        cat <<EOF
    $funcName [-g|-G] [command [param1 ...]]

    Opens a $targetDesc and optionally executes a command.

    The new $targetType will run a login shell (i.e., load the user's shell profile) and inherit
    the working folder from this shell (the active Terminal tab).
    IMPORTANT: In scripts, \`$funcName\` *statically* inherits the working folder from the
    *invoking Terminal tab* at the time of script *invocation*, even if you change the
    working folder *inside* the script before invoking \`$funcName\`.

    -g (back*g*round) causes Terminal not to activate, but within Terminal, the new tab/window
      will become the active element.
    -G causes Terminal not to activate *and* the active element within Terminal not to change;
      i.e., the previously active window and tab stay active.

    NOTE: With -g or -G specified, for technical reasons, Terminal will still activate *briefly* when
    you create a new tab (creating a new window is not affected).

    When a command is specified, its first token will become the new ${targetType}'s title.
    Quoted parameters are handled properly.

    To specify multiple commands, use 'eval' followed by a single, *double*-quoted string
    in which the commands are separated by ';' Do NOT use backslash-escaped double quotes inside
    this string; rather, use backslash-escaping as needed.
    Use 'exit' as the last command to automatically close the tab when the command
    terminates; precede it with 'read -s -n 1' to wait for a keystroke first.

    Alternatively, pass a script name or path; prefix with 'exec' to automatically
    close the $targetType when the script terminates.

    $funcName ls -l "\$Home/Library/Application Support"
    $funcName eval "ls \\\$HOME/Library/Application\ Support; echo Press a key to exit.; read -s -n 1; exit"
    $funcName /path/to/someScript
    $funcName exec /path/to/someScript
        return 0

    # Option-parameters loop.
    while (( $# )); do
        case "$1" in
            --) # Explicit end-of-options marker.
                shift   # Move to next param and proceed with data-parameter analysis below.
            -*) # An unrecognized switch.
                echo "$FUNCNAME: PARAMETER ERROR: Unrecognized option: '$1'. To force interpretation as non-option, precede with '--'. Use -h or --h for help." 1>&2 && return 2
            *)  # 1st argument reached; proceed with argument-parameter analysis below.

    # All remaining parameters, if any, make up the command to execute in the new tab/window.

    local CMD_PREFIX='tell application "Terminal" to do script'

        # Command for opening a new Terminal window (with a single, new tab).
    local CMD_NEWWIN=$CMD_PREFIX    # Curiously, simply executing 'do script' with no further arguments opens a new *window*.
        # Commands for opening a new tab in the current Terminal window.
        # Sadly, there is no direct way to open a new tab in an existing window, so we must activate Terminal first, then send a keyboard shortcut.
    local CMD_ACTIVATE='tell application "Terminal" to activate'
    local CMD_NEWTAB='tell application "System Events" to keystroke "t" using {command down}'
        # For use with -g: commands for saving and restoring the previous application
    local CMD_SAVE_ACTIVE_APPNAME='tell application "System Events" to set prevAppName to displayed name of first process whose frontmost is true'
    local CMD_REACTIVATE_PREV_APP='activate application prevAppName'
        # For use with -G: commands for saving and restoring the previous state within Terminal
    local CMD_SAVE_ACTIVE_WIN='tell application "Terminal" to set prevWin to front window'
    local CMD_REACTIVATE_PREV_WIN='set frontmost of prevWin to true'
    local CMD_SAVE_ACTIVE_TAB='tell application "Terminal" to set prevTab to (selected tab of front window)'
    local CMD_REACTIVATE_PREV_TAB='tell application "Terminal" to set selected of prevTab to true'

    if (( $# )); then # Command specified; open a new tab or window, then execute command.
            # Use the command's first token as the tab title.
        local tabTitle=$1
        case "$tabTitle" in
            exec|eval) # Use following token instead, if the 1st one is 'eval' or 'exec'.
                tabTitle=$(echo "$2" | awk '{ print $1 }') 
            cd) # Use last path component of following token instead, if the 1st one is 'cd'
                tabTitle=$(basename "$2")
        local CMD_SETTITLE="tell application \"Terminal\" to set custom title of front window to \"$tabTitle\""
            # The tricky part is to quote the command tokens properly when passing them to AppleScript:
            # Step 1: Quote all parameters (as needed) using printf '%q' - this will perform backslash-escaping.
        local quotedArgs=$(printf '%q ' "$@")
            # Step 2: Escape all backslashes again (by doubling them), because AppleScript expects that.
        local cmd="$CMD_PREFIX \"${quotedArgs//\\/\\\\}\""
            # Open new tab or window, execute command, and assign tab title.
            # '>/dev/null' suppresses AppleScript's output when it creates a new tab.
        if (( makeTab )); then
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active tab after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_SAVE_ACTIVE_TAB" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" -e "$CMD_REACTIVATE_PREV_APP" -e "$CMD_REACTIVATE_PREV_TAB" >/dev/null
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" -e "$CMD_REACTIVATE_PREV_APP" >/dev/null
                osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" >/dev/null
        else # make *window*
            # Note: $CMD_NEWWIN is not needed, as $cmd implicitly creates a new window.
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active window after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_WIN" -e "$cmd" -e "$CMD_SETTITLE" -e "$CMD_REACTIVATE_PREV_WIN" >/dev/null
                    osascript -e "$cmd" -e "$CMD_SETTITLE" >/dev/null
                    # Note: Even though we do not strictly need to activate Terminal first, we do it, as assigning the custom title to the 'front window' would otherwise sometimes target the wrong window.
                osascript -e "$CMD_ACTIVATE" -e "$cmd" -e "$CMD_SETTITLE" >/dev/null
    else    # No command specified; simply open a new tab or window.
        if (( makeTab )); then
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active tab after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_SAVE_ACTIVE_TAB" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$CMD_REACTIVATE_PREV_APP" -e "$CMD_REACTIVATE_PREV_TAB" >/dev/null
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$CMD_REACTIVATE_PREV_APP" >/dev/null
                osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" >/dev/null
        else # make *window*
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active window after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_WIN" -e "$CMD_NEWWIN" -e "$CMD_REACTIVATE_PREV_WIN" >/dev/null
                    osascript -e "$CMD_NEWWIN" >/dev/null
                    # Note: Even though we do not strictly need to activate Terminal first, we do it so as to better visualize what is happening (the new window will appear stacked on top of an existing one).
                osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWWIN" >/dev/null


# Opens a new Terminal window and optionally executes a command.
function newwin {
    newtab "$@" # Simply pass through to 'newtab', which will examine the call stack to see how it was invoked.

The remote end hung up unexpectedly while git cloning

Obs.: Changing http.postBuffer might also require to set up the Nginx configuration file for gitlab to accept larger body sizes for the client, by tuning the value of client_max_body_size.

However, there is a workaround if you have access to the Gitlab machine or to a machine in its network, and that is by making use of git bundle.

  1. go to your git repository on the source machine
  2. run git bundle create my-repo.bundle --all
  3. transfer (eg., with rsync) the my-repo.bundle file to the destination machine
  4. on the destination machine, run git clone my-repo.bundle
  5. git remote set-url origin "path/to/your/repo.git"
  6. git push

All the best!

How to check if a Constraint exists in Sql server?

SELECT as Tabla, as Restriccion, 
        restriccion.type as Tipo, 
        restriccion.type_desc as Tipo_Desc
FROM {DATABASE_NAME}.sys.objects tabla 

INNER JOIN {DATABASE_NAME}.sys.objects restriccion

ON tabla.object_id = restriccion.parent_object_id

WHERE tabla.type = 'U' - Solo tablas creadas por el usuario.

AND restriccion.type = 'UQ' --Tipo de Restriccion UNIQUE

ORDER BY, restriccion.type_desc                

Call JavaScript function from C#

If you want to call JavaScript function in C#, this will help you:

public string functionname(arg)
    if (condition)
        Page page = HttpContext.Current.CurrentHandler as Page;
            "<script type='text/javascript'>functionname1(" + arg1 + ",'" + arg2 + "');</script>");

Detecting which UIButton was pressed in a UITableView

// how do I know which button sent this message?
// processing button press for this row requires an indexPath.

Pretty straightforward actually:

- (void)buttonPressedAction:(id)sender
    UIButton *button = (UIButton *)sender;
    CGPoint rowButtonCenterInTableView = [[rowButton superview] toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rowButtonCenterInTableView];
    MyTableViewItem *rowItem = [self.itemsArray objectAtIndex:indexPath.row];
    // Now you're good to go.. do what the intention of the button is, but with
    // the context of the "row item" that the button belongs to
    [self performFooWithItem:rowItem];

Working well for me :P

if you want to adjust your target-action setup, you can include the event parameter in the method, and then use the touches of that event to resolve the coordinates of the touch. The coordinates still need to be resolved in the touch view bounds, but that may seem easier for some people.

JavaScript Promises - reject vs. throw

The difference is ternary operator

  • You can use
return condition ? someData : Promise.reject(new Error('not OK'))
  • You can't use
return condition ? someData  : throw new Error('not OK')

Passing parameter to controller from route in laravel

This is what you need in 1 line of code.

Route::get('/groups/{groupId}', 'GroupsController@getShow');

Suggestion: Use CamelCase as opposed to underscores, try & follow PSR-* guidelines.

Hope it helps.

Comparing two byte arrays in .NET

User gil suggested unsafe code which spawned this solution:

// Copyright (c) 2008-2013 Hafthor Stefansson
// Distributed under the MIT/X11 software license
// Ref:
static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) {
  if(a1==a2) return true;
  if(a1==null || a2==null || a1.Length!=a2.Length)
    return false;
  fixed (byte* p1=a1, p2=a2) {
    byte* x1=p1, x2=p2;
    int l = a1.Length;
    for (int i=0; i < l/8; i++, x1+=8, x2+=8)
      if (*((long*)x1) != *((long*)x2)) return false;
    if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; }
    if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; }
    if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false;
    return true;

which does 64-bit based comparison for as much of the array as possible. This kind of counts on the fact that the arrays start qword aligned. It'll work if not qword aligned, just not as fast as if it were.

It performs about seven timers faster than the simple for loop. Using the J# library performed equivalently to the original for loop. Using .SequenceEqual runs around seven times slower; I think just because it is using IEnumerator.MoveNext. I imagine LINQ-based solutions being at least that slow or worse.

How can I remove a button or make it invisible in Android?

First make the button invisible in xml file.Then set button visible in java code if needed.

Button resetButton=(Button)findViewById(;
resetButton.setVisibility(View.VISIBLE); //To set visible



How to revert to origin's master branch's version of file

I've faced same problem and came across to this thread but my problem was with upstream. Below git command worked for me.


git checkout {remoteName}/{branch} -- {../path/file.js}


git checkout upstream/develop -- public/js/index.js

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

@EH_warch You need to use the Complete callback to generate your base64:

onAnimationComplete: function(){

If you see a white image, it means you called the toBase64Image before it finished rendering.

Good examples using java.util.logging

java.util.logging keeps you from having to tote one more jar file around with your application, and it works well with a good Formatter.

In general, at the top of every class, you should have:

private static final Logger LOGGER = Logger.getLogger( ClassName.class.getName() );

Then, you can just use various facilities of the Logger class.

Use Level.FINE for anything that is debugging at the top level of execution flow:

LOGGER.log( Level.FINE, "processing {0} entries in loop", list.size() );

Use Level.FINER / Level.FINEST inside of loops and in places where you may not always need to see that much detail when debugging basic flow issues:

LOGGER.log( Level.FINER, "processing[{0}]: {1}", new Object[]{ i, list.get(i) } );

Use the parameterized versions of the logging facilities to keep from generating tons of String concatenation garbage that GC will have to keep up with. Object[] as above is cheap, on the stack allocation usually.

With exception handling, always log the complete exception details:

try {
    ...something that can throw an ignorable exception
} catch( Exception ex ) {
    LOGGER.log( Level.SEVERE, ex.toString(), ex );

I always pass ex.toString() as the message here, because then when I "grep -n" for "Exception" in log files, I can see the message too. Otherwise, it is going to be on the next line of output generated by the stack dump, and you have to have a more advanced RegEx to match that line too, which often gets you more output than you need to look through.

Implement paging (skip / take) functionality with this query

In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.


select * from table order by [some_column] 
offset 10 rows
FETCH NEXT 10 rows only

And you can't use the "TOP" keyword when doing this.

You can learn more here:

How to read a value from the Windows registry

Since Windows >=Vista/Server 2008, RegGetValue is available, which is a safer function than RegQueryValueEx. No need for RegOpenKeyEx, RegCloseKey or NUL termination checks of string values (REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ).

#include <iostream>
#include <string>
#include <exception>
#include <windows.h>

/*! \brief                          Returns a value from HKLM as string.
    \exception  std::runtime_error  Replace with your error handling.
std::wstring GetStringValueFromHKLM(const std::wstring& regSubKey, const std::wstring& regValue)
    size_t bufferSize = 0xFFF; // If too small, will be resized down below.
    std::wstring valueBuf; // Contiguous buffer since C++11.
    auto cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
    auto rc = RegGetValueW(
    while (rc == ERROR_MORE_DATA)
        // Get a buffer that is big enough.
        cbData /= sizeof(wchar_t);
        if (cbData > static_cast<DWORD>(bufferSize))
            bufferSize = static_cast<size_t>(cbData);
            bufferSize *= 2;
            cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
        rc = RegGetValueW(
    if (rc == ERROR_SUCCESS)
        cbData /= sizeof(wchar_t);
        valueBuf.resize(static_cast<size_t>(cbData - 1)); // remove end null character
        return valueBuf;
        throw std::runtime_error("Windows system error code: " + std::to_string(rc));

int main()
    std::wstring regSubKey;
#ifdef _WIN64 // Manually switching between 32bit/64bit for the example. Use dwFlags instead.
    regSubKey = L"SOFTWARE\\WOW6432Node\\Company Name\\Application Name\\";
    regSubKey = L"SOFTWARE\\Company Name\\Application Name\\";
    std::wstring regValue(L"MyValue");
    std::wstring valueFromRegistry;
        valueFromRegistry = GetStringValueFromHKLM(regSubKey, regValue);
    catch (std::exception& e)
        std::cerr << e.what();
    std::wcout << valueFromRegistry;

Its parameter dwFlags supports flags for type restriction, filling the value buffer with zeros on failure (RRF_ZEROONFAILURE) and 32/64bit registry access (RRF_SUBKEY_WOW6464KEY, RRF_SUBKEY_WOW6432KEY) for 64bit programs.

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

Prevent typing non-numeric in input type number

Please note that e.which, e.keyCode and e.charCode are deprecated:

I prefer e.key:

document.querySelector("input").addEventListener("keypress", function (e) {
    var allowedChars = '0123456789.';
    function contains(stringValue, charValue) {
        return stringValue.indexOf(charValue) > -1;
    var invalidKey = e.key.length === 1 && !contains(allowedChars, e.key)
            || e.key === '.' && contains(, '.');
    invalidKey && e.preventDefault();});

This function doesn't interfere with control codes in Firefox (Backspace, Tab, etc) by checking the string length: e.key.length === 1.

It also prevents duplicate dots at the beginning and between the digits: e.key === '.' && contains(, '.')

Unfortunately, it doesn't prevent multiple dots at the end: 234....

It seems there is no way to cope with it.

Update data on a page without refreshing

You can read about jQuery Ajax from official jQuery Site:

If you don't want to use any click event then you can set timer for periodically update.

Below code may be help you just example.

function update() {
  $.get("response.php", function(data) {
    window.setTimeout(update, 10000);

Above function will call after every 10 seconds and get content from response.php and update in #some_div.

Shortcut to exit scale mode in VirtualBox

I arrived at this page looking to turn off scale mode for good, so I figured I would share what I found:

VBoxManage setextradata global GUI/Input/MachineShortcuts "ScaleMode=None"

Running this in my host's terminal worked like a charm for me.


Delete item from array and shrink array

You can't resize the array, per se, but you can create a new array and efficiently copy the elements from the old array to the new array using some utility function like this:

public static int[] removeElement(int[] original, int element){
    int[] n = new int[original.length - 1];
    System.arraycopy(original, 0, n, 0, element );
    System.arraycopy(original, element+1, n, element, original.length - element-1);
    return n;

A better approach, however, would be to use an ArrayList (or similar List structure) to store your data and then use its methods to remove elements as needed.

JQuery ajax call default timeout value

The XMLHttpRequest.timeout property represents a number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout. An important note the timeout shouldn't be used for synchronous XMLHttpRequests requests, used in a document environment or it will throw an InvalidAccessError exception. You may not use a timeout for synchronous requests with an owning window.

IE10 and 11 do not support synchronous requests, with support being phased out in other browsers too. This is due to detrimental effects resulting from making them.

More info can be found here.

How can I check if a var is a string in JavaScript?

You were close:

if (typeof a_string === 'string') {
    // this is a string

On a related note: the above check won't work if a string is created with new String('hello') as the type will be Object instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.

Selecting text in an element (akin to highlighting with your mouse)

Tim's method works perfectly for my case - selecting the text in a div for both IE and FF after I replaced the following statement:


with the following:


The text in the div is selected by clicking it with the following jQuery function:

$(function () {
    $("#divFoo").click(function () {

Regular expression to stop at first match

Use of Lazy quantifiers ? with no global flag is the answer.


enter image description here

If you had global flag /g then, it would have matched all the lowest length matches as below. enter image description here

How to check if the request is an AJAX request with PHP

Set a session variable for every page on your site (actual pages not includes or rpcs) that contains the current page name, then in your Ajax call pass a nonce salted with the $_SERVER['SCRIPT_NAME'];

function create_nonce($optional_salt='')
    return hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']);
$_SESSION['current_page'] = $_SERVER['SCRIPT_NAME'];

  <input name="formNonce" id="formNonce" type="hidden" value="<?=create_nonce($_SERVER['SCRIPT_NAME']);?>">
  <label class="form-group">
    Login<br />
    <input name="userName" id="userName" type="text" />
  <label class="form-group">
    Password<br />
    <input name="userPassword" id="userPassword" type="password" />
  <button type="button" class="btnLogin">Sign in</button>
<script type="text/javascript">
    $("form.login button").on("click", function() {

    function authorize (authUser, authPassword, authNonce) {
          type: "POST",
          url: "/inc/rpc.php",
          dataType: "json",
          data: "userID="+authUser+"&password="+authPassword+"&nonce="+authNonce
        .success(function( msg ) {
            //some successful stuff

Then in the rpc you are calling test the nonce you passed, if it is good then odds are pretty great that your rpc was legitimately called:

function check_nonce($nonce, $optional_salt='')
    $lasthour = date("G")-1<0 ? date('Ymd').'23' : date("YmdG")-1;
    if (hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce || 
        hash_hmac('sha256', session_id().$optional_salt, $lasthour.'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce)
        return true;
    } else {
        return false;

$ret = array();
header('Content-Type: application/json');
if (check_nonce($_POST['nonce'], $_SESSION['current_page']))
    $ret['nonce_check'] = 'passed';
} else {
    $ret['nonce_check'] = 'failed';
echo json_encode($ret);

edit: FYI the way I have it set the nonce is only good for an hour and change, so if they have not refreshed the page doing the ajax call in the last hour or 2 the ajax request will fail.

iPhone Debugging: How to resolve 'failed to get the task for process'?

I just changed my bundleIdentifier name, that seemed to do the trick.

Dynamically create an array of strings with malloc

#define ID_LEN 5
char **orderedIds;
int i;
int variableNumberOfElements = 5; /* Hard coded here */

orderedIds = (char **)malloc(variableNumberOfElements * (ID_LEN + 1) * sizeof(char));


How to execute a program or call a system command from Python

Using the Popen function of the subprocess Python module is the simplest way of running Linux commands. In that, the Popen.communicate() function will give your commands output. For example

import subprocess

process = subprocess.Popen(..)   # Pass command and arguments to the function
stdout, stderr = process.communicate()   # Get command output and error

Get item in the list in Scala?

Please use parenthesis () to access the list elements list_name(index)

C++: How to round a double to an int?

Casting is not a mathematical operation and doesn't behave as such. Try

int y = (int)round(x);

Get google map link with latitude/longitude

Use View mode returns a map with no markers or directions.

The example below uses the optional maptype parameter to display a satellite view of the map.

Print a list in reverse order with range()?

No sense to use reverse because the range method can return reversed list.

When you have iteration over n items and want to replace order of list returned by range(start, stop, step) you have to use third parameter of range which identifies step and set it to -1, other parameters shall be adjusted accordingly:

  1. Provide stop parameter as -1(it's previous value of stop - 1, stop was equal to 0).
  2. As start parameter use n-1.

So equivalent of range(n) in reverse order would be:

n = 10
print range(n-1,-1,-1) 
#[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

What do the makefile symbols $@ and $< mean?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.
For example:

hello.o: hello.c hello.h
         gcc -c $< -o $@

Here, hello.o is the output file. This is what $@ expands to. The first dependency is hello.c. That's what $< expands to.

The -c flag generates the .o file; see man gcc for a more detailed explanation. The -o specifies the output file to create.

For further details, you can read this article about Linux Makefiles.

Also, you can check the GNU make manuals. It will make it easier to make Makefiles and to debug them.

If you run this command, it will output the makefile database:

make -p 

JPA entity without id

I know that JPA entities must have primary key but I can't change database structure due to reasons beyond my control.

More precisely, a JPA entity must have some Id defined. But a JPA Id does not necessarily have to be mapped on the table primary key (and JPA can somehow deal with a table without a primary key or unique constraint).

Is it possible to create JPA (Hibernate) entities that will be work with database structure like this?

If you have a column or a set of columns in the table that makes a unique value, you can use this unique set of columns as your Id in JPA.

If your table has no unique columns at all, you can use all of the columns as the Id.

And if your table has some id but your entity doesn't, make it an Embeddable.

Simple and fast method to compare images for similarity

Can the screenshot or icon be transformed (scaled, rotated, skewed ...)? There are quite a few methods on top of my head that could possibly help you:

  • Simple euclidean distance as mentioned by @carlosdc (doesn't work with transformed images and you need a threshold).
  • (Normalized) Cross Correlation - a simple metrics which you can use for comparison of image areas. It's more robust than the simple euclidean distance but doesn't work on transformed images and you will again need a threshold.
  • Histogram comparison - if you use normalized histograms, this method works well and is not affected by affine transforms. The problem is determining the correct threshold. It is also very sensitive to color changes (brightness, contrast etc.). You can combine it with the previous two.
  • Detectors of salient points/areas - such as MSER (Maximally Stable Extremal Regions), SURF or SIFT. These are very robust algorithms and they might be too complicated for your simple task. Good thing is that you do not have to have an exact area with only one icon, these detectors are powerful enough to find the right match. A nice evaluation of these methods is in this paper: Local invariant feature detectors: a survey.

Most of these are already implemented in OpenCV - see for example the cvMatchTemplate method (uses histogram matching): The salient point/area detectors are also available - see OpenCV Feature Detection.

How do you set autocommit in an SQL Server session?

Autocommit is SQL Server's default transaction management mode. (SQL 2000 onwards)

Ref: Autocommit Transactions

How to return a boolean method in java?

You're allowed to have more than one return statement, so it's legal to write

if (some_condition) {
  return true;
return false;

It's also unnecessary to compare boolean values to true or false, so you can write

if (verifyPwd())  {
  // do_task

Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.

boolean success = true;

if (some_condition) {
  // Handle the condition.
  success = false;
} else if (some_other_condition) {
  // Handle the other condition.
  success = false;
if (another_condition) {
  // Handle the third condition.

// Do some more critical things.

return success;

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

There are possible solutions here:,64808,254785#msg-254785 and here:,23138,254786#msg-254786

All of these are config settings. In my case I have two computers with everything in XAMPP synced. On the other computer phpMyAdmin did start normally. So the problem in my case seemed to be with the specific computer, not the config files. Stopping firewall didn't help.

Finally, more or less by accident, I bumped into the file:


Doubleclicking that file miraculously gave me back PhpMyAdmin. Posted here in case anyone might be helped by this too.

In Visual Basic how do you create a block comment

There's not a way as of 11/2012, HOWEVER

Highlight Text (In visual

ctrl + k + c, ctrl + k + u

Will comment / uncomment, respectively

Access denied for user 'test'@'localhost' (using password: YES) except root user


CREATE USER 'golden'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'golden'@'localhost';

Or even better use: mysql_setpermission to create the user

Create a Maven project in Eclipse complains "Could not resolve archetype"

I find it solution

We can see the origin of the problem : Connection refused: connect

I have already do this :

1) Window -> Preferences -> General -> Network Connections. I put in Manual with the url and port of my proxy for HTTP protocol. It works because before this, Spring Tool Suite did not want to update. After, it's okay.

2) Window -> Preferences -> Maven -> User Settings. In Global Settings, is empty. In User Settings, I put the path to settings.xml. In this file, i have :

enter image description here

Change / Add syntax highlighting for a language in Sublime 2/3

Syntax highlighting is controlled by the theme you use, accessible through Preferences -> Color Scheme. Themes highlight different keywords, functions, variables, etc. through the use of scopes, which are defined by a series of regular expressions contained in a .tmLanguage file in a language's directory/package. For example, the JavaScript.tmLanguage file assigns the scopes source.js and variable.language.js to the this keyword. Since Sublime Text 3 is using the .sublime-package zip file format to store all the default settings it's not very straightforward to edit the individual files.

Unfortunately, not all themes contain all scopes, so you'll need to play around with different ones to find one that looks good, and gives you the highlighting you're looking for. There are a number of themes that are included with Sublime Text, and many more are available through Package Control, which I highly recommend installing if you haven't already. Make sure you follow the ST3 directions.

As it so happens, I've developed the Neon Color Scheme, available through Package Control, that you might want to take a look at. My main goal, besides trying to make a broad range of languages look as good as possible, was to identify as many different scopes as I could - many more than are included in the standard themes. While the JavaScript language definition isn't as thorough as Python's, for example, Neon still has a lot more diversity than some of the defaults like Monokai or Solarized.

jQuery highlighted with Neon Theme

I should note that I used @int3h's Better JavaScript language definition for this image instead of the one that ships with Sublime. It can be installed via Package Control.


Of late I've discovered another JavaScript replacement language definition - JavaScriptNext - ES6 Syntax. It has more scopes than the base JavaScript or even Better JavaScript. It looks like this on the same code:


Also, since I originally wrote this answer, @skuroda has released PackageResourceViewer via Package Control. It allows you to seamlessly view, edit and/or extract parts of or entire .sublime-package packages. So, if you choose, you can directly edit the color schemes included with Sublime.


With the release of nearly all of the default packages on Github, changes have been coming fast and furiously. The old JS syntax has been completely rewritten to include the best parts of JavaScript Next ES6 Syntax, and now is as fully ES6-compatible as can be. A ton of other changes have been made to cover corner and edge cases, improve consistency, and just overall make it better. The new syntax has been included in the (at this time) latest dev build 3111.

If you'd like to use any of the new syntaxes with the current beta build 3103, simply clone the Github repo someplace and link the JavaScript (or whatever language(s) you want) into your Packages directory - find it on your system by selecting Preferences -> Browse Packages.... Then, simply do a git pull in the original repo directory from time to time to refresh any changes, and you can enjoy the latest and greatest! I should note that the repo uses the new .sublime-syntax format instead of the old .tmLanguage one, so they will not work with ST3 builds prior to 3084, or with ST2 (in both cases, you should have upgraded to the latest beta or dev build anyway).

I'm currently tweaking my Neon Color Scheme to handle all of the new scopes in the new JS syntax, but most should be covered already.

Share link on Google+

As of July 25, 2011, the answer is no.

I have looked through their Javascript and it seems they don't want anyone directly accessing their api for +1 at the moment.

The Javascript that does all of the work for the +1 button is here:

If you run it through a Javascript cleanup program you can tell that they have obfuscated their code with various functions that only start with letters and constantly refer back to themselves and do cryptic things.

I figure in the next couple of weeks or moths they will release a link based sharing api due to the fact that we will need this for sharing from flash and other web based formats that don't rely on pure html and js.

HTML "overlay" which allows clicks to fall through to elements behind it

Add pointer-events: none; to the overlay.

Original answer: My suggestion would be that you could capture the click event with the overlay, hide the overlay, then refire the click event, then display the overlay again. I'm not sure if you'd get a flicker effect though.

[Update] Exactly this problem and exactly my solution just appeared in this post: "Forwarding Mouse Events Through Layers". I know its probably a little late for the OP, but for the sake of somebody having this problem in the future, I though I would include it.

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Just to add to yamen's answer, which is perfect for images but not so much for text.

If you are trying to use this to scale text, like say a Word document (which is in this case in bytes from Word Interop), you will need to make a few modifications or you will get giant bars on the side.

May not be perfect but works for me!

using (MemoryStream ms = new MemoryStream(wordBytes))
    float width = 3840;
    float height = 2160;
    var brush = new SolidBrush(Color.White);

    var rawImage = Image.FromStream(ms);
    float scale = Math.Min(width / rawImage.Width, height / rawImage.Height);
    var scaleWidth  = (int)(rawImage.Width  * scale);
    var scaleHeight = (int)(rawImage.Height * scale);
    var scaledBitmap = new Bitmap(scaleWidth, scaleHeight);

    Graphics graph = Graphics.FromImage(scaledBitmap);
    graph.InterpolationMode = InterpolationMode.High;
    graph.CompositingQuality = CompositingQuality.HighQuality;
    graph.SmoothingMode = SmoothingMode.AntiAlias;
    graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
    graph.DrawImage(rawImage, new Rectangle(0, 0 , scaleWidth, scaleHeight));

    scaledBitmap.Save(fileName, ImageFormat.Png);
    return scaledBitmap;

Is using 'var' to declare variables optional?

Consider this question asked at StackOverflow today:

Simple Javascript question

A good test and a practical example is what happens in the above scenario...
The developer used the name of the JavaScript function in one of his variables.

What's the problem with the code?
The code only works the first time the user clicks the button.

What's the solution?
Add the var keyword before the variable name.

Iif equivalent in C#

It's limited in that you can't put statements in there. You can only put values(or things that return/evaluate to values), to return

This works ('a' is a static int within class Blah)


(round brackets are impicitly between the equals and the question mark).

This doesn't work.

Blah.a = Blah.a < 4 ? Console.WriteLine("asdf") : Console.WriteLine("34er");
Blah.a = Blah.a < 4 ? MessageBox.Show("asdf") : MessageBox.Show("34er");

So you can only use the c# ternary operator for returning values. So it's not quite like a shortened form of an if. Javascript and perhaps some other languages let you put statements in there.

How to substring in jquery

No jQuery needed! Just use the substring method:

var gorge = name.substring(4);

Or if the text you want to remove isn't static:

var name = 'nameGorge';
var toRemove = 'name';
var gorge = name.replace(toRemove,'');

How do I debug jquery AJAX calls?

Make your JQuery call more robust by adding success and error callbacks like this:

 $('#ChangePermission').click(function() {
         url: 'change_permission.php',
         type: 'POST',
         data: {
             'user': document.GetElementById("user").value,
             'perm': document.GetElementById("perm").value
         success: function(result) { //we got the response
             alert('Successfully called');
         error: function(jqxhr, status, exception) {
             alert('Exception:', exception);

How to Specify Eclipse Proxy Authentication Credentials?

If you have still problems, try deactivating ("Clear") SOCKS

see: "I believe the reason for this is because it uses the SOCKS proxy instead of the HTTP proxy if SOCKS is configured."

Https to http redirect using htaccess

You can use the following rule to redirect from https to http :

 RewriteEngine On

RewriteCond %{HTTPS} ^on$
RewriteRule ^(.*)$$1 [NC,L,R]

Explanation :

RewriteCond %{HTTPS} ^on$

Checks if the HTTPS is on (Request is made using https)


RewriteRule ^(.*)$$1 [NC,L,R]

Redirect any request ( to .

  • $1 is part of the regex in RewriteRule pattern, it contains whatever value was captured in (.+) , in this case ,it captures the full request_uri everything after the domain name.

  • [NC,L,R] are the flags, NC makes the uri case senstive, you can use both uppercase or lowercase letters in the request.

L flag tells the server to stop proccessing other rules if the currunt rule has matched, it is important to use the L flag to avoid rule confliction when you have more then on rules in a block.

R flag is used to make an external redirection.

Unable to make the session state request to the session state server

If you need to change HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection to 1, remember to restart the state service after you change the parameter.

DataGridView checkbox column - value and functionality

If your column has been already created due to binding with a recordset of BIT type, the type of the column will be text anyway. The solution I have found is to remove that column and replace it with a DataGridViewCheckBoxColumn having the same binding data.

DataGridViewColumn oldCol = dgViewCategory.Columns["mycolumn"];
int chkIdx = oldCol.Index;
DataGridViewCheckBoxColumn chkCol = new DataGridViewCheckBoxColumn();
chkCol.HeaderText = oldCol.HeaderText;
chkCol.FalseValue = "False";
chkCol.TrueValue = "True";
chkCol.DataPropertyName = oldCol.DataPropertyName;
chkCol.Name = oldCol.Name;
dgViewCategory.Columns.Insert(chkIdx, chkCol);

Render basic HTML view?

If you're using express@~3.0.0 change the line below from your example:

app.use(express.staticProvider(__dirname + '/public'));

to something like this:

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

I made it as described on express api page and it works like charm. With that setup you don't have to write additional code so it becomes easy enough to use for your micro production or testing.

Full code listed below:

var express = require('express');
var app = express.createServer();

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {

app.listen(8080, '')

Unicode character as bullet for list-item in CSS

Using Text As Bullets

Use li:before with an escaped Hex HTML Entity (or any plain text).


My example will produce lists with check marks as bullets.


ul {
    list-style: none;
    padding: 0px;

ul li:before
    content: '\2713';
    margin: 0 1em;    /* any design */

Browser Compatibility

Haven't tested myself, but it should be supported as of IE8. At least that's what quirksmode & css-tricks say.

You can use conditional comments to apply older/slower solutions like images, or scripts. Better yet, use both with <noscript> for the images.


<!--[if lt IE 8]>

About background images

Background images are indeed easy to handle, but...

  1. Browser support for background-size is actually only as of IE9.
  2. HTML text colors and special (crazy) fonts can do a lot, with less HTTP requests.
  3. A script solution can just inject the HTML Entity, and let the same CSS do the work.
  4. A good resetting CSS code might make list-style (the more logical choice) easier.


What is the yield keyword used for in C#?

One major point about Yield keyword is Lazy Execution. Now what I mean by Lazy Execution is to execute when needed. A better way to put it is by giving an example

Example: Not using Yield i.e. No Lazy Execution.

public static IEnumerable<int> CreateCollectionWithList()
    var list =  new List<int>();

    return list;

Example: using Yield i.e. Lazy Execution.

public static IEnumerable<int> CreateCollectionWithYield()
    yield return 10;
    for (int i = 0; i < 3; i++) 
        yield return i;

    yield return 20;

Now when I call both methods.

var listItems = CreateCollectionWithList();
var yieldedItems = CreateCollectionWithYield();

you will notice listItems will have a 5 items inside it (hover your mouse on listItems while debugging). Whereas yieldItems will just have a reference to the method and not the items. That means it has not executed the process of getting items inside the method. A very efficient a way of getting data only when needed. Actual implementation of yield can seen in ORM like Entity Framework and NHibernate etc.

Changing CSS Values with Javascript

I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.

function css(selector,property,value)
    try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }

Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

Print to standard printer from Python?

I find this to be the superior solution, at least when dealing with web applications. The idea is this: convert the HTML page to a PDF document and send that to a printer via gsprint.

Even though gsprint is no longer in development, it works really, really well. You can choose the printer and the page orientation and size among several other options.

I convert the web page to PDF using Puppeteer, Chrome's headless browser. But you need to pass in the session cookie to maintain credentials.

Location of the android sdk has not been setup in the preferences in mac os?

Simply create this folder:


and then from Window -> Preferences -> Android, put this path:


Do a "git export" (like "svn export")?

I needed this for a deploy script and I couldn't use any of the above mentioned approaches. Instead I figured out a different solution:

[ $# -eq 2 ] || echo "USAGE $0 REPOSITORY DESTINATION" && exit 1
TMPNAME="/tmp/$(basename $REPOSITORY).$$"
rm -rf $TMPNAME/.git
rm -rf $TMPNAME

Calculate average in java

public class MainTwo{
    public static void main(String[] arguments) {
        double[] Average = new double[5];
        Average[0] = 4;
        Average[1] = 5;
        Average[2] = 2;
        Average[3] = 4;
        Average[4] = 5;
        double sum = 0;
        if (Average.length > 0) {
            for (int x = 0; x < Average.length; x++) {
            System.out.println("Sum is " + sum);
            System.out.println("Average is " + sum/Average.length);

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

This project should be helpful - maps touch events to click events in a way that allows jQuery UI to work on iPad and iPhone without any changes. Just add the JS to any existing project.

Using Python 3 in virtualenv

Python now comes with its own implementation of virtual environment, by the name of "venv". I would suggest using that, instead of virtualenv.

Quoting from venv - docs,

Deprecated since version 3.6: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6.

Changed in version 3.5: The use of venv is now recommended for creating virtual environments.

For windows, to initiate venv on some project, open cmd:

python -m venv "c:\path\to\myenv"

(Would suggest using double quote around directory path if it contains any spaces. Ex: "C:/My Dox/Spaced Directory/Something")

Once venv is set up, you will see some new folders inside your project directory. One of them would be "Scripts".

To activate or invoke venv you need:

C:\> <venv>\Scripts\activate.bat

You can deactivate a virtual environment by typing “deactivate” in your shell. With this, you are now ready to install your project specific libraries, which will reside under the folder "Lib".

================================ Edit 1 ==================================== The scenario which will be discussed below is not what originally asked, just adding this in case someone use vscode with python extension

In case, you use vs code with its python extension, you might face an issue with its pylint which points to the global installation. In this case, pylint won't be able to see the modules that are installed in your virtual environment and hence will show errors while importing.

Here is a simple method to get past this.

cd Workspace\Scripts
code .

We are basically activating the environment first and then invoking vs-code so that pylint starts within the environment and can see all local packages.

css display table cell requires percentage width

You just need to add 'table-layout: fixed;'

.table {
   display: table;
   height: 100px;
   width: 100%;
   table-layout: fixed;

How to fix syntax error, unexpected T_IF error in php?

PHP parser errors take some getting used to; if it complains about an unexpected 'something' at line X, look at line X-1 first. In this case it will not tell you that you forgot a semi-colon at the end of the previous line , instead it will complain about the if that comes next.

You'll get used to it :)

Code for best fit straight line of a scatter plot in python

from sklearn.linear_model import LinearRegression

X, Y = x.reshape(-1,1), y.reshape(-1,1)
plt.plot( X, LinearRegression().fit(X, Y).predict(X) )

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

Increment and decrement by 10.

inc(x) <- 10 

dec(x) <- 10

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

Found the script below in this github issue. Works great for me.

#!/usr/bin/env ruby
port = ARGV.first || 3000
system("sudo echo kill-server-on #{port}")

pid = `sudo lsof -iTCP -sTCP:LISTEN -n -P | grep #{port} | awk '{ print $2 }' | head -n 1`.strip
puts "PID: #{pid}"
`kill -9 #{pid}` unless pid.empty?

You can either run it in irb or inside a ruby file.

For the latter, create server_killer.rb then run it with ruby server_killer.rb

How do I count unique items in field in Access query?

Try this

SELECT Count(*) AS N

Read this for more info.

Can I map a hostname *and* a port with /etc/hosts?

No, that's not possible. The port is not part of the hostname, so it has no meaning in the hosts-file.

Why are my PowerShell scripts not running?


Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

Always use the above command to enable to executing PowerShell in the current session.

How can I sort a std::map first by value, then by key?

EDIT: The other two answers make a good point. I'm assuming that you want to order them into some other structure, or in order to print them out.

"Best" can mean a number of different things. Do you mean "easiest," "fastest," "most efficient," "least code," "most readable?"

The most obvious approach is to loop through twice. On the first pass, order the values:

if(current_value > examined_value)
    current_value = examined_value
    (and then swap them, however you like)

Then on the second pass, alphabetize the words, but only if their values match.

if(current_value == examined_value)
    (alphabetize the two)

Strictly speaking, this is a "bubble sort" which is slow because every time you make a swap, you have to start over. One "pass" is finished when you get through the whole list without making any swaps.

There are other sorting algorithms, but the principle would be the same: order by value, then alphabetize.

How can I create a Java method that accepts a variable number of arguments?

The following will create a variable length set of arguments of the type of string:

print(String arg1, String... arg2)

You can then refer to arg2 as an array of Strings. This is a new feature in Java 5.

Submitting a form on 'Enter' with jQuery?

I found out today the keypress event is not fired when hitting the Enter key, so you might want to switch to keydown() or keyup() instead.

My test script:

        $('.module input').keydown(function (e) {
            var keyCode = e.which;
            console.log("keydown ("+keyCode+")")
            if (keyCode == 13) {
                return false;
        $('.module input').keyup(function (e) {
            var keyCode = e.which;
            console.log("keyup ("+keyCode+")")
            if (keyCode == 13) {
                return false;
        $('.module input').keypress(function (e) {
            var keyCode = e.which;
            console.log("keypress ("+keyCode+")");
            if (keyCode == 13) {
                return false;

The output in the console when typing "A Enter B" on the keyboard:

keydown (65)
keypress (97)
keyup (65)

keydown (13)
keyup (13)

keydown (66)
keypress (98)
keyup (66)

You see in the second sequence the 'keypress' is missing, but keydown and keyup register code '13' as being pressed/released. As per jQuery documentation on the function keypress():

Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

Tested on IE11 and FF61 on Server 2012 R2

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist

Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit

There are several possible solutions:

Create an empty file

touch file


echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

C# Foreach statement does not contain public definition for GetEnumerator

You don't show us the declaration of carBootSaleList. However from the exception message I can see that it is of type CarBootSaleList. This type doesn't implement the IEnumerable interface and therefore cannot be used in a foreach.

Your CarBootSaleList class should implement IEnumerable<CarBootSale>:

public class CarBootSaleList : IEnumerable<CarBootSale>
    private List<CarBootSale> carbootsales;


    public IEnumerator<CarBootSale> GetEnumerator()
        return carbootsales.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator()
        return carbootsales.GetEnumerator();

Including dependencies in a jar with Maven

If you want to do an executable jar file, them need set the main class too. So the full configuration should be.

                       <!-- ... -->

Left padding a String with Zeros

This will pad left any string to a total width of 10 without worrying about parse errors:

String unpadded = "12345"; 
String padded = "##########".substring(unpadded.length()) + unpadded;

//unpadded is "12345"
//padded   is "#####12345"

If you want to pad right:

String unpadded = "12345"; 
String padded = unpadded + "##########".substring(unpadded.length());

//unpadded is "12345"
//padded   is "12345#####"  

You can replace the "#" characters with whatever character you would like to pad with, repeated the amount of times that you want the total width of the string to be. E.g. if you want to add zeros to the left so that the whole string is 15 characters long:

String unpadded = "12345"; 
String padded = "000000000000000".substring(unpadded.length()) + unpadded;

//unpadded is "12345"
//padded   is "000000000012345"  

The benefit of this over khachik's answer is that this does not use Integer.parseInt, which can throw an Exception (for example, if the number you want to pad is too large like 12147483647). The disadvantage is that if what you're padding is already an int, then you'll have to convert it to a String and back, which is undesirable.

So, if you know for sure that it's an int, khachik's answer works great. If not, then this is a possible strategy.

Select element by exact match of its content

So Amandu's answer mostly works. Using it in the wild, however, I ran into some issues, where things that I would have expected to get found were not getting found. This was because sometimes there is random white space surrounding the element's text. It is my belief that if you're searching for "Hello World", you would still want it to match " Hello World ", or even "Hello World \n". Thus, I just added the "trim()" method to the function, which removes surrounding whitespace, and it started to work better.


$.expr[':'].textEquals = function(el, i, m) {
    var searchText = m[3];
    var match = $(el).text().trim().match("^" + searchText + "$")
    return match && match.length > 0;

Also, note, this answer is extremely similar to Select link by text (exact match)

And secondary note... trim only removes whitespace before and after the searched text. It does not remove whitespace in the middle of the words. I believe this is desirable behavior, but you could change that if you wanted.

Delete specific line from a text file?

  1. Read and remember each line

  2. Identify the one you want to get rid of

  3. Forget that one

  4. Write the rest back over the top of the file

WCF named pipe minimal example

Try this.

Here is the service part.

public interface IService
    void  HelloWorld();

public class Service : IService
    public void HelloWorld()
        //Hello World

Here is the Proxy

public class ServiceProxy : ClientBase<IService>
    public ServiceProxy()
        : base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
            new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))

    public void InvokeHelloWorld()

And here is the service hosting part.

var serviceHost = new ServiceHost
        (typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
    serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");

    Console.WriteLine("Service started. Available in following endpoints");
    foreach (var serviceEndpoint in serviceHost.Description.Endpoints)

python catch exception and continue try block

No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.

What about a for-loop though?

funcs = do_smth1, do_smth2

for func in funcs:
    except Exception:
        pass  # or you could use 'continue'

Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.

JQuery .each() backwards

Needed to do a reverse on $.each so i used Vinay idea:

//jQuery.each(collection, callback) =>
$.each($(collection).get().reverse(), callback func() {});

worked nicely, thanks

Difference between <span> and <div> with text-align:center;?

the difference is not between <span> and <div> specifically, but between inline and block elements. <span> defaults to being display:inline; whereas <div> defaults to being display:block;. But these can be overridden in CSS.

The difference in the way text-align:center works between the two is down to the width.

A block element defaults to being the width of its container. It can have its width set using CSS, but either way it is a fixed width.

An inline element takes its width from the size of its content text.

text-align:center tells the text to position itself centrally in the element. But in an inline element, this is clearly not going to have any effect because the element is the same width as the text; aligning it one way or the other is meaningless.

In a block element, because the element's width is independent of the content, the content can be positioned within the element using the text-align style.

Finally, a solution for you:

There is an additional value for the display property which provides a half-way house between block and inline. Conveniently enough, it's called inline-block. If you specify a <span> to be display:inline-block; in the CSS, it will continue to work as an inline element but will take on some of the properties of a block as well, such as the ability to specify a width. Once you specify a width for it, you will be able to center the text within that width using text-align:center;

Hope that helps.

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

You always can do a session flush. Flush will synchronize the state of all your objects in session (please, someone correct me if i'm wrong), and maybe it would solve your problem in some cases.

Implementing your own equals and hashcode may help you too.