Programs & Examples On #Error handling

Programming language constructs designed to handle errors signaled by error codes, exceptions or other language specific means.

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

Pipe output and capture exit status in Bash

It may sometimes be simpler and clearer to use an external command, rather than digging into the details of bash. pipeline, from the minimal process scripting language execline, exits with the return code of the second command*, just like a sh pipeline does, but unlike sh, it allows reversing the direction of the pipe, so that we can capture the return code of the producer process (the below is all on the sh command line, but with execline installed):

$ # using the full execline grammar with the execlineb parser:
$ execlineb -c 'pipeline { echo "hello world" } tee out.txt'
hello world
$ cat out.txt
hello world

$ # for these simple examples, one can forego the parser and just use "" as a separator
$ # traditional order
$ pipeline echo "hello world" "" tee out.txt 
hello world

$ # "write" order (second command writes rather than reads)
$ pipeline -w tee out.txt "" echo "hello world"
hello world

$ # pipeline execs into the second command, so that's the RC we get
$ pipeline -w tee out.txt "" false; echo $?
1

$ pipeline -w tee out.txt "" true; echo $?
0

$ # output and exit status
$ pipeline -w tee out.txt "" sh -c "echo 'hello world'; exit 42"; echo "RC: $?"
hello world
RC: 42
$ cat out.txt
hello world

Using pipeline has the same differences to native bash pipelines as the bash process substitution used in answer #43972501.

* Actually pipeline doesn't exit at all unless there is an error. It executes into the second command, so it's the second command that does the returning.

How do I log errors and warnings into a file?

Use the following code:

ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "Hello, errors!" );

Then watch the file:

tail -f /tmp/php-error.log

Or update php.ini as described in this blog entry from 2008.

Are there any standard exit status codes in Linux?

When Linux returns 0, it means success. Anything else means failure, each program has its own exit codes, so it would been quite long to list them all... !

About the 11 error code, it's indeed the segmentation fault number, mostly meaning that the program accessed a memory location that was not assigned.

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

This is more of a important comment and that why implicitly unwrapped optionals can be deceptive when it comes to debugging nil values.

Think of the following code: It compiles with no errors/warnings:

c1.address.city = c3.address.city

Yet at runtime it gives the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Can you tell me which object is nil?

You can't!

The full code would be:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var c1 = NormalContact()
        let c3 = BadContact()

        c1.address.city = c3.address.city // compiler hides the truth from you and then you sudden get a crash
    }
}

struct NormalContact {
    var address : Address = Address(city: "defaultCity")
}

struct BadContact {
    var address : Address!
}

struct Address {
    var city : String
}

Long story short by using var address : Address! you're hiding the possibility that a variable can be nil from other readers. And when it crashes you're like "what the hell?! my address isn't an optional, so why am I crashing?!.

Hence it's better to write as such:

c1.address.city = c2.address!.city  // ERROR:  Fatal error: Unexpectedly found nil while unwrapping an Optional value 

Can you now tell me which object it is that was nil?

This time the code has been made more clear to you. You can rationalize and think that likely it's the address parameter that was forcefully unwrapped.

The full code would be :

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var c1 = NormalContact()
        let c2 = GoodContact()

        c1.address.city = c2.address!.city
        c1.address.city = c2.address?.city // not compile-able. No deceiving by the compiler
        c1.address.city = c2.address.city // not compile-able. No deceiving by the compiler
        if let city = c2.address?.city {  // safest approach. But that's not what I'm talking about here. 
            c1.address.city = city
        }

    }
}

struct NormalContact {
    var address : Address = Address(city: "defaultCity")
}

struct GoodContact {
    var address : Address?
}

struct Address {
    var city : String
}

How do I get PHP errors to display?

You can do this by changing the php.ini file and add the following

display_errors = on
display_startup_errors = on

OR you can also use the following code as this always works for me

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

live output from subprocess command

If you're able to use third-party libraries, You might be able to use something like sarge (disclosure: I'm its maintainer). This library allows non-blocking access to output streams from subprocesses - it's layered over the subprocess module.

PHP Notice: Undefined offset: 1 with array when reading data

Change

$data[$parts[0]] = $parts[1];

to

if ( ! isset($parts[1])) {
   $parts[1] = null;
}

$data[$parts[0]] = $parts[1];

or simply:

$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;

Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.

According to php.net possible return values from explode:

Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

Fastest way to check if a string is JSON in PHP?

The simplest and fastest way that I use is following;

$json_array = json_decode( $raw_json , true );

if( $json_array == NULL )   //check if it was invalid json string
    die ('Invalid');  // Invalid JSON error

 // you can execute some else condition over here in case of valid JSON

It is because json_decode() returns NULL if the entered string is not json or invalid json.


Simple function to validate JSON

If you have to validate your JSON in multiple places, you can always use the following function.

function is_valid_json( $raw_json ){
    return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes! thats it.
}

In the above function, you will get true in return if it is a valid JSON.

How do I turn off PHP Notices?

Used This Line In Your Code

error_reporting(E_ALL ^ E_NOTICE);  

I think its helf full to you.

REST API error code 500 handling

80 % of the times, this would due to wrong input by in soapRequest.xml file

Detailed 500 error message, ASP + IIS 7.5

In my case it was permission issue. Open application folder properties -> Security tab -> Edit -> Add

  • IIS AppPool\[DefaultAppPool or any other apppool] (if use ApplicationPoolIdentity option)
  • IUSRS
  • IIS_IUSRS

Error: could not find function ... in R

There are a few things you should check :

  1. Did you write the name of your function correctly? Names are case sensitive.
  2. Did you install the package that contains the function? install.packages("thePackage") (this only needs to be done once)
  3. Did you attach that package to the workspace ? require(thePackage) or library(thePackage) (this should be done every time you start a new R session)
  4. Are you using an older R version where this function didn't exist yet?

If you're not sure in which package that function is situated, you can do a few things.

  1. If you're sure you installed and attached/loaded the right package, type help.search("some.function") or ??some.function to get an information box that can tell you in which package it is contained.
  2. find and getAnywhere can also be used to locate functions.
  3. If you have no clue about the package, you can use findFn in the sos package as explained in this answer.
  4. RSiteSearch("some.function") or searching with rdocumentation or rseek are alternative ways to find the function.

Sometimes you need to use an older version of R, but run code created for a newer version. Newly added functions (eg hasName in R 3.4.0) won't be found then. If you use an older R version and want to use a newer function, you can use the package backports to make such functions available. You also find a list of functions that need to be backported on the git repo of backports. Keep in mind that R versions older than R3.0.0 are incompatible with packages built for R3.0.0 and later versions.

Deploying website: 500 - Internal server error

If you are using IIS 8.5 it may be that you need to change the ApplicationPool ID setting from ApplicationPoolId to NetworkService

Right click the Application Pool in question, click on "Advanced Settings" and then scroll down to ID - it will probably be set to ApplicationPoolIdentity. Click the button (..) and select NetworkService from the dropdown list instead.

Also make sure that if it is a .NET 2.0 application that you are not referencing the 4.0 framework in your App Pool.

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

This may not be the best way for MVC ( https://stackoverflow.com/a/9461386/5869805 )

Below is how you render a view in Application_Error and write it to http response. You do not need to use redirect. This will prevent a second request to server, so the link in browser's address bar will stay same. This may be good or bad, it depends on what you want.

Global.asax.cs

protected void Application_Error()
{
    var exception = Server.GetLastError();
    // TODO do whatever you want with exception, such as logging, set errorMessage, etc.
    var errorMessage = "SOME FRIENDLY MESSAGE";

    // TODO: UPDATE BELOW FOUR PARAMETERS ACCORDING TO YOUR ERROR HANDLING ACTION
    var errorArea = "AREA";
    var errorController = "CONTROLLER";
    var errorAction = "ACTION";
    var pathToViewFile = $"~/Areas/{errorArea}/Views/{errorController}/{errorAction}.cshtml"; // THIS SHOULD BE THE PATH IN FILESYSTEM RELATIVE TO WHERE YOUR CSPROJ FILE IS!

    var requestControllerName = Convert.ToString(HttpContext.Current.Request.RequestContext?.RouteData?.Values["controller"]);
    var requestActionName = Convert.ToString(HttpContext.Current.Request.RequestContext?.RouteData?.Values["action"]);

    var controller = new BaseController(); // REPLACE THIS WITH YOUR BASE CONTROLLER CLASS
    var routeData = new RouteData { DataTokens = { { "area", errorArea } }, Values = { { "controller", errorController }, {"action", errorAction} } };
    var controllerContext = new ControllerContext(new HttpContextWrapper(HttpContext.Current), routeData, controller);
    controller.ControllerContext = controllerContext;

    var sw = new StringWriter();
    var razorView = new RazorView(controller.ControllerContext, pathToViewFile, "", false, null);
    var model = new ViewDataDictionary(new HandleErrorInfo(exception, requestControllerName, requestActionName));
    var viewContext = new ViewContext(controller.ControllerContext, razorView, model, new TempDataDictionary(), sw);
    viewContext.ViewBag.ErrorMessage = errorMessage;
    //TODO: add to ViewBag what you need
    razorView.Render(viewContext, sw);
    HttpContext.Current.Response.Write(sw);
    Server.ClearError();
    HttpContext.Current.Response.End(); // No more processing needed (ex: by default controller/action routing), flush the response out and raise EndRequest event.
}

View

@model HandleErrorInfo
@{
    ViewBag.Title = "Error";
    // TODO: SET YOUR LAYOUT
}
<div class="">
    ViewBag.ErrorMessage
</div>
@if(Model != null && HttpContext.Current.IsDebuggingEnabled)
{
    <div class="" style="background:khaki">
        <p>
            <b>Exception:</b> @Model.Exception.Message <br/>
            <b>Controller:</b> @Model.ControllerName <br/>
            <b>Action:</b> @Model.ActionName <br/>
        </p>
        <div>
            <pre>
                @Model.Exception.StackTrace
            </pre>
        </div>
    </div>
}

What's the source of Error: getaddrinfo EAI_AGAIN?

updating the npm to latest fixes this problem for me.

npm install npm@latest

this issue is related to your network connectivity. hence can be temporary. on a stable internet connection this issue was hardly observed.

Warning: implode() [function.implode]: Invalid arguments passed

It happens when $ret hasn't been defined. The solution is simple. Right above $tags = get_tags();, add the following line:

$ret = array();

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

Enabling error display in PHP via htaccess only

.htaccess:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

How can I get useful error messages in PHP?

Some applications do handle these instructions themselves, by calling something like this:

error_reporting(E_ALL & ~E_DEPRECATED); or error_reporting(0);

And thus overriding your .htaccess settings.

Does Python have an argc argument?

I often use a quick-n-dirty trick to read a fixed number of arguments from the command-line:

[filename] = sys.argv[1:]

in_file = open(filename)   # Don't need the "r"

This will assign the one argument to filename and raise an exception if there isn't exactly one argument.

Disabling Strict Standards in PHP 5.4

Heads up, you might need to restart LAMP, Apache or whatever your using to make this take affect. Racked our brains for a while on this one, seemed to make no affect until services were restarted, presumably because the website was caching.

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

This is an IndexError in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.

# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64) 

# check its shape      
In [15]: arr.shape  
Out[15]: (0,)

with this array arr in place, if we now try to assign any value to some index, for example to the index 0 as in the case below

In [16]: arr[0] = 23     

Then, we will get an IndexError, as below:


IndexError                                Traceback (most recent call last)
<ipython-input-16-0891244a3c59> in <module>
----> 1 arr[0] = 23

IndexError: index 0 is out of bounds for axis 0 with size 0

The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0).

In [19]: arr.size * arr.itemsize  
Out[19]: 0

So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0 and fix that.

must declare a named package eclipse because this compilation unit is associated to the named module

Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.

Quick fix:

  1. Create a package eg. helloWorld inside the src folder.
  2. Move helloWorld.java file in that package. Just drag and drop on the package. Error should disappear.

Explanation:

  • My Eclipse version: 2020-09 (4.17.0)
  • My Java version: Java 15, 2020-09-15

Latest version of Eclipse required java11 or above. The module feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules

When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java file. If you select don't create then module-info.java will not create and your project will free from this issue.

Best practice is while crating project, after giving project name. Click on next button instead of finish. On next page at the bottom it ask for creation of module-info.java file. Select or deselect as per need.

If selected: (by default) click on finish button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.

If deselect: No issue

Eclipse returns error message "Java was started but returned exit code = 1"

This work for me in eclipse js and eclipse php:

 -vm
 C:/java/jdk-11.0.1/bin/javaw.exe
 --launcher.appendVmargs
 -vmargs

Error handling in C code

In addition the other great answers, I suggest that you try to separate the error flag and the error code in order to save one line on each call, i.e.:

if( !doit(a, b, c, &errcode) )
{   (* handle *)
    (* thine  *)
    (* error  *)
}

When you have lots of error-checking, this little simplification really helps.

ASP.NET MVC 404 Error Handling

Yet another solution.

Add ErrorControllers or static page to with 404 error information.

Modify your web.config (in case of controller).

<system.web>
    <customErrors mode="On" >
       <error statusCode="404" redirect="~/Errors/Error404" />
    </customErrors>
</system.web>

Or in case of static page

<system.web>
    <customErrors mode="On" >
        <error statusCode="404" redirect="~/Static404.html" />
    </customErrors>
</system.web>

This will handle both missed routes and missed actions.

"Stack overflow in line 0" on Internet Explorer

I had this problem, and I solved it. There was an attribute in the <%@ Page tag named MaintainScrollPositionOnPostback and after removing it, the error disapeared. I added it before to prevent scrolling after each postback.

How to get the jQuery $.ajax error response text?

Look at the responseText property of the request parameter.

How to capture no file for fs.readFileSync()?

The JavaScript try…catch mechanism cannot be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use throw inside an error-first callback:

// THIS WILL NOT WORK:
const fs = require('fs');

try {
  fs.readFile('/some/file/that/does-not-exist', (err, data) => {
    // Mistaken assumption: throwing here...
    if (err) {
      throw err;
    }
  });
} catch (err) {
  // This will not catch the throw!
  console.error(err);
}

This will not work because the callback function passed to fs.readFile() is called asynchronously. By the time the callback has been called, the surrounding code, including the try…catch block, will have already exited. Throwing an error inside the callback can crash the Node.js process in most cases. If domains are enabled, or a handler has been registered with process.on('uncaughtException'), such errors can be intercepted.

reference: https://nodejs.org/api/errors.html

PHP Try and Catch for SQL Insert

    $sql = "INSERT INTO   customer(FIELDS)VALUES(VALUES)";
    mysql_query($sql);
    if (mysql_errno())
    {
            echo "<script>alert('License already registered');location.replace('customerform.html');</script>";
    }   

Multiple values in single-value context

Yes, there is.

Surprising, huh? You can get a specific value from a multiple return using a simple mute function:

package main

import "fmt"
import "strings"

func µ(a ...interface{}) []interface{} {
    return a
}

type A struct {
    B string
    C func()(string)
}

func main() {
    a := A {
        B:strings.TrimSpace(µ(E())[1].(string)),
        C:µ(G())[0].(func()(string)),
    }

    fmt.Printf ("%s says %s\n", a.B, a.C())
}

func E() (bool, string) {
    return false, "F"
}

func G() (func()(string), bool) {
    return func() string { return "Hello" }, true
}

https://play.golang.org/p/IwqmoKwVm-

Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.

You can read more about the science behind that from this article. Credits to the author.

Can I try/catch a warning?

Normaly you should never use @ unless this is the only solution. In that specific case the function dns_check_record should be use first to know if the record exists.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

Most of what I write has already been covered by Pressacco, but this is specific to SpecFlow.

I was getting this message for the <specFlow> element and therefore I added a specflow.xsd file to the solution this answer (with some modifications to allow for the <plugins> element).

Thereafter I (like Pressacco), right clicked within the file buffer of app.config and selected properties, and within Schemas, I added "specflow.xsd" to the end. The entirety of Schemas now reads:

"C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\1033\DotNetConfig.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\EntityFrameworkConfig_6_1_0.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\RazorCustomSchema.xsd" "specflow.xsd"

How to display my application's errors in JSF?

FacesContext.addMessage(String, FacesMessage) requires the component's clientId, not it's id. If you're wondering why, think about having a control as a child of a dataTable, stamping out different values with the same control for each row - it would be possible to have a different message printed for each row. The id is always the same; the clientId is unique per row.

So "myform:mybutton" is the correct value, but hard-coding this is ill-advised. A lookup would create less coupling between the view and the business logic and would be an approach that works in more restrictive environments like portlets.

<f:view>
  <h:form>
    <h:commandButton id="mybutton" value="click"
      binding="#{showMessageAction.mybutton}"
      action="#{showMessageAction.validatePassword}" />
    <h:message for="mybutton" />
  </h:form>
</f:view>

Managed bean logic:

/** Must be request scope for binding */
public class ShowMessageAction {

    private UIComponent mybutton;

    private boolean isOK = false;

    public String validatePassword() {
        if (isOK) {
            return "ok";
        }
        else {
            // invalid
            FacesMessage message = new FacesMessage("Invalid password length");
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(mybutton.getClientId(context), message);
        }
        return null;
    }

    public void setMybutton(UIComponent mybutton) {
        this.mybutton = mybutton;
    }

    public UIComponent getMybutton() {
        return mybutton;
    }
}

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

That really depends on if you expect to find the object, or not. If you follow the school of thought that exceptions should be used for indicating something, well, err, exceptional has occured then:

  • Object found; return object
  • Object not-found; throw exception

Otherwise, return null.

Begin, Rescue and Ensure in Ruby?

This is why we need ensure:

def hoge
  begin
    raise
  rescue  
    raise # raise again
  ensure  
    puts 'ensure' # will be executed
  end  
  puts 'end of func' # never be executed
end  

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

The following should work and not require any permissions in the manifest (basically override shouldOverrideUrlLoading and handle links separately from tel, mailto, etc.):

    mWebView = (WebView) findViewById(R.id.web_view);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if( url.startsWith("http:") || url.startsWith("https:") ) {
                return false;
            }

            // Otherwise allow the OS to handle things like tel, mailto, etc.
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity( intent );
            return true;
        }
    });
    mWebView.loadUrl(url);

Also, note that in the above snippet I am enabling JavaScript, which you will also most likely want, but if for some reason you don't, just remove those 2 lines.

Reference - What does this error mean in PHP?

Warning: function() expects parameter X to be boolean (or integer, string, etc)

If the wrong type of parameter is passed to a function – and PHP cannot convert it automatically – a warning is thrown. This warning identifies which parameter is the problem, and what data type is expected. The solution: change the indicated parameter to the correct data type.


For example this code:

echo substr(["foo"], 23);

Results in this output:

PHP Warning: substr() expects parameter 1 to be string, array given

Log exception with traceback

maybe not as stylish, but easier:

#!/bin/bash
log="/var/log/yourlog"
/path/to/your/script.py 2>&1 | (while read; do echo "$REPLY" >> $log; done)

Raise warning in Python without interrupting program

You shouldn't raise the warning, you should be using warnings module. By raising it you're generating error, rather than warning.

vba error handling in loop

As a general way to handle error in a loop like your sample code, I would rather use:

on error resume next
for each...
    'do something that might raise an error, then
    if err.number <> 0 then
         ...
    end if
 next ....

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

Is there a TRY CATCH command in Bash

I've developed an almost flawless try & catch implementation in bash, that allows you to write code like:

try 
    echo 'Hello'
    false
    echo 'This will not be displayed'

catch 
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"

You can even nest the try-catch blocks inside themselves!

try {
    echo 'Hello'

    try {
        echo 'Nested Hello'
        false
        echo 'This will not execute'
    } catch {
        echo "Nested Caught (@ $__EXCEPTION_LINE__)"
    }

    false
    echo 'This will not execute too'

} catch {
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
}

The code is a part of my bash boilerplate/framework. It further extends the idea of try & catch with things like error handling with backtrace and exceptions (plus some other nice features).

Here's the code that's responsible just for try & catch:

set -o pipefail
shopt -s expand_aliases
declare -ig __oo__insideTryCatch=0

# if try-catch is nested, then set +e before so the parent handler doesn't catch us
alias try="[[ \$__oo__insideTryCatch -gt 0 ]] && set +e;
           __oo__insideTryCatch+=1; ( set -e;
           trap \"Exception.Capture \${LINENO}; \" ERR;"
alias catch=" ); Exception.Extract \$? || "

Exception.Capture() {
    local script="${BASH_SOURCE[1]#./}"

    if [[ ! -f /tmp/stored_exception_source ]]; then
        echo "$script" > /tmp/stored_exception_source
    fi
    if [[ ! -f /tmp/stored_exception_line ]]; then
        echo "$1" > /tmp/stored_exception_line
    fi
    return 0
}

Exception.Extract() {
    if [[ $__oo__insideTryCatch -gt 1 ]]
    then
        set -e
    fi

    __oo__insideTryCatch+=-1

    __EXCEPTION_CATCH__=( $(Exception.GetLastException) )

    local retVal=$1
    if [[ $retVal -gt 0 ]]
    then
        # BACKWARDS COMPATIBILE WAY:
        # export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-1)]}"
        # export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-2)]}"
        export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[-1]}"
        export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[-2]}"
        export __EXCEPTION__="${__EXCEPTION_CATCH__[@]:0:(${#__EXCEPTION_CATCH__[@]} - 2)}"
        return 1 # so that we may continue with a "catch"
    fi
}

Exception.GetLastException() {
    if [[ -f /tmp/stored_exception ]] && [[ -f /tmp/stored_exception_line ]] && [[ -f /tmp/stored_exception_source ]]
    then
        cat /tmp/stored_exception
        cat /tmp/stored_exception_line
        cat /tmp/stored_exception_source
    else
        echo -e " \n${BASH_LINENO[1]}\n${BASH_SOURCE[2]#./}"
    fi

    rm -f /tmp/stored_exception /tmp/stored_exception_line /tmp/stored_exception_source
    return 0
}

Feel free to use, fork and contribute - it's on GitHub.

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

Handling a timeout error in python sockets

from foo import * 

adds all the names without leading underscores (or only the names defined in the modules __all__ attribute) in foo into your current module.

In the above code with from socket import * you just want to catch timeout as you've pulled timeout into your current namespace.

from socket import * pulls in the definitions of everything inside of socket but doesn't add socket itself.

try:
    # socketstuff
except timeout:
    print 'caught a timeout'

Many people consider import * problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.

For example, consider the following three python files:

# a.py
def foo():
    print "this is a's foo function"

# b.py
def foo():
    print "this is b's foo function"

# yourcode.py
from a import *
from b import *
foo()

If you run yourcode.py you'll see just the output "this is b's foo function".

For this reason I'd suggest either importing the module and using it or importing specific names from the module:

For example, your code would look like this with explicit imports:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message', (server_host, server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            #more code

Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.

Does a finally block always get executed in Java?

Example code:

public static void main(String[] args) {
    System.out.println(Test.test());
}

public static int test() {
    try {
        return 0;
    }
    finally {
        System.out.println("finally trumps return.");
    }
}

Output:

finally trumps return. 
0

What does the "On Error Resume Next" statement do?

It means, when an error happens on the line, it is telling vbscript to continue execution without aborting the script. Sometimes, the On Error follows the Goto label to alter the flow of execution, something like this in a Sub code block, now you know why and how the usage of GOTO can result in spaghetti code:

Sub MySubRoutine()
   On Error Goto ErrorHandler

   REM VB code...

   REM More VB Code...

Exit_MySubRoutine:

   REM Disable the Error Handler!

   On Error Goto 0

   REM Leave....
   Exit Sub

ErrorHandler:

   REM Do something about the Error

   Goto Exit_MySubRoutine
End Sub

How to handle ETIMEDOUT error?

We could look at error object for a property code that mentions the possible system error and in cases of ETIMEDOUT where a network call fails, act accordingly.

if (err.code === 'ETIMEDOUT') {
    console.log('My dish error: ', util.inspect(err, { showHidden: true, depth: 2 }));
}

How to do error logging in CodeIgniter (PHP)

Also make sure that you have allowed codeigniter to log the type of messages you want in a config file.

i.e $config['log_threshold'] = [log_level ranges 0-4];

What is the difference between `throw new Error` and `throw someObject`?

React behavior

Apart from the rest of the answers, I would like to show one difference in React.

If I throw a new Error() and I am in development mode, I will get an error screen and a console log. If I throw a string literal, I will only see it in the console and possibly miss it, if I am not watching the console log.

Example

Throwing an error logs into the console and shows an error screen while in development mode (the screen won't be visible in production).

throw new Error("The application could not authenticate.");

Error screen in react

Whereas the following code only logs into the console:

throw "The application could not authenticate.";

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.

Notice: Undefined variable: _SESSION in "" on line 9

First, you'll need to add session_start() at the top of any page that you wish to use SESSION variables on.

Also, you should check to make sure the variable is set first before using it:

if(isset($_SESSION['SESS_fname'])){
    echo $_SESSION['SESS_fname'];
}

Or, simply:

echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");

How to print an exception in Python?

In case you want to pass error strings, here is an example from Errors and Exceptions (Python 2.6)

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

Why is "except: pass" a bad programming practice?

Since it hasn't been mentioned yet, it's better style to use contextlib.suppress:

with suppress(FileNotFoundError):
    os.remove('somefile.tmp')

In this example, somefile.tmp will be non-existent after this block of code executes without raising any exceptions (other than FileNotFoundError, which is suppressed).

How do I debug "Error: spawn ENOENT" on node.js?

I was also going through this annoying problem while running my test cases, so I tried many ways to get across it. But the way works for me is to run your test runner from the directory which contains your main file which includes your nodejs spawn function something like this:

nodeProcess = spawn('node',params, {cwd: '../../node/', detached: true });

For example, this file name is test.js, so just move to the folder which contains it. In my case, it is test folder like this:

cd root/test/

then from run your test runner in my case its mocha so it will be like this:

mocha test.js

I have wasted my more than one day to figure it out. Enjoy!!

400 BAD request HTTP error code meaning?

A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.

In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.

By that logic, both the scenarios you provided should be 400s.

Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation--either because of an undefined element or an improper element value. That would be a bad request. Same deal here.

Try/catch does not seem to have an effect

Edit: As stated in the comments, the following solution applies to PowerShell V1 only.

See this blog post on "Technical Adventures of Adam Weigert" for details on how to implement this.

Example usage (copy/paste from Adam Weigert's blog):

Try {
    echo " ::Do some work..."
    echo " ::Try divide by zero: $(0/0)"
} -Catch {
    echo "  ::Cannot handle the error (will rethrow): $_"
    #throw $_
} -Finally {
    echo " ::Cleanup resources..."
}

Otherwise you'll have to use exception trapping.

How do I catch an Ajax query post error?

In case you want to utilize .then() which has a subtle difference in comparison with .done() :

return $.post(url, payload)
.then(
    function (result, textStatus, jqXHR) {
        return result;
    },
    function (jqXHR, textStatus, errorThrown) {
        return console.error(errorThrown);
    });

How can I solve the error LNK2019: unresolved external symbol - function?

One option would be to include function.cpp in your UnitTest1 project, but that may not be the most ideal solution structure. The short answer to your problem is that when building your UnitTest1 project, the compiler and linker have no idea that function.cpp exists, and also have nothing to link that contains a definition of multiple. A way to fix this is making use of linking libraries.

Since your unit tests are in a different project, I'm assuming your intention is to make that project a standalone unit-testing program. With the functions you are testing located in another project, it's possible to build that project to either a dynamically or statically linked library. Static libraries are linked to other programs at build time, and have the extension .lib, and dynamic libraries are linked at runtime, and have the extension .dll. For my answer I'll prefer static libraries.

You can turn your first program into a static library by changing it in the projects properties. There should be an option under the General tab where the project is set to build to an executable (.exe). You can change this to .lib. The .lib file will build to the same place as the .exe.

In your UnitTest1 project, you can go to its properties, and under the Linker tab in the category Additional Library Directories, add the path to which MyProjectTest builds. Then, for Additional Dependencies under the Linker - Input tab, add the name of your static library, most likely MyProjectTest.lib.

That should allow your project to build. Note that by doing this, MyProjectTest will not be a standalone executable program unless you change its build properties as needed, which would be less than ideal.

Replace single quotes in SQL Server

If you really must completely strip out the single quotes you can do this:

Replace(@strip, '''', '')

However, ordinarily you'd replace ' with '' and this will make SQL Server happy when querying the database. The trick with any of the built-in SQL functions (like replace) is that they too require you to double up your single quotes.

So to replace ' with '' in code you'd do this:

Replace(@strip, '''', '''''')

Of course... in some situations you can avoid having to do this entirely if you use parameters when querying the database. Say you're querying the database from a .NET application, then you'd use the SqlParameter class to feed the SqlCommand parameters for the query and all of this single quote business will be taken care of automatically. This is usually the preferred method as SQL parameters will also help prevent SQL injection attacks.

What's a good way to extend Error in JavaScript?

I would take a step back and consider why you want to do that? I think the point is to deal with different errors differently.

For example, in Python, you can restrict the catch statement to only catch MyValidationError, and perhaps you want to be able to do something similar in javascript.

catch (MyValidationError e) {
    ....
}

You can't do this in javascript. There's only going to be one catch block. You're supposed to use an if statement on the error to determine its type.

catch(e) { if(isMyValidationError(e)) { ... } else { // maybe rethrow? throw e; } }

I think I would instead throw a raw object with a type, message, and any other properties you see fit.

throw { type: "validation", message: "Invalid timestamp" }

And when you catch the error:

catch(e) {
    if(e.type === "validation") {
         // handle error
    }
    // re-throw, or whatever else
}

How can I exclude all "permission denied" messages from "find"?

You can also use the -perm and -prune predicates to avoid descending into unreadable directories (see also How do I remove "permission denied" printout statements from the find program? - Unix & Linux Stack Exchange):

find . -type d ! -perm -g+r,u+r,o+r -prune -o -print > files_and_folders

Is try-catch like error handling possible in ASP Classic?

Regarding Wolfwyrd's anwer: "On Error Resume Next" in fact turns error handling off! Not on. On Error Goto 0 turns error-handling back ON because at the least, we want the machine to catch it if we didn't write it in ourselves. Off = leaving it to you to handle it.

If you use On Error Resume Next, you need to be careful about how much code you include after it: remember, the phrase "If Err.Number <> 0 Then" only refers to the most previous error triggered.

If your block of code after "On Error Resume Next" has several places where you might reasonably expect it to fail, then you must place "If Err.number <> 0" after each and every one of those possible failure lines, to check execution.

Otherwise, after "on error resume next" means just what it says - your code can fail on as many lines as it likes and execution will continue merrily along. That's why it's a pain in the ass.

When to catch java.lang.Error?

It might be appropriate to catch error within unit tests that check an assertion is made. If someone disables assertions or otherwise deletes the assertion you would want to know

In Python try until no error

It won't get much cleaner. This is not a very clean thing to do. At best (which would be more readable anyway, since the condition for the break is up there with the while), you could create a variable result = None and loop while it is None. You should also adjust the variables and you can replace continue with the semantically perhaps correct pass (you don't care if an error occurs, you just want to ignore it) and drop the break - this also gets the rest of the code, which only executes once, out of the loop. Also note that bare except: clauses are evil for reasons given in the documentation.

Example incorporating all of the above:

result = None
while result is None:
    try:
        # connect
        result = get_data(...)
    except:
         pass
# other code that uses result but is not involved in getting it

Powershell: How can I stop errors from being displayed in a script?

You're way off track here.

You already have a nice, big error message. Why on Earth would you want to write code that checks $? explicitly after every single command? This is enormously cumbersome and error prone. The correct solution is stop checking $?.

Instead, use PowerShell's built in mechanism to blow up for you. You enable it by setting the error preference to the highest level:

$ErrorActionPreference = 'Stop'

I put this at the top of every single script I ever write, and now I don't have to check $?. This makes my code vastly simpler and more reliable.

If you run into situations where you really need to disable this behavior, you can either catch the error or pass a setting to a particular function using the common -ErrorAction. In your case, you probably want your process to stop on the first error, catch the error, and then log it.

Do note that this doesn't handle the case when external executables fail (exit code nonzero, conventionally), so you do still need to check $LASTEXITCODE if you invoke any. Despite this limitation, the setting still saves a lot of code and effort.

Additional reliability

You might also want to consider using strict mode:

Set-StrictMode -Version Latest

This prevents PowerShell from silently proceeding when you use a non-existent variable and in other weird situations. (See the -Version parameter for details about what it restricts.)

Combining these two settings makes PowerShell much more of fail-fast language, which makes programming in it vastly easier.

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

One obvious thing is that you will have to remove the comma here

receipt int(10),

but the actual problem is because of the line

amount double(10) NOT NULL,

change it to

amount double NOT NULL,

Raise error in a Bash script

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

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

So what you want to do falls upon these two categories

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

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

Should I use exit in my script/function?

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

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

Should I use set -e for error on exit?

No!

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

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

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

    set -e
    somecommand that fails | cat -
    echo survived 
    

Recommended for use - trap on exit

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

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

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

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

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

trap cleanup ERR

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

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

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

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

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

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

    trap 'echo error' ERR
    (false)
    

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

How do find your PHP error log on Linux:

eric@dev /var $ sudo updatedb
[sudo] password for eric:
eric@dev /var $ sudo locate error_log

/var/log/httpd/error_log

Another equivalent way:

eric@dev /home/eric $ sudo find / -name "error_log" 2>/dev/null

/var/log/httpd/error_log

How to check the exit status using an if statement

Using zsh you can simply use:

if [[ $(false)? -eq 1 ]]; then echo "yes" ;fi

When using bash & set -e is on you can use:

false || exit_code=$?
if [[ ${exit_code} -ne 0 ]]; then echo ${exit_code}; fi

Error handling in Bash

This trick is useful for missing commands or functions. The name of the missing function (or executable) will be passed in $_

function handle_error {
    status=$?
    last_call=$1

    # 127 is 'command not found'
    (( status != 127 )) && return

    echo "you tried to call $last_call"
    return
}

# Trap errors.
trap 'handle_error "$_"' ERR

How to catch SQLServer timeout exceptions

I am not sure but when we have execute time out or command time out The client sends an "ABORT" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException

JAX-RS / Jersey how to customize error handling?

This is the correct behavior actually. Jersey will try to find a handler for your input and will try to construct an object from the provided input. In this case it will try to create a new Date object with the value X provided to the constructor. Since this is an invalid date, by convention Jersey will return 404.

What you can do is rewrite and put birth date as a String, then try to parse and if you don't get what you want, you're free to throw any exception you want by any of the exception mapping mechanisms (there are several).

Is it not possible to stringify an Error using JSON.stringify?

Make it serializable

// example error
let err = new Error('I errored')

// one liner converting Error into regular object that can be stringified
err = Object.getOwnPropertyNames(err).reduce((acc, key) => { acc[key] = err[key]; return acc; }, {})

If you want to send this object from child process, worker or though the network there's no need to stringify. It will be automatically stringified and parsed like any other normal object

VBScript -- Using error handling

You can regroup your steps functions calls in a facade function :

sub facade()
    call step1()
    call step2()
    call step3()
    call step4()
    call step5()
end sub

Then, let your error handling be in an upper function that calls the facade :

sub main()
    On error resume next

    call facade()

    If Err.Number <> 0 Then
        ' MsgBox or whatever. You may want to display or log your error there
        msgbox Err.Description
        Err.Clear
    End If

    On Error Goto 0
end sub

Now, let's suppose step3() raises an error. Since facade() doesn't handle errors (there is no On error resume next in facade()), the error will be returned to main() and step4() and step5() won't be executed.

Your error handling is now refactored in 1 code block

How to catch integer(0)?

If it's specifically zero length integers, then you want something like

is.integer0 <- function(x)
{
  is.integer(x) && length(x) == 0L
}

Check it with:

is.integer0(integer(0)) #TRUE
is.integer0(0L)         #FALSE
is.integer0(numeric(0)) #FALSE

You can also use assertive for this.

library(assertive)
x <- integer(0)
assert_is_integer(x)
assert_is_empty(x)
x <- 0L
assert_is_integer(x)
assert_is_empty(x)
## Error: is_empty : x has length 1, not 0.
x <- numeric(0)
assert_is_integer(x)
assert_is_empty(x)
## Error: is_integer : x is not of class 'integer'; it has class 'numeric'.

php return 500 error but no error log

You need to enable the PHP error log.

This is due to some random glitch in the web server when you have a php error, it throws a 500 internal error (i have the same issue).

If you look in the PHP error log, you should find your solution.

see here in the doc of how to enable it in the php.ini

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

Find 'gradle-wrapper.properties' in root project

distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

Change "https" to "http".

How to get error message when ifstream open fails

Every system call that fails update the errno value.

Thus, you can have more information about what happens when a ifstream open fails by using something like :

cerr << "Error: " << strerror(errno);

However, since every system call updates the global errno value, you may have issues in a multithreaded application, if another system call triggers an error between the execution of the f.open and use of errno.

On system with POSIX standard:

errno is thread-local; setting it in one thread does not affect its value in any other thread.


Edit (thanks to Arne Mertz and other people in the comments):

e.what() seemed at first to be a more C++-idiomatically correct way of implementing this, however the string returned by this function is implementation-dependant and (at least in G++'s libstdc++) this string has no useful information about the reason behind the error...

Automatic exit from Bash shell script on error

One idiom is:

cd some_dir && ./configure --some-flags && make && make install

I realize that can get long, but for larger scripts you could break it into logical functions.

Hash String via SHA-256 in Java

This is already implemented in the runtime libs.

public static String calc(InputStream is) {
    String output;
    int read;
    byte[] buffer = new byte[8192];

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] hash = digest.digest();
        BigInteger bigInt = new BigInteger(1, hash);
        output = bigInt.toString(16);
        while ( output.length() < 32 ) {
            output = "0"+output;
        }
    } 
    catch (Exception e) {
        e.printStackTrace(System.err);
        return null;
    }

    return output;
}

In a JEE6+ environment one could also use JAXB DataTypeConverter:

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));

How to pass parameters in $ajax POST?

function funcion(y) {
$.ajax({
   type: 'POST',
   url: '/ruta',
   data: {"x": y},
   contentType: "application/x-www-form-urlencoded;charset=utf8",
});
}

How can I Convert HTML to Text in C#?

Here is the short sweet answer using HtmlAgilityPack. You can run this in LinqPad.

var html = "<div>..whatever html</div>";
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var plainText = doc.DocumentNode.InnerText;

I simply use HtmlAgilityPack in any .NET project that needs HTML parsing. It's simple, reliable, and fast.

What does <a href="#" class="view"> mean?

Don't forget to look at the Javascript as well. My guess is that there is custom Javascript code getting executed when you click on the link and it's that Javascript that is generating the URL and navigating to it.

Different CURRENT_TIMESTAMP and SYSDATE in oracle

SYSDATE, SYSTIMESTAMP returns the Database's date and timestamp, whereas current_date, current_timestamp returns the date and timestamp of the location from where you work.

For eg. working from India, I access a database located in Paris. at 4:00PM IST:

select sysdate,systimestamp from dual;

This returns me the date and Time of Paris:

RESULT

12-MAY-14   12-MAY-14 12.30.03.283502000 PM +02:00

select current_date,current_timestamp from dual;

This returns me the date and Time of India:

RESULT

12-MAY-14   12-MAY-14 04.00.03.283520000 PM ASIA/CALCUTTA

Please note the 3:30 time difference.

Get Country of IP Address with PHP

Use the widget www.feedsalive.com, to get the country informations & last page information as well.

c++ string array initialization

Prior to C++11, you cannot initialise an array using type[]. However the latest c++11 provides(unifies) the initialisation, so you can do it in this way:

string* pStr = new string[3] { "hi", "there"};

See http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init

Is there a wikipedia API just for retrieve content summary?

Since 2017 Wikipedia provides a REST API with better caching. In the documentation you can find the following API which perfectly fits your use case. (as it is used by the new Page Previews feature)

https://en.wikipedia.org/api/rest_v1/page/summary/Stack_Overflow returns the following data which can be used to display a summery with a small thumbnail:

{
  "type": "standard",
  "title": "Stack Overflow",
  "displaytitle": "Stack Overflow",
  "extract": "Stack Overflow is a question and answer site for professional and enthusiast programmers. It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.",
  "extract_html": "<p><b>Stack Overflow</b> is a question and answer site for professional and enthusiast programmers. It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of <i>Coding Horror</i>, Atwood's popular programming blog.</p>",
  "namespace": {
    "id": 0,
    "text": ""
  },
  "wikibase_item": "Q549037",
  "titles": {
    "canonical": "Stack_Overflow",
    "normalized": "Stack Overflow",
    "display": "Stack Overflow"
  },
  "pageid": 21721040,
  "thumbnail": {
    "source": "https://upload.wikimedia.org/wikipedia/en/thumb/f/fa/Stack_Overflow_homepage%2C_Feb_2017.png/320px-Stack_Overflow_homepage%2C_Feb_2017.png",
    "width": 320,
    "height": 149
  },
  "originalimage": {
    "source": "https://upload.wikimedia.org/wikipedia/en/f/fa/Stack_Overflow_homepage%2C_Feb_2017.png",
    "width": 462,
    "height": 215
  },
  "lang": "en",
  "dir": "ltr",
  "revision": "902900099",
  "tid": "1a9cdbc0-949b-11e9-bf92-7cc0de1b4f72",
  "timestamp": "2019-06-22T03:09:01Z",
  "description": "website hosting questions and answers on a wide range of topics in computer programming",
  "content_urls": {
    "desktop": {
      "page": "https://en.wikipedia.org/wiki/Stack_Overflow",
      "revisions": "https://en.wikipedia.org/wiki/Stack_Overflow?action=history",
      "edit": "https://en.wikipedia.org/wiki/Stack_Overflow?action=edit",
      "talk": "https://en.wikipedia.org/wiki/Talk:Stack_Overflow"
    },
    "mobile": {
      "page": "https://en.m.wikipedia.org/wiki/Stack_Overflow",
      "revisions": "https://en.m.wikipedia.org/wiki/Special:History/Stack_Overflow",
      "edit": "https://en.m.wikipedia.org/wiki/Stack_Overflow?action=edit",
      "talk": "https://en.m.wikipedia.org/wiki/Talk:Stack_Overflow"
    }
  },
  "api_urls": {
    "summary": "https://en.wikipedia.org/api/rest_v1/page/summary/Stack_Overflow",
    "metadata": "https://en.wikipedia.org/api/rest_v1/page/metadata/Stack_Overflow",
    "references": "https://en.wikipedia.org/api/rest_v1/page/references/Stack_Overflow",
    "media": "https://en.wikipedia.org/api/rest_v1/page/media/Stack_Overflow",
    "edit_html": "https://en.wikipedia.org/api/rest_v1/page/html/Stack_Overflow",
    "talk_page_html": "https://en.wikipedia.org/api/rest_v1/page/html/Talk:Stack_Overflow"
  }
}

By default, it follows redirects (so that /api/rest_v1/page/summary/StackOverflow also works), but this can be disabled with ?redirect=false

If you need to access the API from another domain you can set the CORS header with &origin= (e.g. &origin=*)

Update 2019: The API seems to return more useful information about the page.

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

Regular Expression for matching parentheses

For any special characters you should use '\'. So, for matching parentheses - /\(/

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

Python installation folder > Lib > idlelib > idle.pyw

send a shortcut to desktop.

From the desktop shortcut you can add it to taskbar too for quickaccess.

Hope this helps.

Compiler error "archive for required library could not be read" - Spring Tool Suite

Just had this problem on Indigo SR2. It popped up after I removed a superfluous jar from the classpath (build path). Restarting Eclipse didn't help. Added back the jar to the build path...error went away. Removed the jar once again, and this time I was spared from another complaint.

How to print without newline or space?

Many of these answers seem a little complicated. In Python 3.x you simply do this:

print(<expr>, <expr>, ..., <expr>, end=" ")

The default value of end is "\n". We are simply changing it to a space or you can also use end="" (no space) to do what printf normally does.

?: operator (the 'Elvis operator') in PHP

Elvis operator:

?: is the Elvis operator. This is a binary operator which does the following:

Coerces the value left of ?: to a boolean and checks if it is true. If true it will return the expression on the left side, if false it will return the expression on the right side.

Example:

var_dump(0 ?: "Expression not true");     // expression returns: Expression not true
var_dump("" ?: "Expression not true");    // expression returns: Expression not true
var_dump("hi" ?: "Expression not true");  // expression returns string hi
var_dump(null ?: "Expression not true");  // expression returns: Expression not true
var_dump(56 ?: "Expression not true");    // expression return int 56

When to use:

The Elvis operator is basically shorthand syntax for a specific case of the ternary operator which is:

$testedVar ? $ testedVar : $otherVar;

The Elvis operator will make the syntax more consise in the following manner:

$testedVar ?: $otherVar;

Difference between "managed" and "unmanaged"

Managed Code

Managed code is what Visual Basic .NET and C# compilers create. It runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. So, think of it as, "My code is managed by the CLR."

Visual Basic and C# can only produce managed code, so, if you're writing an application in one of those languages you are writing an application managed by the CLR. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it's optional.

Unmanaged Code

Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.

No free memory management or anything else the CLR provides.

Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

Mixing the two

Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application. This blurs the line between the two and complicates the definition, but it's worth mentioning just so you know that you can still have memory leaks if, for example, you're using a third party library with some badly written unmanaged code.

Here's an example I found by googling:

#using <mscorlib.dll>
using namespace System;

#include "stdio.h"

void ManagedFunction()
{
    printf("Hello, I'm managed in this section\n");
}

#pragma unmanaged
UnmanagedFunction()
{
    printf("Hello, I am unmanaged through the wonder of IJW!\n");
    ManagedFunction();
}

#pragma managed
int main()
{
    UnmanagedFunction();
    return 0;
}

Preloading CSS Images

try with this:

var c=new Image("Path to the background image");
c.onload=function(){
   //render the form
}

With this code you preload the background image and render the form when it's loaded

SmartGit Installation and Usage on Ubuntu

Now on the Smartgit webpage (I don't know since when) there is the possibility to download directly the .deb package. Once installed, it will upgrade automagically itself when a new version is released.

Remove specific characters from a string in Javascript

Another way to do it:

rnum = rnum.split("F0").pop()

It splits the string into two: ["", "123456"], then selects the last element.

Find duplicate records in MySQL

    Find duplicate Records:

    Suppose we have table : Student 
    student_id int
    student_name varchar
    Records:
    +------------+---------------------+
    | student_id | student_name        |
    +------------+---------------------+
    |        101 | usman               |
    |        101 | usman               |
    |        101 | usman               |
    |        102 | usmanyaqoob         |
    |        103 | muhammadusmanyaqoob |
    |        103 | muhammadusmanyaqoob |
    +------------+---------------------+

    Now we want to see duplicate records
    Use this query:


   select student_name,student_id ,count(*) c from student group by student_id,student_name having c>1;

+--------------------+------------+---+
| student_name        | student_id | c |
+---------------------+------------+---+
| usman               |        101 | 3 |
| muhammadusmanyaqoob |        103 | 2 |
+---------------------+------------+---+

iPhone 6 and 6 Plus Media Queries

Just so you know the iPhone 6 lies about it's min-width. It thinks it is 320 instead of 375 it is suppose to be.

@media only screen and (max-device-width: 667px) 
and (-webkit-device-pixel-ratio: 2) {

}

This was the only thing I could get to work to target the iPhone 6. The 6+ works fine the using this method:

@media screen and (min-device-width : 414px) 
and (max-device-height : 736px) and (max-resolution: 401dpi)
{

}

Delete all the queues from RabbitMQ?

With rabbitmqadmin you can remove them with this one-liner:

rabbitmqadmin -f tsv -q list queues name | while read queue; do rabbitmqadmin -q delete queue name=${queue}; done

Get sum of MySQL column in PHP

MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.

Method #1

$qry = "SELECT column_value AS count
        FROM table_name ";

$res = $db->query($qry);

$total = 0;
while ($rec = $db->fetchAssoc($res)) {
    $total += $rec['count'];
}
echo "Total: " . $total . "\n";

Method #2

$qry = "SELECT SUM(column_value) AS count 
        FROM table_name ";

$res = $db->query($qry);

$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];

echo "Total: " . $total . "\n";

Method #3 -SQLi

$qry = "SELECT SUM(column_value) AS count 
        FROM table_name ";

$res = $conn->query($sql);

$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];

echo "Total: " . $total . "\n";

Method #4: Depreciated (don't use)

$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name'); 
$row = mysql_fetch_assoc($res); 
$sum = $row['count'];

How do you merge two Git repositories?

If you want to merge project-a into project-b:

cd path/to/project-b
git remote add project-a /path/to/project-a
git fetch project-a --tags
git merge --allow-unrelated-histories project-a/master # or whichever branch you want to merge
git remote remove project-a

Taken from: git merge different repositories?

This method worked pretty well for me, it's shorter and in my opinion a lot cleaner.

In case you want to put project-a into a subdirectory, you can use git-filter-repo (filter-branch is discouraged). Run the following commands before the commands above:

cd path/to/project-a
git filter-repo --to-subdirectory-filter project-a

An example of merging 2 big repositories, putting one of them into a subdirectory: https://gist.github.com/x-yuri/9890ab1079cf4357d6f269d073fd9731

Note: The --allow-unrelated-histories parameter only exists since git >= 2.9. See Git - git merge Documentation / --allow-unrelated-histories

Update: Added --tags as suggested by @jstadler in order to keep tags.

Pip Install not installing into correct directory?

I totally agree with the guys, it's better to use virtualenv so you can set a custom environment for every project. It ideal for maintenance because it's like a different world for every project and every update of an application you make won't interfere with other projects.

Here you can find a nutshell of virtualenv related to installation and first steps.

Member '<method>' cannot be accessed with an instance reference

In C#, unlike VB.NET and Java, you can't access static members with instance syntax. You should do:

MyClass.MyItem.Property1

to refer to that property or remove the static modifier from Property1 (which is what you probably want to do). For a conceptual idea about what static is, see my other answer.

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

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

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

WebView link click open default browser

I had to do the same thing today and I have found a very useful answer on StackOverflow that I want to share here in case someone else needs it.

Source (from sven)

webView.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
            view.getContext().startActivity(
                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
});

Argument of type 'X' is not assignable to parameter of type 'X'

In my case, strangely enough, I was missing the import of the class it was complaining about and my IDE didn't detect it.

How to get highcharts dates in the x axis?

You write like this-:

xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
           day: '%d %b %Y'    //ex- 01 Jan 2016
        }
}

also check for other datetime format

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

jQuery autoComplete view all on click?

In order to show all items / simulate combobox behavior, you should first ensure you have set the minLength option to 0 (default is 1). Then you can bind the click event to perform a search with the empty string.

$('inputSelector').autocomplete({ minLength: 0 });
$('inputSelector').click(function() { $(this).autocomplete("search", ""); });

Java Replace Line In Text File

just how to replace strings :) as i do first arg will be filename second target string third one the string to be replaced instead of targe

public class ReplaceString{
      public static void main(String[] args)throws Exception {
        if(args.length<3)System.exit(0);
        String targetStr = args[1];
        String altStr = args[2];
        java.io.File file = new java.io.File(args[0]);
        java.util.Scanner scanner = new java.util.Scanner(file);
        StringBuilder buffer = new StringBuilder();
        while(scanner.hasNext()){
          buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
          if(scanner.hasNext())buffer.append("\n");
        }
        scanner.close();
        java.io.PrintWriter printer = new java.io.PrintWriter(file);
        printer.print(buffer);
        printer.close();
      }
    }

How to save traceback / sys.exc_info() values in a variable?

Use traceback.extract_stack() if you want convenient access to module and function names and line numbers.

Use ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.

Notice that even with ''.join() you will get a multi-line string, since the elements of format_stack() contain \n. See output below.

Remember to import traceback.

Here's the output from traceback.extract_stack(). Formatting added for readability.

>>> traceback.extract_stack()
[
   ('<string>', 1, '<module>', None),
   ('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
   ('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
   ('<pyshell#1>', 1, '<module>', None)
]

Here's the output from ''.join(traceback.format_stack()). Formatting added for readability.

>>> ''.join(traceback.format_stack())
'  File "<string>", line 1, in <module>\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
       ret = method(*args, **kwargs)\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
       exec(code, self.locals)\n  File "<pyshell#2>", line 1, in <module>\n'

Java creating .jar file

Put all the 6 classes to 6 different projects. Then create jar files of all the 6 projects. In this manner you will get 6 executable jar files.

How can I connect to MySQL in Python 3 on Windows?

This does not fully answer my original question, but I think it is important to let everyone know what I did and why.

I chose to continue using python 2.7 instead of python 3 because of the prevalence of 2.7 examples and modules on the web in general.

I now use both mysqldb and mysql.connector to connect to MySQL in Python 2.7. Both are great and work well. I think mysql.connector is ultimately better long term however.

How to use a DataAdapter with stored procedure and parameter

public class SQLCon
{
  public static string cs = 
   ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
protected void Page_Load(object sender, EventArgs e)
{
    SqlDataAdapter MyDataAdapter;
    SQLCon cs = new SQLCon();
    DataSet RsUser = new DataSet();
    RsUser = new DataSet();
    using (SqlConnection MyConnection = new SqlConnection(SQLCon.cs))
       {
        MyConnection.Open();
        MyDataAdapter = new SqlDataAdapter("GetAPPID", MyConnection);
        //'Set the command type as StoredProcedure.
        MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
        RsUser = new DataSet();
        MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@organizationID", 
        SqlDbType.Int));
        MyDataAdapter.SelectCommand.Parameters["@organizationID"].Value = TxtID.Text;
        MyDataAdapter.Fill(RsUser, "GetAPPID");
       }

      if (RsUser.Tables[0].Rows.Count > 0) //data was found
      {
        Session["AppID"] = RsUser.Tables[0].Rows[0]["AppID"].ToString();
       }
     else
       {

       }    
}    

Meaning of 'const' last in a function declaration of a class?

Here const means that at that function any variable's value can not change

class Test{
private:
    int a;
public:
    void test()const{
        a = 10;
    }
};

And like this example, if you try to change the value of a variable in the test function you will get an error.

How can I build XML in C#?

The best thing hands down that I have tried is LINQ to XSD (which is unknown to most developers). You give it an XSD Schema and it generates a perfectly mapped complete strongly-typed object model (based on LINQ to XML) for you in the background, which is really easy to work with - and it updates and validates your object model and XML in real-time. While it's still "Preview", I have not encountered any bugs with it.

If you have an XSD Schema that looks like this:

  <xs:element name="RootElement">
     <xs:complexType>
      <xs:sequence>
        <xs:element name="Element1" type="xs:string" />
        <xs:element name="Element2" type="xs:string" />
      </xs:sequence>
       <xs:attribute name="Attribute1" type="xs:integer" use="optional" />
       <xs:attribute name="Attribute2" type="xs:boolean" use="required" />
     </xs:complexType>
  </xs:element>

Then you can simply build XML like this:

RootElement rootElement = new RootElement;
rootElement.Element1 = "Element1";
rootElement.Element2 = "Element2";
rootElement.Attribute1 = 5;
rootElement.Attribute2 = true;

Or simply load an XML from file like this:

RootElement rootElement = RootElement.Load(filePath);

Or save it like this:

rootElement.Save(string);
rootElement.Save(textWriter);
rootElement.Save(xmlWriter);

rootElement.Untyped also yields the element in form of a XElement (from LINQ to XML).

Phone number formatting an EditText in Android

There is a library called PhoneNumberUtils that can help you to cope with phone number conversions and comparisons. For instance, use ...

EditText text = (EditText) findViewById(R.id.editTextId);
PhoneNumberUtils.formatNumber(text.getText().toString())

... to format your number in a standard format.

PhoneNumberUtils.compare(String a, String b);

... helps with fuzzy comparisons. There are lots more. Check out http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html for more.

p.s. setting the the EditText to phone is already a good choice; eventually it might be helpful to add digits e.g. in your layout it looks as ...

<EditText
    android:id="@+id/editTextId"
    android:inputType="phone"
    android:digits="0123456789+" 
/> 

PKIX path building failed in Java application

In my case the issue was resolved by installing Oracle's official JDK 10 as opposed to using the default OpenJDK that came with my Ubuntu. This is the guide I followed: https://www.linuxuprising.com/2018/04/install-oracle-java-10-in-ubuntu-or.html

How to scroll up or down the page to an anchor using jQuery?

You may want to add offsetTop and scrollTop value in case You are animating not the whole page , but rather some nested content.

e.g :

var itemTop= $('.letter[name="'+id+'"]').offset().top;
var offsetTop = $someWrapper.offset().top;
var scrollTop = $someWrapper.scrollTop();
var y = scrollTop + letterTop - offsetTop

this.manage_list_wrap.animate({
  scrollTop: y
}, 1000);

Javascript: Setting location.href versus location

Like as has been said already, location is an object. But that person suggested using either. But, you will do better to use the .href version.

Objects have default properties which, if nothing else is specified, they are assumed. In the case of the location object, it has a property called .href. And by not specifying ANY property during the assignment, it will assume "href" by default.

This is all well and fine until a later object model version changes and there either is no longer a default property, or the default property is changed. Then your program breaks unexpectedly.

If you mean href, you should specify href.

Changing Placeholder Text Color with Swift

I'm surprised to see how many poor solutions there are here.

Here is a version that will always work.

Swift 4.2

extension UITextField{
    @IBInspectable var placeholderColor: UIColor {
        get {
            return self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .lightText
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [.foregroundColor: newValue])
        }
    }
}

TIP: If you change the placeholder text after setting the color- the color will reset.

Find stored procedure by name

For SQL Server version 9.0 (2005), you can use the code below:

select * 
from 
syscomments c
inner join sys.procedures p on p.object_id = c.id
where 
p.name like '%usp_ConnectionsCount%';

Have bash script answer interactive prompts

There is a special build-in util for this - 'yes'.

To answer all questions with the same answer, you can run

yes [answer] |./your_script

Or you can put it inside your script have specific answer to each question

Compute row average in pandas

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

How to determine the last Row used in VBA including blank spaces in between

ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.count).row

ActiveSheet can be replaced with WorkSheets(1) or WorkSheets("name here")

Get the key corresponding to the minimum value within a dictionary

>>> d = {320:1, 321:0, 322:3}
>>> min(d, key=lambda k: d[k]) 
321

How can I send an inner <div> to the bottom of its parent <div>?

Make the outer div position="relative" and the inner div position="absolute" and set it's bottom="0".

php Replacing multiple spaces with a single space

$output = preg_replace('/\s+/', ' ',$input);

\s is shorthand for [ \t\n\r]. Multiple spaces will be replaced with single space.

Cannot deserialize the current JSON array (e.g. [1,2,3])

This could be You

Before trying to consume your json object with another object just check that the api is returning raw json via the browser api/rootobject, for my case i found out that the underlying data provider mssqlserver was not running and throw an unhanded exception !

as simple as that :)

Git copy file preserving history

All you have to do is:

  1. move the file to two different locations,
  2. merge the two commits that do the above, and
  3. move one copy back to the original location.

You will be able to see historical attributions (using git blame) and full history of changes (using git log) for both files.

Suppose you want to create a copy of file foo called bar. In that case the workflow you'd use would look like this:

git mv foo bar
git commit

SAVED=`git rev-parse HEAD`
git reset --hard HEAD^
git mv foo copy
git commit

git merge $SAVED     # This will generate conflicts
git commit -a        # Trivially resolved like this

git mv copy foo
git commit

Why this works

After you execute the above commands, you end up with a revision history that looks like this:

( revision history )            ( files )

    ORIG_HEAD                      foo
     /     \                      /   \
SAVED       ALTERNATE          bar     copy
     \     /                      \   /
      MERGED                     bar,copy
        |                           |
     RESTORED                    bar,foo

When you ask Git about the history of foo, it will:

  1. detect the rename from copy between MERGED and RESTORED,
  2. detect that copy came from the ALTERNATE parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and ALTERNATE.

From there it will dig into the history of foo.

When you ask Git about the history of bar, it will:

  1. notice no change between MERGED and RESTORED,
  2. detect that bar came from the SAVED parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and SAVED.

From there it will dig into the history of foo.

It's that simple. :)

You just need to force Git into a merge situation where you can accept two traceable copies of the file(s), and we do this with a parallel move of the original (which we soon revert).

Get local IP address

Pre requisites: you have to add System.Data.Linq reference and refer it

using System.Linq;
string ipAddress ="";
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
ipAddress = Convert.ToString(ipHostInfo.AddressList.FirstOrDefault(address => address.AddressFamily == AddressFamily.InterNetwork));

Angular 2 - innerHTML styling

If you are using sass as style preprocessor, you can switch back to native Sass compiler for dev dependency by:

npm install node-sass --save-dev

So that you can keep using /deep/ for development.

React-Router open Link in new tab

The simples way is to use 'to' property:

<Link to="chart" target="_blank" to="http://link2external.page.com" >Test</Link>

How can I print variable and string on same line in Python?

You can either use a formatstring:

print "There are %d births" % (births,)

or in this simple case:

print "There are ", births, "births"

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

How to remove RVM (Ruby Version Manager) from my system

Note that if you installed RVM via apt-get, you have to run some further steps than rvm implode or apt-get remove ruby-rvm to get it to really uninstall.

See "Installing RVM on Ubuntu".

How to create local notifications?

Updated with Swift 5 Generally we use three type of Local Notifications

  1. Simple Local Notification
  2. Local Notification with Action
  3. Local Notification with Content

Where you can send simple text notification or with action button and attachment.

Using UserNotifications package in your app, the following example Request for notification permission, prepare and send notification as per user action AppDelegate itself, and use view controller listing different type of local notification test.

AppDelegate

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    let notificationCenter = UNUserNotificationCenter.current()
    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        //Confirm Delegete and request for permission
        notificationCenter.delegate = self
        let options: UNAuthorizationOptions = [.alert, .sound, .badge]
        notificationCenter.requestAuthorization(options: options) {
            (didAllow, error) in
            if !didAllow {
                print("User has declined notifications")
            }
        }

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
    }
    func applicationDidEnterBackground(_ application: UIApplication) {
    }
    func applicationWillEnterForeground(_ application: UIApplication) {
    }
    func applicationWillTerminate(_ application: UIApplication) {
    }
    func applicationDidBecomeActive(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
    }


    //MARK: Local Notification Methods Starts here

    //Prepare New Notificaion with deatils and trigger
    func scheduleNotification(notificationType: String) {

        //Compose New Notificaion
        let content = UNMutableNotificationContent()
        let categoryIdentifire = "Delete Notification Type"
        content.sound = UNNotificationSound.default
        content.body = "This is example how to send " + notificationType
        content.badge = 1
        content.categoryIdentifier = categoryIdentifire

        //Add attachment for Notification with more content
        if (notificationType == "Local Notification with Content")
        {
            let imageName = "Apple"
            guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
            let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
            content.attachments = [attachment]
        }

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let identifier = "Local Notification"
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

        notificationCenter.add(request) { (error) in
            if let error = error {
                print("Error \(error.localizedDescription)")
            }
        }

        //Add Action button the Notification
        if (notificationType == "Local Notification with Action")
        {
            let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
            let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
            let category = UNNotificationCategory(identifier: categoryIdentifire,
                                                  actions: [snoozeAction, deleteAction],
                                                  intentIdentifiers: [],
                                                  options: [])
            notificationCenter.setNotificationCategories([category])
        }
    }

    //Handle Notification Center Delegate methods
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        if response.notification.request.identifier == "Local Notification" {
            print("Handling notifications with the Local Notification Identifier")
        }
        completionHandler()
    }
}

and ViewController

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var appDelegate = UIApplication.shared.delegate as? AppDelegate
    let notifications = ["Simple Local Notification",
                         "Local Notification with Action",
                         "Local Notification with Content",]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK: - Table view data source

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return notifications.count
    }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = notifications[indexPath.row]
        return cell
    }

     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let notificationType = notifications[indexPath.row]
        let alert = UIAlertController(title: "",
                                      message: "After 5 seconds " + notificationType + " will appear",
                                      preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Okay, I will wait", style: .default) { (action) in
            self.appDelegate?.scheduleNotification(notificationType: notificationType)
        }
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    }
}

What does `set -x` do?

set -x enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.

set +x disables it.

T-SQL Cast versus Convert

Convert has a style parameter for date to string conversions.

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

How to select top n rows from a datatable/dataview in ASP.NET

myDataTable.AsEnumerable().Take(5).CopyToDataTable()

CSS Circle with border

You are missing the border width and the border style properties in the Border shorthand property :

_x000D_
_x000D_
.circle {
    border: 2px solid red;
    background-color: #FFFFFF;
    height: 100px;
    border-radius:50%;
    width: 100px;
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_


Also, You can use percentages for the border-radius property so that the value isn't dependent of the circle width/height. That is why I used 50% for border-radius (more info on border-radius in pixels and percent).

Side note : In your example, you didn't specify the border-radius property without vendor prefixes whitch you propably don't need as only browsers before chrome 4 safari 4 and Firefox 3.6 use them (see canIuse).

Java String remove all non numeric characters

Currency decimal separator can be different from Locale to another. It could be dangerous to consider . as separator always. i.e.

+------------------------------------+
¦    Locale      ¦      Sample       ¦
¦----------------+-------------------¦
¦ USA            ¦ $1,222,333.44 USD ¦
¦ United Kingdom ¦ £1.222.333,44 GBP ¦
¦ European       ¦ €1.333.333,44 EUR ¦
+------------------------------------+

I think the proper way is:

  • Get decimal character via DecimalFormatSymbols by default Locale or specified one.
  • Cook regex pattern with decimal character in order to obtain digits only

And here how I am solving it:

code:

import java.text.DecimalFormatSymbols;
import java.util.Locale;

    public static String getDigit(String quote, Locale locale) {
    char decimalSeparator;
    if (locale == null) {
        decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
    } else {
        decimalSeparator = new DecimalFormatSymbols(locale).getDecimalSeparator();
    }

    String regex = "[^0-9" + decimalSeparator + "]";
    String valueOnlyDigit = quote.replaceAll(regex, "");
    try {
        return valueOnlyDigit;
    } catch (ArithmeticException | NumberFormatException e) {
        Log.e(TAG, "Error in getMoneyAsDecimal", e);
        return null;
    }
    return null;
}

I hope that may help,'.

Disabling enter key for form

try this ^^

$(document).ready(function() {
        $("form").bind("keypress", function(e) {
            if (e.keyCode == 13) {
                return false;
            }
        });
    });

Hope this helps

Problems when trying to load a package in R due to rJava

If you have this issue with macOS, there is no easy way here: ( Especially, when you want to use R3.4. I have been there already.

R 3.4, rJava, macOS and even more mess

For R3.3 it's a little bit easier (R3.3 was compiled using different compiler).

R, Java, rJava and macOS adventures

Python script header

The Python executable might be installed at a location other than /usr/bin, but env is nearly always present in that location so using /usr/bin/envis more portable.

How do I declare a 2d array in C++ using new?

There are two general techniques that I would recommend for this in C++11 and above, one for compile time dimensions and one for run time. Both answers assume you want uniform, two-dimensional arrays (not jagged ones).

Compile time dimensions

Use a std::array of std::array and then use new to put it on the heap:

// the alias helps cut down on the noise:
using grid = std::array<std::array<int, sizeX>, sizeY>;
grid * ary = new grid;

Again, this only works if the sizes of the dimensions are known at compile time.

Run time dimensions

The best way to accomplish a 2 dimensional array with sizes only known at runtime is to wrap it into a class. The class will allocate a 1d array and then overload operator [] to provide indexing for the first dimension. This works because in C++ a 2D array is row-major:

 matrix shown in logical form and one-dimensional form

(Taken from http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)

A contiguous sequence of memory is good for performance reasons and is also easy to clean up. Here's an example class that omits a lot of useful methods but shows the basic idea:

#include <memory>

class Grid {
  size_t _rows;
  size_t _columns;
  std::unique_ptr<int[]> data;

public:
  Grid(size_t rows, size_t columns)
      : _rows{rows},
        _columns{columns},
        data{std::make_unique<int[]>(rows * columns)} {}

  size_t rows() const { return _rows; }

  size_t columns() const { return _columns; }

  int *operator[](size_t row) { return row * _columns + data.get(); }

  int &operator()(size_t row, size_t column) {
    return data[row * _columns + column];
  }
}

So we create an array with std::make_unique<int[]>(rows * columns) entries. We overload operator [] which will index the row for us. It returns an int * which points to the beginning of the row, which can then be dereferenced as normal for the column. Note that make_unique first ships in C++14 but you can polyfill it in C++11 if necessary.

It's also common for these types of structures to overload operator() as well:

  int &operator()(size_t row, size_t column) {
    return data[row * _columns + column];
  }

Technically I haven't used new here, but it's trivial to move from std::unique_ptr<int[]> to int * and use new/delete.

How to test my servlet using JUnit

You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the 'result' and verify it's correct.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public class TestMyServlet extends Mockito{

    @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    

        when(request.getParameter("username")).thenReturn("me");
        when(request.getParameter("password")).thenReturn("secret");

        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        when(response.getWriter()).thenReturn(writer);

        new MyServlet().doPost(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(stringWriter.toString().contains("My expected string"));
    }
}

Java reading a file into an ArrayList?

You can use:

List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );

Source: Java API 7.0

select into in mysql

Use the CREATE TABLE SELECT syntax.

http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

Select n random rows from SQL Server table

It appears newid() can't be used in where clause, so this solution requires an inner query:

SELECT *
FROM (
    SELECT *, ABS(CHECKSUM(NEWID())) AS Rnd
    FROM MyTable
) vw
WHERE Rnd % 100 < 10        --10%

How do I select last 5 rows in a table without sorting?

You can retrieve them from memory.
So first you get the rows in a DataSet, and then get the last 5 out of the DataSet.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

XHR polling vs SSE vs WebSockets

  • XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.

    The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia

  • Server Sent Events Client sends request to server. Server sends new data to webpage at any time.

    Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla

  • WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.

    The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia

Change background color of edittext in android

I worked out a working solution to this problem after 2 days of struggle, below solution is perfect for them who want to change few edit text only, change/toggle color through java code, and want to overcome the problems of different behavior on OS versions due to use setColorFilter() method.

    import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import com.newco.cooltv.R;

public class RqubeErrorEditText extends AppCompatEditText {

  private int errorUnderlineColor;
  private boolean isErrorStateEnabled;
  private boolean mHasReconstructedEditTextBackground;

  public RqubeErrorEditText(Context context) {
    super(context);
    initColors();
  }

  public RqubeErrorEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    initColors();
  }

  public RqubeErrorEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initColors();
  }

  private void initColors() {
    errorUnderlineColor = R.color.et_error_color_rule;

  }

  public void setErrorColor() {
    ensureBackgroundDrawableStateWorkaround();
    getBackground().setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
        ContextCompat.getColor(getContext(), errorUnderlineColor), PorterDuff.Mode.SRC_IN));
  }

  private void ensureBackgroundDrawableStateWorkaround() {
    final Drawable bg = getBackground();
    if (bg == null) {
      return;
    }
    if (!mHasReconstructedEditTextBackground) {
      // This is gross. There is an issue in the platform which affects container Drawables
      // where the first drawable retrieved from resources will propogate any changes
      // (like color filter) to all instances from the cache. We'll try to workaround it...
      final Drawable newBg = bg.getConstantState().newDrawable();
      //if (bg instanceof DrawableContainer) {
      //  // If we have a Drawable container, we can try and set it's constant state via
      //  // reflection from the new Drawable
      //  mHasReconstructedEditTextBackground =
      //      DrawableUtils.setContainerConstantState(
      //          (DrawableContainer) bg, newBg.getConstantState());
      //}
      if (!mHasReconstructedEditTextBackground) {
        // If we reach here then we just need to set a brand new instance of the Drawable
        // as the background. This has the unfortunate side-effect of wiping out any
        // user set padding, but I'd hope that use of custom padding on an EditText
        // is limited.
        setBackgroundDrawable(newBg);
        mHasReconstructedEditTextBackground = true;
      }
    }
  }

  public boolean isErrorStateEnabled() {
    return isErrorStateEnabled;
  }

  public void setErrorState(boolean isErrorStateEnabled) {
    this.isErrorStateEnabled = isErrorStateEnabled;
    if (isErrorStateEnabled) {
      setErrorColor();
      invalidate();
    } else {
      getBackground().mutate().clearColorFilter();
      invalidate();
    }
  }
}

Uses in xml

<com.rqube.ui.widget.RqubeErrorEditText
            android:id="@+id/f_signup_et_referral_code"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toEndOf="@+id/referral_iv"
            android:layout_toRightOf="@+id/referral_iv"
            android:ems="10"
            android:hint="@string/lbl_referral_code"
            android:imeOptions="actionNext"
            android:inputType="textEmailAddress"
            android:textSize="@dimen/text_size_sp_16"
            android:theme="@style/EditTextStyle"/>

Add lines in style

<style name="EditTextStyle" parent="android:Widget.EditText">
    <item name="android:textColor">@color/txt_color_change</item>
    <item name="android:textColorHint">@color/et_default_color_text</item>
    <item name="colorControlNormal">@color/et_default_color_rule</item>
    <item name="colorControlActivated">@color/et_engagged_color_rule</item>
  </style>

java code to toggle color

myRqubeEditText.setErrorState(true);
myRqubeEditText.setErrorState(false);

Find if variable is divisible by 2

Seriously, there's no jQuery plugin for odd/even checks?

Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.

Source code is also available at http://jsfiddle.net/7HQNG/

Test-suites are available at http://jsfiddle.net/zeuRV/

(function() {
    /*
     * isEven(n)
     * @args number n
     * @return boolean returns whether the given number is even
     */
    jQuery.isEven = function(number) {
        return number % 2 == 0;
    };

    /* isOdd(n)
     * @args number n
     * @return boolean returns whether the given number is odd
     */
    jQuery.isOdd = function(number) {
        return !jQuery.isEven(number);
    };
})();?

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

For me, my issue was that I was

android:background="?attr/selectableItemBackground"

To a LinearLayout background, once I removed it the test passed.

ASP.Net which user account running Web Service on IIS 7?

I had a ton of trouble with this and then found a great solution:

Create a file in a text editor called whoami.php with the below code as it's content, save the file and upload it to public_html (or whatever you root of your webserver directory is named). It should output a useful string that you can use to track down the user the webserver is running as, my output was "php is running as user: nt authority\iusr" which allowed me to track down the permissions I needed to modify to the user "IUSR".

<?php
  // outputs the username that owns the running php/httpd process
  // (on a system with the "whoami" executable in the path)
  echo 'php is running as user: ' . exec('whoami');
?>

Why do I need to override the equals and hashCode methods in Java?

IMHO, it's as per the rule says - If two objects are equal then they should have same hash, i.e., equal objects should produce equal hash values.

Given above, default equals() in Object is == which does comparison on the address, hashCode() returns the address in integer(hash on actual address) which is again distinct for distinct Object.

If you need to use the custom Objects in the Hash based collections, you need to override both equals() and hashCode(), example If I want to maintain the HashSet of the Employee Objects, if I don't use stronger hashCode and equals I may endup overriding the two different Employee Objects, this happen when I use the age as the hashCode(), however I should be using the unique value which can be the Employee ID.

Is there a portable way to get the current username in Python?

For UNIX, at least, this works...

import commands
username = commands.getoutput("echo $(whoami)")
print username

edit: I just looked it up and this works on Windows and UNIX:

import commands
username = commands.getoutput("whoami")

On UNIX it returns your username, but on Windows, it returns your user's group, slash, your username.

--

I.E.

UNIX returns: "username"

Windows returns: "domain/username"

--

It's interesting, but probably not ideal unless you are doing something in the terminal anyway... in which case you would probably be using os.system to begin with. For example, a while ago I needed to add my user to a group, so I did (this is in Linux, mind you)

import os
os.system("sudo usermod -aG \"group_name\" $(whoami)")
print "You have been added to \"group_name\"! Please log out for this to take effect"

I feel like that is easier to read and you don't have to import pwd or getpass.

I also feel like having "domain/user" could be helpful in certain applications in Windows.

Git Bash is extremely slow on Windows 7 x64

In my case, the Git Bash shortcut was set to Start in:%HOMEDRIVE%%HOMEPATH% (you can check this by right clicking Git Bash and selecting properties). This was the network drive.

The solution is to make it point to %HOME%. If you do not have it, you can set it up in the environment variables and now Git Bash should be lightning fast.

How do you execute an arbitrary native command from a string?

Invoke-Expression, also aliased as iex. The following will work on your examples #2 and #3:

iex $command

Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:

$command = 'C:\somepath\someexe.exe somearg'
iex $command

However, if the exe is in quotes, you need the help of & to get it running, as in this example, as run from the commandline:

>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"

And then in the script:

$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"

Likely, you could handle nearly all cases by detecting if the first character of the command string is ", like in this naive implementation:

function myeval($command) {
    if ($command[0] -eq '"') { iex "& $command" }
    else { iex $command }
}

But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}, perhaps for specific exception types/messages, or examine the command string.

If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.

Setting up enviromental variables in Windows 10 to use java and javac

if you have any version problems (javac -version=15.0.1, java -version=1.8.0)
windows search : edit environment variables for your account
then delete these in your windows Environment variable: system variable: Path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
C:\Program Files\Common Files\Oracle\Java\javapath

then if you're using java 15
environment variable: system variable : Path
add path C:\Program Files\Java\jdk-15.0.1\bin
is enough

if you're using java 8

  • create JAVA_HOME
  • environment variable: system variable : JAVA_HOME
    JAVA_HOME = C:\Program Files\Java\jdk1.8.0_271
  • environment variable: system variable : Path
    add path = %JAVA_HOME%\bin
  • How to store image in SQL Server database tables column

    Insert Into FEMALE(ID, Image)
    Select '1', BulkColumn 
    from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image
    

    You will also need admin rights to run the query.

    Excel Reference To Current Cell

    Without INDIRECT(): =CELL("width", OFFSET($A$1,ROW()-1,COLUMN()-1) )

    Javascript onclick hide div

    Simple & Best way:

    onclick="parentNode.remove()"
    

    Deletes the complete parent from html

    IIS Express Windows Authentication

    I'm using visual studio 2019 develop against ASP.Net application. Here's what been worked for us:

    1. Open your Project Property Windows, Disable Anonymous Authentication and Enable Windows Authentication
    2. In your Web.Config under system.web

    _x000D_
    _x000D_
    <authentication mode="Windows"></authentication>p
    _x000D_
    _x000D_
    _x000D_

    And I didn't change application.config in iis express.

    Edit a specific Line of a Text File in C#

    When you create a StreamWriter it always create a file from scratch, you will have to create a third file and copy from target and replace what you need, and then replace the old one. But as I can see what you need is XML manipulation, you might want to use XmlDocument and modify your file using Xpath.

    How to create global variables accessible in all views using Express / Node.JS?

    One way to do this by updating the app.locals variable for that app in app.js

    Set via following

    var app = express();
    app.locals.appName = "DRC on FHIR";
    

    Get / Access

    app.listen(3000, function () {
        console.log('[' + app.locals.appName + '] => app listening on port 3001!');
    });
    

    Elaborating with a screenshot from @RamRovi example with slight enhancement.

    enter image description here

    Uses of content-disposition in an HTTP response header

    For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition

    Basic usage:

    var cd = new System.Net.Mime.ContentDisposition();
    cd.FileName = "myFile.txt";
    cd.ModificationDate = DateTime.UtcNow;
    cd.Size = 100;
    Response.AppendHeader("content-disposition", cd.ToString());
    

    Get variable from PHP to JavaScript

    You can pass PHP Variables to your JavaScript by generating it with PHP:

    <?php
    $someVar = 1;
    ?>
    
    <script type="text/javascript">
        var javaScriptVar = "<?php echo $someVar; ?>";
    </script>
    

    Converting string to tuple without splitting characters

    You can use eval()

    >>> a = ['Quattro TT']  
    >>> eval(str(a))
    ['Quattro TT']
    

    How to get date and time from server

    You should set the timezone to the one of the timezones you want.

    // set default timezone
    date_default_timezone_set('America/Chicago'); // CDT
    
    $info = getdate();
    $date = $info['mday'];
    $month = $info['mon'];
    $year = $info['year'];
    $hour = $info['hours'];
    $min = $info['minutes'];
    $sec = $info['seconds'];
    
    $current_date = "$date/$month/$year == $hour:$min:$sec";
    

    Or a much shorter version:

    // set default timezone
    date_default_timezone_set('America/Chicago'); // CDT
    
    $current_date = date('d/m/Y == H:i:s');
    

    java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

    Use:

    ((Long) userService.getAttendanceList(currentUser)).intValue();
    

    instead.

    The .intValue() method is defined in class Number, which Long extends.

    How to install the current version of Go in Ubuntu Precise

    i installed from source. there is a step-by-step tutorial here: http://golang.org/doc/install/source

    In c++ what does a tilde "~" before a function name signify?

    That would be the destructor(freeing up any dynamic memory)

    Should I use px or rem value units in my CSS?

    Yes, REM and PX are relative yet other answers have suggested to go for REM over PX, I would also like to back this up using an accessibility example.
    When user sets different font-size on browser, REM automatically scale up and down elements like fonts, images etc on the webpage which is not the case with PX.


    In the below gif left side text is set using font size REM unit while right side font is set by PX unit.

    enter image description here

    As you can see that REM is scaling up/down automatically when I resize the default font-size of webpage.(bottom-right side)

    Default font-size of a webpage is 16px which is equal to 1 rem (only for default html page i.e. html{font-size:100%}), so, 1.25rem is equal to 20px.

    P.S: who else is using REM? CSS Frameworks! like Bootstrap 4, Bulma CSS etc, so better get along with it.

    How to export database schema in Oracle to a dump file

    It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

    Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

      SQL> select * from dba_directories;
    

    ... and if not, create one

      SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
      SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant
    

    Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

     $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
    

    Or specifying a specific directory, add directory=<directory name>:

     C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
    

    With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

     $ exp system/manager owner=user1 file=user1.dmp
    

    Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

    Example for American UTF8 (UNIX):

     $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
    

    Windows uses SET, example using Japanese UTF8:

     C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
    

    More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

    Conda command not found

    MacOSX: cd /Users/USER_NAME/anaconda3/bin && ./activate

    JavaScript: Passing parameters to a callback function

    If you are not sure how many parameters are you going to be passed into callback functions, use apply function.

    function tryMe (param1, param2) {
      alert (param1 + " and " + param2);
    }
    
    function callbackTester(callback,params){
        callback.apply(this,params);
    }
    
    callbackTester(tryMe,['hello','goodbye']);
    

    How to get a enum value from string in C#?

    var value = (uint)Enum.Parse(typeof(basekey), "HKEY_LOCAL_MACHINE", true);
    

    This code snippet illustrates obtaining an enum value from a string. To convert from a string, you need to use the static Enum.Parse() method, which takes 3 parameters. The first is the type of enum you want to consider. The syntax is the keyword typeof() followed by the name of the enum class in brackets. The second parameter is the string to be converted, and the third parameter is a bool indicating whether you should ignore case while doing the conversion.

    Finally, note that Enum.Parse() actually returns an object reference, that means you need to explicitly convert this to the required enum type(string,int etc).

    Thank you.

    PHP using Gettext inside <<<EOF string

    As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

    <?php
    
        $world = _("World");
    
        $str = <<<EOF
        <p>Hello</p>
        <p>$world</p>
    EOF;
        echo $str;
    ?>
    

    a workaround idea that comes to mind is building a class with a magic getter method.

    You would declare a class like this:

    class Translator
    {
     public function __get($name) {
      return _($name); // Does the gettext lookup
      }
     }
    

    Initialize an object of the class at some point:

      $translate = new Translator();
    

    You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

        $str = <<<EOF
        <p>Hello</p>
        <p>{$translate->World}</p>
    EOF;
        echo $str;
    ?>
    

    $translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

    To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

     $translate->{"Hello World!!!!!!"}
    

    This is all untested but should work.

    Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

    DSO missing from command line

    DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

    That is, try adding -lpthread to your command line.

    When to use Interface and Model in TypeScript / Angular

    I personally use interfaces for my models, There hoewver are 3 schools regarding this question, and choosing one is most often based on your requirements:

    1- Interfaces:

    interface is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. Once your code is transpiled to its target language, it will be stripped from its interfaces - JavaScript isn’t typed.

    interface User {
     id: number;
     username: string;
    }
    // inheritance
    interface UserDetails extends User {
     birthdate: Date;
     biography?: string;  // use the '?' annotation to mark this property as optionnal
    }
    

    Mapping server response to an interface is straight forward if you are using HttpClient from HttpClientModule if you are using Angular 4.3.x and above.

    getUsers() :Observable<User[]> {
     return this.http.get<User[]>(url); // no need for '.map((res: Response) => res.json())' 
    }
    

    when to use interfaces:

    • You only need the definition for the server data without introducing additional overhead for the final output.
    • You only need to transmit data without any behaviors or logic (constructor initialization, methods)
    • You do not instantiate/create objects from your interface very often
      • Using simple object-literal notationlet instance: FooInterface = { ... };, you risk having semi-instances all over the place.
      • That doesn't enforce the constraints given by a class ( constructor or initialization logic, validation, encapsulation of private fields...Etc)
    • You need to define contracts/configurations for your systems (global configurations)

    2- Classes:

    A class defines the blueprints of an object. They express the logic, methods, and properties these objects will inherit.

    class User {
     id: number;
     username: string;
     constructor(id :number, username: string)  {
      this.id = id;
      this.username = username.replace(/^\s+|\s+$/g, ''); // trim whitespaces and new lines
     }
    }
    // inheritance
    class UserDetails extends User {
     birthdate: Date;
     biography?: string;  
     constructor(id :number, username: string, birthdate:Date, biography? :string )  {
       super(id,username);
      this.birthdate = ...;
     }
    }
    

    when to use classes:

    • You instantiate your class and change the instances state over time.
    • Instances of your class will need methods to query or mutate its state
    • When you want to associate behaviors with data more closely;
    • You enforce constraints on the creation of your instaces.
    • If you only write a bunch of properties assignments in your class, you might consider using a type instead.

    2- Types:

    With the latest versions of typescript, interfaces and types becoming more similar. types do not express logic or state inside your application. It is best to use types when you want to describe some form of information. They can describe varying shapes of data, ranging from simple constructs like strings, arrays, and objects. Like interfaces, types are only virtual structures that don't transpile to any javascript, they just help the compiler making our life easier.

    type User = {
     id: number;
     username: string;
    }
    // inheritance
    type UserDetails = User & {
      birthDate :Date;
      biography?:string;
    }
    

    when to use types:

    • pass it around as concise function parameters
    • describe a class constructor parameters
    • document small or medium objects coming in or out from an API.
    • they don't carry state nor behavior

    Checking if a collection is empty in Java: which is the best method?

    If you have the Apache common utilities in your project rather use the first one. Because its shorter and does exactly the same as the latter one. There won't be any difference between both methods but how it looks inside the source code.

    Also a empty check using

    listName.size() != 0
    

    Is discouraged because all collection implementations have the

    listName.isEmpty()
    

    function that does exactly the same.

    So all in all, if you have the Apache common utils in your classpath anyway, use

    if (CollectionUtils.isNotEmpty(listName)) 
    

    in any other case use

    if(listName != null && listName.isEmpty())
    

    You will not notice any performance difference. Both lines do exactly the same.

    JavaScript displaying a float to 2 decimal places

    I have made this function. It works fine but returns string.

    function show_float_val(val,upto = 2){
      var val = parseFloat(val);
      return val.toFixed(upto);
    }
    

    Fill Combobox from database

    string query = "SELECT column_name FROM table_name";      //query the database
    SqlCommand queryStatus = new SqlCommand(query, myConnection);
    sqlDataReader reader = queryStatus.ExecuteReader();                               
                
    while (reader.Read())   //loop reader and fill the combobox
    {
    ComboBox1.Items.Add(reader["column_name"].ToString());
    }
    

    What is the difference between a cer, pvk, and pfx file?

    Here are my personal, super-condensed notes, as far as this subject pertains to me currently, for anyone who's interested:

    • Both PKCS12 and PEM can store entire cert chains: public keys, private keys, and root (CA) certs.
    • .pfx == .p12 == "PKCS12"
      • fully encrypted
    • .pem == .cer == .cert == "PEM" (or maybe not... could be binary... see comments...)
      • base-64 (string) encoded X509 cert (binary) with a header and footer
        • base-64 is basically just a string of "A-Za-z0-9+/" used to represent 0-63, 6 bits of binary at a time, in sequence, sometimes with 1 or 2 "=" characters at the very end when there are leftovers ("=" being "filler/junk/ignore/throw away" characters)
        • the header and footer is something like "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" or "-----BEGIN ENCRYPTED PRIVATE KEY-----" and "-----END ENCRYPTED PRIVATE KEY-----"
      • Windows recognizes .cer and .cert as cert files
    • .jks == "Java Key Store"
      • just a Java-specific file format which the API uses
        • .p12 and .pfx files can also be used with the JKS API
    • "Trust Stores" contain public, trusted, root (CA) certs, whereas "Identity/Key Stores" contain private, identity certs; file-wise, however, they are the same.

    Waiting until two async blocks are executed before starting another block

    The first answer is essentially correct, but if you want the very simplest way to accomplish the desired result, here's a stand-alone code example demonstrating how to do it with a semaphore (which is also how dispatch groups work behind the scenes, JFYI):

    #include <dispatch/dispatch.h>
    #include <stdio.h>
    
    main()
    {
            dispatch_queue_t myQ = dispatch_queue_create("my.conQ", DISPATCH_QUEUE_CONCURRENT);
            dispatch_semaphore_t mySem = dispatch_semaphore_create(0);
    
            dispatch_async(myQ, ^{ printf("Hi I'm block one!\n"); sleep(2); dispatch_semaphore_signal(mySem);});
            dispatch_async(myQ, ^{ printf("Hi I'm block two!\n"); sleep(4); dispatch_semaphore_signal(mySem);});
            dispatch_async(myQ, ^{ dispatch_semaphore_wait(mySem, DISPATCH_TIME_FOREVER); printf("Hi, I'm the final block!\n"); });
            dispatch_main();
    }
    

    How does Tomcat find the HOME PAGE of my Web App?

    I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

      <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping> 
    

    Maven compile with multiple src directories

    While the answer from evokk is basically correct, it is missing test classes. You must add test classes with goal add-test-source:

    <execution>
        <phase>generate-sources</phase>
        <goals>
            <goal>add-test-source</goal>
        </goals>
        <configuration>
           <sources>
                <source>target/generated/some-test-classes</source>
            </sources>
        </configuration>
    </execution>
    

    "You may need an appropriate loader to handle this file type" with Webpack and Babel

    Due to updates and changes overtime, version compatibility start causing issues with configuration.

    Your webpack.config.js should be like this you can also configure how ever you dim fit.

    var path = require('path');
    var webpack = require("webpack");
    
    module.exports = {
      entry: './src/js/app.js',
      devtool: 'source-map',
        mode: 'development',
      module: {
        rules: [{
          test: /\.js$/,
          exclude: /node_modules/,
          use: ["babel-loader"]
        },{
          test: /\.css$/,
          use: ['style-loader', 'css-loader']
        }]
      },
      output: {
        path: path.resolve(__dirname, './src/vendor'),
        filename: 'bundle.min.js'
      }
    };
    

    Another Thing to notice it's the change of args, you should read babel documentation https://babeljs.io/docs/en/presets

    .babelrc
    
    {
        "presets": ["@babel/preset-env", "@babel/preset-react"]
    }
    
    

    NB: you have to make sure you have the above @babel/preset-env & @babel/preset-react installed in your package.json dependencies

    How to check if mysql database exists

    CREATE SCHEMA IF NOT EXISTS `demodb` DEFAULT CHARACTER SET utf8 ;
    

    Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

    I experienced this issue when I tried to update a Hot Towel Project from the project template and when I created an empty project and installed HotTowel via nuget in VS 2012 as of 10/23/2013.

    To fix, I updated via Nuget the Web Api Web Host and Web API packages to 5.0, the current version in NuGet at the moment (10/23/2013).

    I then added the binding directs:

    <dependentAssembly>
      <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
    </dependentAssembly>
    

    In Django, how do I check if a user is in a certain group?

    If a user belongs to a certain group or not, can be checked in django templates using:

    {% if group in request.user.groups.all %} "some action" {% endif %}

    Maven compile: package does not exist

    the issue happened with me, I resolved by removing the scope tag only and built successfully.

    Getting scroll bar width using JavaScript

    I think this will be simple and fast -

    var scrollWidth= window.innerWidth-$(document).width()
    

    Getting Current time to display in Label. VB.net

    Use Date.Now instead of DateTime.Now

    Handling a timeout error in python sockets

    I had enough success just catchig socket.timeout and socket.error; although socket.error can be raised for lots of reasons. Be careful.

    import socket
    import logging
    
    hostname='google.com'
    port=443
    
    try:
        sock = socket.create_connection((hostname, port), timeout=3)
    
    except socket.timeout as err:
        logging.error(err)
    
    except socket.error as err:
        logging.error(err)
    

    How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

    Here's how you can do it with Markdown:

    ![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)
    

    Get the difference between dates in terms of weeks, months, quarters, and years

    All the existing answers are imperfect (IMO) and either make assumptions about the desired output or don't provide flexibility for the desired output.

    Based on the examples from the OP, and the OP's stated expected answers, I think these are the answers you are looking for (plus some additional examples that make it easy to extrapolate).

    (This only requires base R and doesn't require zoo or lubridate)

    Convert to Datetime Objects

    date_strings = c("14.01.2013", "26.03.2014")
    datetimes = strptime(date_strings, format = "%d.%m.%Y") # convert to datetime objects
    

    Difference in Days

    You can use the diff in days to get some of our later answers

    diff_in_days = difftime(datetimes[2], datetimes[1], units = "days") # days
    diff_in_days
    #Time difference of 435.9583 days
    

    Difference in Weeks

    Difference in weeks is a special case of units = "weeks" in difftime()

    diff_in_weeks = difftime(datetimes[2], datetimes[1], units = "weeks") # weeks
    diff_in_weeks
    #Time difference of 62.27976 weeks
    

    Note that this is the same as dividing our diff_in_days by 7 (7 days in a week)

    as.double(diff_in_days)/7
    #[1] 62.27976
    

    Difference in Years

    With similar logic, we can derive years from diff_in_days

    diff_in_years = as.double(diff_in_days)/365 # absolute years
    diff_in_years
    #[1] 1.194406
    

    You seem to be expecting the diff in years to be "1", so I assume you just want to count absolute calendar years or something, which you can easily do by using floor()

    # get desired output, given your definition of 'years'
    floor(diff_in_years)
    #[1] 1
    

    Difference in Quarters

    # get desired output for quarters, given your definition of 'quarters'
    floor(diff_in_years * 4)
    #[1] 4
    

    Difference in Months

    Can calculate this as a conversion from diff_years

    # months, defined as absolute calendar months (this might be what you want, given your question details)
    months_diff = diff_in_years*12
    floor(month_diff)
    #[1] 14
    

    I know this question is old, but given that I still had to solve this problem just now, I thought I would add my answers. Hope it helps.

    Facebook Callback appends '#_=_' to Return URL

    Adding this to my redirect page fixed the problem for me ...

    if (window.location.href.indexOf('#_=_') > 0) {
        window.location = window.location.href.replace(/#.*/, '');
    }
    

    Remove all line breaks from a long string of text

    updated based on Xbello comment:

    string = my_string.rstrip('\r\n')
    

    read more here

    Better way to represent array in java properties file

    I highly recommend using Apache Commons (http://commons.apache.org/configuration/). It has the ability to use an XML file as a configuration file. Using an XML structure makes it easy to represent arrays as lists of values rather than specially numbered properties.

    What is an 'undeclared identifier' error and how do I fix it?

    A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. In C++ all names have to be declared before they are used. If you try to use the name of a such that hasn't been declared you will get an "undeclared identifier" compile-error.

    According to the documentation, the declaration of printf() is in cstdio i.e. you have to include it, before using the function.

    CSS - center two images in css side by side

    Try changing

    #fblogo {
        display: block;
        margin-left: auto;
        margin-right: auto;
        height: 30px; 
    }
    

    to

    .fblogo {
        display: inline-block;
        margin-left: auto;
        margin-right: auto;
        height: 30px; 
    }
    
    #images{
        text-align:center;
    }
    

    HTML

    <div id="images">
        <a href="mailto:[email protected]">
        <img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/07/email-icon-e1343123697991.jpg"/></a>
        <a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
        <img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>
    </div>?
    

    DEMO.

    Current date and time as string

    you can use asctime() function of time.h to get a string simply .

    time_t _tm =time(NULL );
    
    struct tm * curtime = localtime ( &_tm );
    cout<<"The current date/time is:"<<asctime(curtime);
    

    Sample output:

    The current date/time is:Fri Oct 16 13:37:30 2015
    

    Redefining the Index in a Pandas DataFrame object

    If you don't want 'a' in the index

    In :

    col = ['a','b','c']
    
    data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
    
    data
    

    Out:

        a   b   c
    0   1   2   3
    1  10  11  12
    2  20  21  22
    

    In :

    data2 = data.set_index('a')
    

    Out:

         b   c
    a
    1    2   3
    10  11  12
    20  21  22
    

    In :

    data2.index.name = None
    

    Out:

         b   c
     1   2   3
    10  11  12
    20  21  22
    

    Change the location of an object programmatically

    You need to pass the whole point to location

    var point = new Point(50, 100);
    this.balancePanel.Location = point;
    

    What does .shape[] do in "for i in range(Y.shape[0])"?

    shape() consists of array having two arguments rows and columns.

    if you search shape[0] then it will gave you the number of rows. shape[1] will gave you number of columns.

    Android ListView with different layouts for each row

    Take a look in the code below.

    First, we create custom layouts. In this case, four types.

    even.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ff500000"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/text"
            android:textColor="@android:color/white"
            android:layout_width="match_parent"
            android:layout_gravity="center"
            android:textSize="24sp"
            android:layout_height="wrap_content" />
    
     </LinearLayout>
    

    odd.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ff001f50"
        android:gravity="right"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/text"
            android:textColor="@android:color/white"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:textSize="28sp"
            android:layout_height="wrap_content"  />
    
     </LinearLayout>
    

    white.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ffffffff"
        android:gravity="right"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/text"
            android:textColor="@android:color/black"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:textSize="28sp"
            android:layout_height="wrap_content"   />
    
     </LinearLayout>
    

    black.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ff000000"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/text"
            android:textColor="@android:color/white"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:textSize="33sp"
            android:layout_height="wrap_content"   />
    
     </LinearLayout>
    

    Then, we create the listview item. In our case, with a string and a type.

    public class ListViewItem {
            private String text;
            private int type;
    
            public ListViewItem(String text, int type) {
                this.text = text;
                this.type = type;
            }
    
            public String getText() {
                return text;
            }
    
            public void setText(String text) {
                this.text = text;
            }
    
            public int getType() {
                return type;
            }
    
            public void setType(int type) {
                this.type = type;
            }
    
        }
    

    After that, we create a view holder. It's strongly recommended because Android OS keeps the layout reference to reuse your item when it disappears and appears back on the screen. If you don't use this approach, every single time that your item appears on the screen Android OS will create a new one and causing your app to leak memory.

    public class ViewHolder {
            TextView text;
    
            public ViewHolder(TextView text) {
                this.text = text;
            }
    
            public TextView getText() {
                return text;
            }
    
            public void setText(TextView text) {
                this.text = text;
            }
    
        }
    

    Finally, we create our custom adapter overriding getViewTypeCount() and getItemViewType(int position).

    public class CustomAdapter extends ArrayAdapter {
    
            public static final int TYPE_ODD = 0;
            public static final int TYPE_EVEN = 1;
            public static final int TYPE_WHITE = 2;
            public static final int TYPE_BLACK = 3;
    
            private ListViewItem[] objects;
    
            @Override
            public int getViewTypeCount() {
                return 4;
            }
    
            @Override
            public int getItemViewType(int position) {
                return objects[position].getType();
            }
    
            public CustomAdapter(Context context, int resource, ListViewItem[] objects) {
                super(context, resource, objects);
                this.objects = objects;
            }
    
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
    
                ViewHolder viewHolder = null;
                ListViewItem listViewItem = objects[position];
                int listViewItemType = getItemViewType(position);
    
    
                if (convertView == null) {
    
                    if (listViewItemType == TYPE_EVEN) {
                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_even, null);
                    } else if (listViewItemType == TYPE_ODD) {
                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_odd, null);
                    } else if (listViewItemType == TYPE_WHITE) {
                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_white, null);
                    } else {
                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_black, null);
                    }
    
                    TextView textView = (TextView) convertView.findViewById(R.id.text);
                    viewHolder = new ViewHolder(textView);
    
                    convertView.setTag(viewHolder);
    
                } else {
                    viewHolder = (ViewHolder) convertView.getTag();
                }
    
                viewHolder.getText().setText(listViewItem.getText());
    
                return convertView;
            }
    
        }
    

    And our activity is something like this:

    private ListView listView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main); // here, you can create a single layout with a listview
    
            listView = (ListView) findViewById(R.id.listview);
    
            final ListViewItem[] items = new ListViewItem[40];
    
            for (int i = 0; i < items.length; i++) {
                if (i == 4) {
                    items[i] = new ListViewItem("White " + i, CustomAdapter.TYPE_WHITE);
                } else if (i == 9) {
                    items[i] = new ListViewItem("Black " + i, CustomAdapter.TYPE_BLACK);
                } else if (i % 2 == 0) {
                    items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_EVEN);
                } else {
                    items[i] = new ListViewItem("ODD " + i, CustomAdapter.TYPE_ODD);
                }
            }
    
            CustomAdapter customAdapter = new CustomAdapter(this, R.id.text, items);
            listView.setAdapter(customAdapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                    Toast.makeText(getBaseContext(), items[i].getText(), Toast.LENGTH_SHORT).show();
                }
            });
    
        }
    }
    

    now create a listview inside mainactivity.xml like this

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.example.shivnandan.gygy.MainActivity">
    
        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">
    
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />
    
        </android.support.design.widget.AppBarLayout>
    
        <include layout="@layout/content_main" />
    
        <ListView
            android:layout_width="match_parent"
    
            android:layout_height="match_parent"
    
            android:id="@+id/listView"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
    
    
            android:layout_marginTop="100dp" />
    
    </android.support.design.widget.CoordinatorLayout>
    

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

    Or You can use

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

    This will take care of numbering the lines in the file

       grep -n . file1 
    

    This will print the last-LineNumberToStartWith

       tail -LineNumberToStartWith
    

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

    grep regEX
    

    What is the difference between <section> and <div>?

    The section tag provides a more semantic syntax for html. div is a generic tag for a section. When you use section tag for appropriate content, it can be used for search engine optimization also. section tag also makes it easy for html parsing. for more info, refer. http://blog.whatwg.org/is-not-just-a-semantic

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

    #!/usr/local/bin/bash -x
    
    find * /home/www -type f | while read files
    do
    
    sedtest=$(sed -n '/^/,/$/p' "${files}" | sed -n '/subdomainA/p')
    
        if [ "${sedtest}" ]
        then
        sed s'/subdomainA/subdomainB/'g "${files}" > "${files}".tmp
        mv "${files}".tmp "${files}"
        fi
    
    done
    

    Run R script from command line

    If you want the output to print to the terminal it is best to use Rscript

    Rscript a.R
    

    Note that when using R CMD BATCH a.R that instead of redirecting output to standard out and displaying on the terminal a new file called a.Rout will be created.

    R CMD BATCH a.R
    # Check the output
    cat a.Rout
    

    One other thing to note about using Rscript is that it doesn't load the methods package by default which can cause confusion. So if you're relying on anything that methods provides you'll want to load it explicitly in your script.

    If you really want to use the ./a.R way of calling the script you could add an appropriate #! to the top of the script

    #!/usr/bin/env Rscript
    sayHello <- function(){
       print('hello')
    }
    
    sayHello()
    

    I will also note that if you're running on a *unix system there is the useful littler package which provides easy command line piping to R. It may be necessary to use littler to run shiny apps via a script? Further details can be found in this question.

    Order a List (C#) by many fields?

    Make your object something like

    public class MyObject : IComparable
    {
        public string a;
        public string b;
    
        virtual public int CompareTo(object obj)
        {
            if (obj is MyObject)
            {
                var compareObj = (MyObject)obj;
                if (this.a.CompareTo(compareObj.a) == 0)
                {
                    // compare second value
                    return this.b.CompareTo(compareObj.b);
                }
                return this.a.CompareTo(compareObj.b);
            }
            else
            {
                throw new ArgumentException("Object is not a MyObject ");
            }
        }
    }
    

    also note that the returns for CompareTo :

    http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx

    Then, if you have a List of MyObject, call .Sort() ie

    var objList = new List<MyObject>();
    objList.Sort();
    

    How to adjust gutter in Bootstrap 3 grid system?

    You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

    .col {
      padding-right:7px;
      padding-left:7px;
    }
    

    Demo: http://bootply.com/93473

    EDIT If you only want the spacing between columns you can select all cols except first and last like this..

    .col:not(:first-child,:last-child) {
      padding-right:7px;
      padding-left:7px;
    }
    

    Updated Bootply

    For Bootstrap 4 see: Remove gutter space for a specific div only

    bundle install fails with SSL certificate verification error

    Simple copy paste instruction given here about .pem file

    https://gist.github.com/luislavena/f064211759ee0f806c88

    For certificate verification failed

    If you've read the previous sections, you will know what this means (and shame > on you if you have not).

    We need to download AddTrustExternalCARoot-2048.pem. Open a Command Prompt and type in:

    C:>gem which rubygems C:/Ruby21/lib/ruby/2.1.0/rubygems.rb Now, let's locate that directory. From within the same window, enter the path part up to the file extension, but using backslashes instead:

    C:>start C:\Ruby21\lib\ruby\2.1.0\rubygems This will open a Explorer window inside the directory we indicated.

    Step 3: Copy new trust certificate

    Now, locate ssl_certs directory and copy the .pem file we obtained from previous step inside.

    It will be listed with other files like GeoTrustGlobalCA.pem.

    What's the effect of adding 'return false' to a click event listener?

    Retuning false from a JavaScript event usually cancels the "default" behavior - in the case of links, it tells the browser to not follow the link.

    Outline radius?

    Old question now, but this might be relevant for somebody with a similar issue. I had an input field with rounded border and wanted to change colour of focus outline. I couldn't tame the horrid square outline to the input control.

    So instead, I used box-shadow. I actually preferred the smooth look of the shadow, but the shadow can be hardened to simulate a rounded outline:

    _x000D_
    _x000D_
     /* Smooth outline with box-shadow: */_x000D_
        .text1:focus {_x000D_
            box-shadow: 0 0 3pt 2pt red;_x000D_
        }_x000D_
    _x000D_
        /* Hard "outline" with box-shadow: */_x000D_
        .text2:focus {_x000D_
            box-shadow: 0 0 0 2pt red;_x000D_
        }
    _x000D_
    <input type=text class="text1"> _x000D_
    <br>_x000D_
    <br>_x000D_
    <br>_x000D_
    <br>_x000D_
    <input type=text class="text2">
    _x000D_
    _x000D_
    _x000D_

    Regular Expression to get all characters before "-"

    So I see many possibilities to achieve this.

    string text = "Foobar-test";
    
    1. Regex Match everything till the first "-"

      Match result = Regex.Match(text, @"^.*?(?=-)");
      
      • ^ match from the start of the string
      • .*? match any character (.), zero or more times (*) but as less as possible (?)
      • (?=-) till the next character is a "-" (this is a positive look ahead)
    2. Regex Match anything that is not a "-" from the start of the string

      Match result2 = Regex.Match(text, @"^[^-]*");
      
      • [^-]* matches any character that is not a "-" zero or more times
    3. Regex Match anything that is not a "-" from the start of the string till a "-"

      Match result21 = Regex.Match(text, @"^([^-]*)-");
      

      Will only match if there is a dash in the string, but the result is then found in capture group 1.

    4. Split on "-"

      string[] result3 = text.Split('-');
      

      Result is an Array the part before the first "-" is the first item in the Array

    5. Substring till the first "-"

      string result4 = text.Substring(0, text.IndexOf("-"));
      

      Get the substring from text from the start till the first occurrence of "-" (text.IndexOf("-"))

    You get then all the results (all the same) with this

    Console.WriteLine(result);
    Console.WriteLine(result2);
    Console.WriteLine(result21.Groups[1]);
    Console.WriteLine(result3[0]);
    Console.WriteLine(result4);
    

    I would prefer the first method.

    You need to think also about the behavior, when there is no dash in the string. The fourth method will throw an exception in that case, because text.IndexOf("-") will be -1. Method 1 and 2.1 will return nothing and method 2 and 3 will return the complete string.

    How to get the xml node value in string

    You should use .Load and not .LoadXML

    MSDN Link

    "The LoadXml method is for loading an XML string directly. You want to use the Load method instead."

    ref : Link

    How to save and extract session data in codeigniter

    In codeigniter we are able to store session values in a database. In the config.php file make the sess_use_database variable true

    $config['sess_use_database'] = TRUE;
    $config['sess_table_name'] = 'ci_sessions';
    

    and create a ci_session table in the database

    CREATE TABLE IF NOT EXISTS  `ci_sessions` (
        session_id varchar(40) DEFAULT '0' NOT NULL,
        ip_address varchar(45) DEFAULT '0' NOT NULL,
        user_agent varchar(120) NOT NULL,
        last_activity int(10) unsigned DEFAULT 0 NOT NULL,
        user_data text NOT NULL,
        PRIMARY KEY (session_id),
        KEY `last_activity_idx` (`last_activity`)
    );
    

    For more details and reference, click here

    How to find the Center Coordinate of Rectangle?

    We can calculate using mid point of line formula,

    centre (x,y) =  new Point((boundRect.tl().x+boundRect.br().x)/2,(boundRect.tl().y+boundRect.br().y)/2)
    

    how to get right offset of an element? - jQuery

    Maybe I'm misunderstanding your question, but the offset is supposed to give you two variables: a horizontal and a vertical. This defines the position of the element. So what you're looking for is:

    $("#whatever").offset().left
    

    and

    $("#whatever").offset().top
    

    If you need to know where the right boundary of your element is, then you should use:

    $("#whatever").offset().left + $("#whatever").outerWidth()
    

    Sort array of objects by single key with date value

    For completeness here is a possible short generic implementation of sortBy:

    function sortBy(list, keyFunc) {
      return list.sort((a,b) => keyFunc(a) - keyFunc(b));
    }
    
    sortBy([{"key": 2}, {"key": 1}], o => o["key"])
    

    Note that this uses the arrays sort method that sorts in place. for a copy you can use arr.concat() or arr.slice(0) or similar method to create a copy.

    How to set a transparent background of JPanel?

    In my particular case it was easier to do this:

     panel.setOpaque(true);
     panel.setBackground(new Color(0,0,0,0,)): // any color with alpha 0 (in this case the color is black
    

    How to append elements into a dictionary in Swift?

    Up till now the best way I have found to append data to a dictionary by using one of the higher order functions of Swift i.e. "reduce". Follow below code snippet:

    newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }
    

    @Dharmesh In your case, it will be,

    newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }
    

    Please let me know if you find any issues in using above syntax.

    Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

    I encountered this error too, it occurs because %HTTPPORT% isn’t part of the system variables yet.

    The solution to this is NOT by manually typing in the url to your browser, which works but you have to keep doing it every single time.

    Simply goto “this pc” or “my computer” right click on it and select properties, then select “advanced system settings” When the new window comes up select “Environment Variables...”

    Now under system variables click new to create a new system variable. Type HTTPPORT into the variable name text box, Then type 8080 into the variable value text box. Click OK, close the windows and logout!

    Thats an important step, make sure you log out. When you log back in, click the get started icon again and it will open without errors.

    ??

    How to call gesture tap on UIView programmatically in swift

    Inside ViewDidLoad

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
        self.imgMainAdView.isUserInteractionEnabled = true
        self.imgMainAdView.addGestureRecognizer(tapGestureRecognizer)
    

    //MARK: - Image Tap Method -
    @objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
    {
        print("Tapped")
        if let url = URL(string: self.strMAinAdvLink)
        {
            UIApplication.shared.open(url, options: [:])
        }
    }
    

    Calling Purpose

    @IBAction func btnCall1Action(_ sender: Any)
    {
        let text = self.strPhoneNumber1!
        let test = String(text.filter { !" -()".contains($0) })
        UIApplication.shared.openURL(NSURL(string: "tel://\(test)")! as URL)
    }
    

    Mail Purpose

    MFMailComposeViewControllerDelegate
    
     @IBAction func btnMailAction(_ sender: Any)
    {
        let strEmail = SAFESTRING(str:  (self.dictEventDetails?.value(forKeyPath: "Email.value_text.email") as! String))
    
        if !MFMailComposeViewController.canSendMail()
        {
            AppDelegate.sharedInstance().showAlertAction(strTitle: "OK", strMessage: "Mail services are not available") { (success) in
            }
            return
        }
        let composeVC = MFMailComposeViewController()
        composeVC.mailComposeDelegate = self
        composeVC.setToRecipients([strEmail])
        composeVC.setSubject("")
        composeVC.setMessageBody("", isHTML: false)
        self.present(composeVC, animated: true, completion: nil)
    }
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?)
    {
        controller.dismiss(animated: true, completion: nil)
    }
    

    CodeIgniter - return only one row?

    You've just answered your own question :) You can do something like this:

    $query = $this->db->get();
    $ret = $query->row();
    return $ret->campaign_id;
    

    You can read more about it here: http://www.codeigniter.com/user_guide/database/results.html

    Difference between maven scope compile and provided for JAR packaging

    Compile means that you need the JAR for compiling and running the app. For a web application, as an example, the JAR will be placed in the WEB-INF/lib directory.

    Provided means that you need the JAR for compiling, but at run time there is already a JAR provided by the environment so you don't need it packaged with your app. For a web app, this means that the JAR file will not be placed into the WEB-INF/lib directory.

    For a web app, if the app server already provides the JAR (or its functionality), then use "provided" otherwise use "compile".

    Here is the reference.

    Can I change the checkbox size using CSS?

    I just came out with this:

    _x000D_
    _x000D_
    input[type="checkbox"] {display:none;}_x000D_
    input[type="checkbox"] + label:before {content:"?";}_x000D_
    input:checked + label:before {content:"?";}_x000D_
    label:hover {color:blue;}
    _x000D_
    <input id="check" type="checkbox" /><label for="check">Checkbox</label>
    _x000D_
    _x000D_
    _x000D_

    Of course, thanks to this, you can change the value of content to your needs and use an image if you wish or use another font...

    The main interest here is that:

    1. The checkbox size stays proportional to the text size

    2. You can control the aspect, the color, the size of the checkbox

    3. No extra HTML needed !

    4. Only 3 lines of CSS needed (the last one is just to give you ideas)

    Edit: As pointed out in the comment, the checkbox won't be accessible by key navigation. You should probably add tabindex=0 as a property for your label to make it focusable.

    How can I exclude directories from grep -R?

    This one works for me:

    grep <stuff> -R --exclude-dir=<your_dir>
    

    Task vs Thread differences

    Source

    Thread

    Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.

    The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.

    There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.

    ThreadPool

    ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.

    Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.

    Task

    Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.

    Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task's result, allowing you to run more code that uses it.

    You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.

    Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.

    All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.

    Conclusion

    The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.

    The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.

    Bash or KornShell (ksh)?

    I'm a korn-shell veteran, so know that I speak from that perspective.

    However, I have been comfortable with Bourne shell, ksh88, and ksh93, and for the most I know which features are supported in which. (I should skip ksh88 here, as it's not widely distributed anymore.)

    For interactive use, take whatever fits your need. Experiment. I like being able to use the same shell for interactive use and for programming.

    I went from ksh88 on SVR2 to tcsh, to ksh88sun (which added significant internationalisation support) and ksh93. I tried bash, and hated it because it flattened my history. Then I discovered shopt -s lithist and all was well. (The lithist option assures that newlines are preserved in your command history.)

    For shell programming, I'd seriously recommend ksh93 if you want a consistent programming language, good POSIX conformance, and good performance, as many common unix commands can be available as builtin functions.

    If you want portability use at least both. And make sure you have a good test suite.

    There are many subtle differences between shells. Consider for example reading from a pipe:

    b=42 && echo one two three four |
        read a b junk && echo $b
    

    This will produce different results in different shells. The korn-shell runs pipelines from back to front; the last element in the pipeline runs in the current process. Bash did not support this useful behaviour until v4.x, and even then, it's not the default.

    Another example illustrating consistency: The echo command itself, which was made obsolete by the split between BSD and SYSV unix, and each introduced their own convention for not printing newlines (and other behaviour). The result of this can still be seen in many 'configure' scripts.

    Ksh took a radical approach to that - and introduced the print command, which actually supports both methods (the -n option from BSD, and the trailing \c special character from SYSV)

    However, for serious systems programming I'd recommend something other than a shell, like python, perl. Or take it a step further, and use a platform like puppet - which allows you to watch and correct the state of whole clusters of systems, with good auditing.

    Shell programming is like swimming in uncharted waters, or worse.

    Programming in any language requires familiarity with its syntax, its interfaces and behaviour. Shell programming isn't any different.

    How to view DB2 Table structure

    Generally it's easiest to use DESCRIBE.

    DESCRIBE TABLE MYSCHEMA.TABLE
    

    or

    DESCRIBE INDEXES FOR MYSCHEMA.TABLE SHOW DETAIL
    

    etc.

    See the documentation: DESCRIBE command

    Creating a simple configuration file and parser in C++

    So I merged some of the above solutions into my own, which for me made more sense, became more intuitive and a bit less error prone. I use a public stp::map to keep track of the possible config ids, and a struct to keep track of the possible values. Her it goes:

    struct{
        std::string PlaybackAssisted = "assisted";
        std::string Playback = "playback";
        std::string Recording = "record";
        std::string Normal = "normal";
    } mode_def;
    
    std::map<std::string, std::string> settings = {
        {"mode", mode_def.Normal},
        {"output_log_path", "/home/root/output_data.log"},
        {"input_log_path", "/home/root/input_data.log"},
    };
    
    void read_config(const std::string & settings_path){
    std::ifstream settings_file(settings_path);
    std::string line;
    
    if (settings_file.fail()){
        LOG_WARN("Config file does not exist. Default options set to:");
        for (auto it = settings.begin(); it != settings.end(); it++){
            LOG_INFO("%s=%s", it->first.c_str(), it->second.c_str());
        }
    }
    
    while (std::getline(settings_file, line)){
        std::istringstream iss(line);
        std::string id, eq, val;
    
        if (std::getline(iss, id, '=')){
            if (std::getline(iss, val)){
                if (settings.find(id) != settings.end()){
                    if (val.empty()){
                        LOG_INFO("Config \"%s\" is empty. Keeping default \"%s\"", id.c_str(), settings[id].c_str());
                    }
                    else{
                        settings[id] = val;
                        LOG_INFO("Config \"%s\" read as \"%s\"", id.c_str(), settings[id].c_str());
                    }
                }
                else{ //Not present in map
                    LOG_ERROR("Setting \"%s\" not defined, ignoring it", id.c_str());
                    continue;
                }
            }
            else{
                // Comment line, skiping it
                continue;
            }
        }
        else{
            //Empty line, skipping it
            continue;            
        }
    }
    

    }

    2D cross-platform game engine for Android and iOS?

    I've worked with Marmalade and I found it satisfying. Although it's not free and the developer community is also not large enough, but still you can handle most of the task using it's tutorials. (I'll write my tutorials once I got some times too).
    IwGame is a good engine, developed by one of the Marmalade user. It's good for a basic game, but if you are looking for some serious advanced gaming stuff, you can also use Cocos2D-x with Marmalade. I've never used Cocos2D-x, but there's an Extension on Marmalade's Github.
    Another good thing about Marmalade is it's EDK (Extension Development Kit), which lets you make an extension for whatever functionality you need which is available in native code, but not in Marmalade. I've used it to develop my own Customized Admob extension and a Facebook extension too.

    Edit:
    Marmalade now has it's own RAD(Rapid Application Development) tool just for 2D development, named as Marmalade Quick. Although the coding will be in Lua not in C++, but since it's built on top of C++ Marmalade, you can easily include a C++ library, and all other EDK extensions. Also the Cocos-2Dx and Box2D extensions are preincluded in the Quick. They recently launched it's Release version (It was in beta for 3-4 months). I think we you're really looking for only 2D development, you should give it a try.

    Update:
    Unity3D recently launched support for 2D games, which seems better than any other 2D game engine, due to it's GUI and Editor. Physics, sprite etc support is inbuilt. You can have a look on it.

    Update 2
    Marmalade is going to discontinue their SDK in favor of their in-house game production soon. So it won't be a wise decision to rely on that.

    Remove all padding and margin table HTML and CSS

    I find the most perfectly working answer is this

    .noBorder {
        border: 0px;
        padding:0; 
        margin:0;
        border-collapse: collapse;
    }
    

    Get bitcoin historical data

    Coinbase has a REST API that gives you access to historical prices from their website. The data seems to show the Coinbase spot price (in USD) about every ten minutes.

    Results are returned in CSV format. You must query the page number you want through the API. There are 1000 results (or price points) per page. That's about 7 days' worth of data per page.

    How does bitshifting work in Java?

    You can't write binary literals like 00101011 in Java so you can write it in hexadecimal instead:

    byte x = 0x2b;
    

    To calculate the result of x >> 2 you can then just write exactly that and print the result.

    System.out.println(x >> 2);
    

    SCP Permission denied (publickey). on EC2 only when using -r flag on directories

    transferring file from local to remote host

    scp -i (path of your key) (path for your file to be transferred) (username@ip):(path where file to be copied)

    e.g scp -i aws.pem /home/user1/Desktop/testFile   ec2-user@someipAddress:/home/ec2-user/
    

    P.S. - ec2-user@someipAddress of this ip address should have access to the destination folder in my case /home/ec2-user/

    How to split one text file into multiple *.txt files?

    John's answer won't produce .txt files as the OP wants. Use:

    split -b=1M -d  file.txt file --additional-suffix=.txt
    

    Conditional operator in Python?

    simple is the best and works in every version.

    if a>10: 
        value="b"
    else: 
        value="c"
    

    How to run ~/.bash_profile in mac terminal

    As @kojiro said, you don't want to "run" this file. Source it as he says. It should get "sourced" at startup. Sourcing just means running every line in the file, including the one you want to get run. If you want to make sure a folder is in a certain path environment variable (as it seems you want from one of your comments on another solution), execute

    $ echo $PATH
    

    At the command line. If you want to check that your ~/.bash_profile is being sourced, either at startup as it should be, or when you source it manually, enter the following line into your ~/.bash_profile file:

    $ echo "Hello I'm running stuff in the ~/.bash_profile!"
    

    Compiler warning - suggest parentheses around assignment used as truth value

    It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have == in there. You can make the warning go away by adding another set of parentheses:

    while ((list = list->next))
    

    RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

    To install GLIBC_2.14 or GLIBC_2.15, download package from /gnu/libc/ index at

    https://ftp.gnu.org/gnu/libc/

    Then follow instructions listed by Timo:

    For example glibc-2.14.tar.gz in your case.

    1. tar xvfz glibc-2.14.tar.gz

    2. cd glibc-2.14

    3. mkdir build

    4. cd build

    5. ../configure --prefix=/opt/glibc-2.14

    6. make

    7. sudo make install

    8. export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH

    Debugging PHP Mail() and/or PHPMailer

    It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

    I've always used phpMailer's SMTP feature:

    $mail->IsSMTP();
    $mail->Host = "localhost";
    

    And if you need debug info:

    $mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                           // 1 = errors and messages
                           // 2 = messages only
    

    No connection could be made because the target machine actively refused it?

    Go to your WCF project - properties -> Web -> debuggers -> unmark the checkbox

    Enable Edit and Continue

    Convert bytes to bits in python

    Use ord when reading reading bytes:

    byte_binary = bin(ord(f.read(1))) # Add [2:] to remove the "0b" prefix
    

    Or

    Using str.format():

    '{:08b}'.format(ord(f.read(1)))
    

    How to install Java SDK on CentOS?

    The following command will return a list of all packages directly related to Java. They will be in the format of java-<version>.

    $ yum search java | grep 'java-'
    

    If there are no available packages, then you may need to download a new repository to search through. I suggest taking a look at Dag Wieers' repo. After downloading it, try the above command again.

    You will see at least one version of Java packages available for download. Depending on when you read this, the lastest available version may be different.

    java-1.7.0-openjdk.x86_64
    

    The above package alone will only install JRE. To also install javac and JDK, the following command will do the trick:

    $ yum install java-1.7.0-openjdk*
    

    These packages will be installing (as well as their dependencies):

    java-1.7.0-openjdk.x86_64
    java-1.7.0-openjdk-accessibility.x86_64
    java-1.7.0-openjdk-demo.x86_64
    java-1.7.0-openjdk-devel.x86_64
    java-1.7.0-openjdk-headless.x86_64
    java-1.7.0-openjdk-javadoc.noarch
    java-1.7.0-openjdk-src.x86_64
    

    How can I find the dimensions of a matrix in Python?

    The number of rows of a list of lists would be: len(A) and the number of columns len(A[0]) given that all rows have the same number of columns, i.e. all lists in each index are of the same size.

    tkinter: how to use after method

    You need to give a function to be called after the time delay as the second argument to after:

    after(delay_ms, callback=None, *args)

    Registers an alarm callback that is called after a given time.

    So what you really want to do is this:

    tiles_letter = ['a', 'b', 'c', 'd', 'e']
    
    def add_letter():
        rand = random.choice(tiles_letter)
        tile_frame = Label(frame, text=rand)
        tile_frame.pack()
        root.after(500, add_letter)
        tiles_letter.remove(rand)  # remove that tile from list of tiles
    
    
    root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
    root.mainloop()
    

    You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

    The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

    Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

    def add_letter():
        if not tiles_letter:
            return
        rand = random.choice(tiles_letter)
        tile_frame = Label(frame, text=rand)
        tile_frame.pack()
        root.after(500, add_letter)
        tiles_letter.remove(rand)  # remove that tile from list of tiles
    

    Live-Demo: repl.it

    How can I update my ADT in Eclipse?

    You have updated the android sdk but not updated the adt to match with it.

    You can update the adt from here

    You might need to update the software source for your adt update

    Go to eclipse > help > Check for updates.

    It should list the latest update of adt. If it is not working try the same *Go to eclipse > help > Install new software * but now please do the follwing:

    It will list the updates available- which should ideally be adt 20.xx

    Eclipse will restart and hopefully everything should work fine for you.

    Custom HTTP headers : naming conventions

    The question bears re-reading. The actual question asked is not similar to vendor prefixes in CSS properties, where future-proofing and thinking about vendor support and official standards is appropriate. The actual question asked is more akin to choosing URL query parameter names. Nobody should care what they are. But name-spacing the custom ones is a perfectly valid -- and common, and correct -- thing to do.

    Rationale:
    It is about conventions among developers for custom, application-specific headers -- "data relevant to their account" -- which have nothing to do with vendors, standards bodies, or protocols to be implemented by third parties, except that the developer in question simply needs to avoid header names that may have other intended use by servers, proxies or clients. For this reason, the "X-Gzip/Gzip" and "X-Forwarded-For/Forwarded-For" examples given are moot. The question posed is about conventions in the context of a private API, akin to URL query parameter naming conventions. It's a matter of preference and name-spacing; concerns about "X-ClientDataFoo" being supported by any proxy or vendor without the "X" are clearly misplaced.

    There's nothing special or magical about the "X-" prefix, but it helps to make it clear that it is a custom header. In fact, RFC-6648 et al help bolster the case for use of an "X-" prefix, because -- as vendors of HTTP clients and servers abandon the prefix -- your app-specific, private-API, personal-data-passing-mechanism is becoming even better-insulated against name-space collisions with the small number of official reserved header names. That said, my personal preference and recommendation is to go a step further and do e.g. "X-ACME-ClientDataFoo" (if your widget company is "ACME").

    IMHO the IETF spec is insufficiently specific to answer the OP's question, because it fails to distinguish between completely different use cases: (A) vendors introducing new globally-applicable features like "Forwarded-For" on the one hand, vs. (B) app developers passing app-specific strings to/from client and server. The spec only concerns itself with the former, (A). The question here is whether there are conventions for (B). There are. They involve grouping the parameters together alphabetically, and separating them from the many standards-relevant headers of type (A). Using the "X-" or "X-ACME-" prefix is convenient and legitimate for (B), and does not conflict with (A). The more vendors stop using "X-" for (A), the more cleanly-distinct the (B) ones will become.

    Example:
    Google (who carry a bit of weight in the various standards bodies) are -- as of today, 20141102 in this slight edit to my answer -- currently using "X-Mod-Pagespeed" to indicate the version of their Apache module involved in transforming a given response. Is anyone really suggesting that Google should use "Mod-Pagespeed", without the "X-", and/or ask the IETF to bless its use?

    Summary:
    If you're using custom HTTP Headers (as a sometimes-appropriate alternative to cookies) within your app to pass data to/from your server, and these headers are, explicitly, NOT intended ever to be used outside the context of your application, name-spacing them with an "X-" or "X-FOO-" prefix is a reasonable, and common, convention.

    How to prevent tensorflow from allocating the totality of a GPU memory?

    config = tf.ConfigProto()
    config.gpu_options.allow_growth=True
    sess = tf.Session(config=config)
    

    https://github.com/tensorflow/tensorflow/issues/1578

    Using Predicate in Swift

    You can use filters available in swift to filter content from an array instead of using a predicate like in Objective-C.

    An example in Swift 4.0 is as follows:

    var stringArray = ["foundation","coredata","coregraphics"]
    stringArray = stringArray.filter { $0.contains("core") }
    

    In the above example, since each element in the array is a string you can use the contains method to filter the array.

    If the array contains custom objects, then the properties of that object can be used to filter the elements similarly.

    How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

    This function returns all user defined routines in current database.

    SELECT pg_get_functiondef(p.oid) FROM pg_proc p
    INNER JOIN pg_namespace ns ON p.pronamespace = ns.oid
    WHERE ns.nspname = 'public';
    

    WSDL vs REST Pros and Cons

    The previous answers contain a lot of information, but I think there is a philosophical difference that hasn't been pointed out. SOAP was the answer to "how to we create a modern, object-oriented, platform and protocol independent successor to RPC?". REST developed from the question, "how to we take the insights that made HTTP so successful for the web, and use them for distributed computing?"

    SOAP is a about giving you tools to make distributed programming look like ... programming. REST tries to impose a style to simplify distributed interfaces, so that distributed resources can refer to each other like distributed html pages can refer to each other. One way it does that is attempt to (mostly) restrict operations to "CRUD" on resources (create, read, update, delete).

    REST is still young -- although it is oriented towards "human readable" services, it doesn't rule out introspection services, etc. or automatic creation of proxies. However, these have not been standardized (as I write). SOAP gives you these things, but (IMHO) gives you "only" these things, whereas the style imposed by REST is already encouraging the spread of web services because of its simplicity. I would myself encourage newbie service providers to choose REST unless there are specific SOAP-provided features they need to use.

    In my opinion, then, if you are implementing a "greenfield" API, and don't know that much about possible clients, I would choose REST as the style it encourages tends to help make interfaces comprehensible, and easy to develop to. If you know a lot about client and server, and there are specific SOAP tools that will make life easy for both, then I wouldn't be religious about REST, though.

    jquery function val() is not equivalent to "$(this).value="?

    Note that :

    typeof $(this) is JQuery object.

    and

    typeof $(this)[0] is HTMLElement object

    then : if you want to apply .val() on HTMLElement , you can add this extension .

    HTMLElement.prototype.val=function(v){
       if(typeof v!=='undefined'){this.value=v;return this;}
       else{return this.value}
    }
    

    Then :

    document.getElementById('myDiv').val() ==== $('#myDiv').val()
    

    And

     document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')
    

    ????? INVERSE :

    Conversely? if you want to add value property to jQuery object , follow those steps :

    1. Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .

    2. Insert Line after L96 , add this code value:"" to init this new prop enter image description here

    3. Search on jQuery.fn.init , it will be almost Line 2747

    enter image description here

    1. Now , assign a value to value prop : (Before return statment add this.value=jQuery(selector).val()) enter image description here

    Enjoy now : $('#myDiv').value

    How to calculate distance from Wifi router using Signal Strength?

    To calculate the distance you need signal strength and frequency of the signal. Here is the java code:

    public double calculateDistance(double signalLevelInDb, double freqInMHz) {
        double exp = (27.55 - (20 * Math.log10(freqInMHz)) + Math.abs(signalLevelInDb)) / 20.0;
        return Math.pow(10.0, exp);
    }
    

    The formula used is:

    distance = 10 ^ ((27.55 - (20 * log10(frequency)) + signalLevel)/20)

    Example: frequency = 2412MHz, signalLevel = -57dbm, result = 7.000397427391188m

    This formula is transformed form of Free Space Path Loss(FSPL) formula. Here the distance is measured in meters and the frequency - in megahertz. For other measures you have to use different constant (27.55). Read for the constants here.

    For more information read here.

    Change the color of a checked menu item in a navigation drawer

    One need to set NavigateItem checked true whenever item in NavigateView is clicked

    //listen for navigation events
    NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
    navigationView.setNavigationItemSelectedListener(this);
    // select the correct nav menu item
    navigationView.getMenu().findItem(mNavItemId).setChecked(true);
    

    Add NavigationItemSelectedListener on NavigationView

      @Override
      public boolean onNavigationItemSelected(final MenuItem menuItem) {
        // update highlighted item in the navigation menu
        menuItem.setChecked(true);
        mNavItemId = menuItem.getItemId();
    
        // allow some time after closing the drawer before performing real navigation
        // so the user can see what is happening
        mDrawerLayout.closeDrawer(GravityCompat.START);
        mDrawerActionHandler.postDelayed(new Runnable() {
          @Override
          public void run() {
            navigate(menuItem.getItemId());
          }
        }, DRAWER_CLOSE_DELAY_MS);
        return true;
      }
    

    Jupyter/IPython Notebooks: Shortcut for "run all"?

    Jupyter Lab 1.0.4:

    1. In the top menu, go to: Settings->Advanced Settings Editor->Keyboard Shortcuts

    2. Paste this code in the User Preferences window:

    {
        "shortcuts": [
            {
                "command": "runmenu:run-all",
                "keys": [
                    "R",
                    "R"
                ],
                "selector": "[data-jp-kernel-user]:focus"
            }
        ]
    }
    
    1. Save (top right of the user-preferences window)

    This will be effective immediately. Here, two consecutive 'R' presses runs all cells (just like two '0' for kernel restart). Notably, system defaults has empty templates for all menu commands, including this code (search for run-all). The selector was copied from kernelmenu:restart, to allow printing r within cells. This system defaults copy-paste can be generalized to any command.

    POST: sending a post request in a url itself

    In windows this command does not work for me..I have tried the following command and it works..using this command I created session in couchdb sync gate way for the specific user...

    curl -v -H "Content-Type: application/json" -X POST -d "{ \"name\": \"abc\",\"password\": \"abc123\" }" http://localhost:4984/todo/_session
    

    MAMP mysql server won't start. No mysql processes are running

    Most of the answers here are offering to delete random files.

    Most of the time, this is the worst thing to do especially if it is important for you to keep the integrity of your development environment.

    As explained in the log file, if this problem is not related to a read access permission nor to a file you deleted in your mysql then the only solution is to:

    Open your my.conf file from the File menu in MAMP (File > Edit Template > MySQL)

    Find and edit this line to be: innodb_force_recovery = 1

    Save with ctrl+S

    MAMP will offer you to restart your servers

    Go back building the next unicorn :)

    Remove last character from C++ string

    If the length is non zero, you can also

    str[str.length() - 1] = '\0';
    

    Why are C# 4 optional parameters defined on interface not enforced on implementing class?

    Just want to add my take here, as the other answers do provide reasonable explanations, but not ones that fully satisfy me.

    Optional parameters are syntactic sugar for compile-time injection of the default value at the call site. This doesn't have anything to do with interfaces/implementations, and it can be seen as purely a side-effect of methods with optional parameters. So, when you call the method,

    public void TestMethod(bool value = false) { /*...*/ }
    

    like SomeClass.TestMethod(), it is actually SomeClass.TestMethod(false). If you call this method on an interface, from static type-checking, the method signature has the optional parameter. If you call this method on a deriving class's instance that doesn't have the optional parameter, from static type-checking, the method signature does not have the optional parameter, and must be called with full arguments.

    Due to how optional parameters are implemented, this is the natural design result.

    Declare an array in TypeScript

    Specific type of array in typescript

    export class RegisterFormComponent 
    {
         genders = new Array<GenderType>();   // Use any array supports different kind objects
    
         loadGenders()
         {
            this.genders.push({name: "Male",isoCode: 1});
            this.genders.push({name: "FeMale",isoCode: 2});
         }
    }
    
    type GenderType = { name: string, isoCode: number };    // Specified format
    

    How to add buttons like refresh and search in ToolBar in Android?

    OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom" instead of app:showAsAction="ifRoom" since i am using v7 library.

    However the title is coming at center of extended toolbar. How to make it appear at the top?

    Find Locked Table in SQL Server

    You can use sp_lock (and sp_lock2), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks:

    select  
        object_name(p.object_id) as TableName, 
        resource_type, resource_description
    from
        sys.dm_tran_locks l
        join sys.partitions p on l.resource_associated_entity_id = p.hobt_id
    

    Using Python to execute a command on every file in a folder

    Use os.walk to iterate recursively over directory content:

    import os
    
    root_dir = '.'
    
    for directory, subdirectories, files in os.walk(root_dir):
        for file in files:
            print os.path.join(directory, file)
    

    No real difference between os.system and subprocess.call here - unless you have to deal with strangely named files (filenames including spaces, quotation marks and so on). If this is the case, subprocess.call is definitely better, because you don't need to do any shell-quoting on file names. os.system is better when you need to accept any valid shell command, e.g. received from user in the configuration file.

    Check if a key exists inside a json object

    function to check undefined and null objects

    function elementCheck(objarray, callback) {
            var list_undefined = "";
            async.forEachOf(objarray, function (item, key, next_key) {
                console.log("item----->", item);
                console.log("key----->", key);
                if (item == undefined || item == '') {
                    list_undefined = list_undefined + "" + key + "!!  ";
                    next_key(null);
                } else {
                    next_key(null);
                }
            }, function (next_key) {
                callback(list_undefined);
            })
        }
    

    here is an easy way to check whether object sent is contain undefined or null

    var objarray={
    "passenger_id":"59b64a2ad328b62e41f9050d",
    "started_ride":"1",
    "bus_id":"59b8f920e6f7b87b855393ca",
    "route_id":"59b1333c36a6c342e132f5d5",
    "start_location":"",
    "stop_location":""
    }
    elementCheck(objarray,function(list){
    console.log("list");
    )
    

    Passing parameters to addTarget:action:forControlEvents

    This fixed my problem but it crashed unless I changed

    action:@selector(switchToNewsDetails:event:)                 
    

    to

    action:@selector(switchToNewsDetails: forEvent:)              
    

    Twitter Bootstrap 3: how to use media queries?

    To improve the main response:

    You can use the media attribute of the <link> tag (it support media queries) in order to download just the code the user needs.

    <link href="style.css" rel="stylesheet">
    <link href="deviceSizeDepending.css" rel="stylesheet" media="(min-width: 40em)">
    

    With this, the browser will download all CSS resources, regardless of the media attribute. The difference is that if the media-query of the media attribute is evaluated to false then that .css file and his content will not be render-blocking.

    Therefore, it is recommended to use the media attribute in the <link> tag since it guarantees a better user experience.

    Here you can read a Google article about this issue https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css

    Some tools that will help you to automate the separation of your css code in different files according to your media-querys

    Webpack https://www.npmjs.com/package/media-query-plugin https://www.npmjs.com/package/media-query-splitting-plugin

    PostCSS https://www.npmjs.com/package/postcss-extract-media-query

    ArrayIndexOutOfBoundsException when using the ArrayList's iterator

    You could also do a for loop as you would for an array but instead of array[i] you would use list.get(i)

    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
    

    Python: importing a sub-package or sub-module

    You seem to be misunderstanding how import searches for modules. When you use an import statement it always searches the actual module path (and/or sys.modules); it doesn't make use of module objects in the local namespace that exist because of previous imports. When you do:

    import package.subpackage.module
    from package.subpackage import module
    from module import attribute1
    

    The second line looks for a package called package.subpackage and imports module from that package. This line has no effect on the third line. The third line just looks for a module called module and doesn't find one. It doesn't "re-use" the object called module that you got from the line above.

    In other words from someModule import ... doesn't mean "from the module called someModule that I imported earlier..." it means "from the module named someModule that you find on sys.path...". There is no way to "incrementally" build up a module's path by importing the packages that lead to it. You always have to refer to the entire module name when importing.

    It's not clear what you're trying to achieve. If you only want to import the particular object attribute1, just do from package.subpackage.module import attribute1 and be done with it. You need never worry about the long package.subpackage.module once you've imported the name you want from it.

    If you do want to have access to the module to access other names later, then you can do from package.subpackage import module and, as you've seen you can then do module.attribute1 and so on as much as you like.

    If you want both --- that is, if you want attribute1 directly accessible and you want module accessible, just do both of the above:

    from package.subpackage import module
    from package.subpackage.module import attribute1
    attribute1 # works
    module.someOtherAttribute # also works
    

    If you don't like typing package.subpackage even twice, you can just manually create a local reference to attribute1:

    from package.subpackage import module
    attribute1 = module.attribute1
    attribute1 # works
    module.someOtherAttribute #also works