Programs & Examples On #Django media

Changing tab bar item image and text color iOS

Swift 3

I did it by creating a custom tabbar controller and added this code inside the viewDidLoad method.

    if let count = self.tabBar.items?.count {
        for i in 0...(count-1) {
            let imageNameForSelectedState   = arrayOfImageNameForSelectedState[i]
            let imageNameForUnselectedState = arrayOfImageNameForUnselectedState[i]

            self.tabBar.items?[i].selectedImage = UIImage(named: imageNameForSelectedState)?.withRenderingMode(.alwaysOriginal)
            self.tabBar.items?[i].image = UIImage(named: imageNameForUnselectedState)?.withRenderingMode(.alwaysOriginal)
        }
    }

    let selectedColor   = UIColor(red: 246.0/255.0, green: 155.0/255.0, blue: 13.0/255.0, alpha: 1.0)
    let unselectedColor = UIColor(red: 16.0/255.0, green: 224.0/255.0, blue: 223.0/255.0, alpha: 1.0)

    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: unselectedColor], for: .normal)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: selectedColor], for: .selected)

It worked for me!

enter image description here

Align DIV to bottom of the page

Right I think I know what you mean so lets see....

HTML:

<div id="con">
   <div id="content">Results will go here</div>
   <div id="footer">Footer will always be at the bottom</div>
</div>

CSS:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
div {
    outline: 1px solid;
}
#con {
   min-height:100%;
   position:relative;
}
#content {
   height: 1000px; /* Changed this height */
   padding-bottom:60px;
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
}

This demo have the height of contentheight: 1000px; so you can see what it would look like scrolling down the bottom.

DEMO HERE

This demo has the height of content height: 100px; so you can see what it would look like with no scrolling.

DEMO HERE

So this will move the footer below the div content but if content is not bigger then the screen (no scrolling) the footer will sit at the bottom of the screen. Think this is what you want. Have a look and a play with it.

Updated fiddles so its easier to see with backgrounds.

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

Python - TypeError: 'int' object is not iterable

This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...

To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !

>>> type(cow)
<class 'range'>
>>> 
>>> type(cow[0])
<class 'int'>
>>> 
>>> type(0)
<class 'int'>
>>> 
>>> >>> list(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

Escaping Double Quotes in Batch Script

eplawless's own answer simply and effectively solves his specific problem: it replaces all " instances in the entire argument list with \", which is how Bash requires double-quotes inside a double-quoted string to be represented.

To generally answer the question of how to escape double-quotes inside a double-quoted string using cmd.exe, the Windows command-line interpreter (whether on the command line - often still mistakenly called the "DOS prompt" - or in a batch file):See bottom for a look at PowerShell.

tl;dr:

  • You must use "" when passing a string to a(nother) batch file and you may use "" with applications created with Microsoft's C/C++/.NET compilers (which also accept \"), which on Windows includes Python and Node.js:

    • Example: foo.bat "We had 3"" of rain."

    • The following applies to batch files only:

      • "" is the only way to get the command interpreter (cmd.exe) to treat the whole double-quoted string as a single argument.

      • Sadly, however, not only are the enclosing double-quotes retained (as usual), but so are the doubled escaped ones, so obtaining the intended string is a two-step process; e.g., assuming that the double-quoted string is passed as the 1st argument, %1:

      • set "str=%~1" removes the enclosing double-quotes; set "str=%str:""="%" then converts the doubled double-quotes to single ones.
        Be sure to use the enclosing double-quotes around the assignment parts to prevent unwanted interpretation of the values.

  • \" is required - as the only option - by many other programs, (e.g., Ruby, Perl, and even Microsoft's own Windows PowerShell(!)), but ITS USE IS NOT SAFE:

    • \" is what many executables and interpreters either require - including Windows PowerShell - when passed strings from the outside - or, in the case of Microsoft's compilers, support as an alternative to "" - ultimately, though, it's up to the target program to parse the argument list.
      • Example: foo.exe "We had 3\" of rain."
    • HOWEVER, USE OF \" CAN RESULT IN UNWANTED, ARBITRARY EXECUTION OF COMMANDS and/or INPUT/OUTPUT REDIRECTIONS:
      • The following characters present this risk: & | < >
      • For instance, the following results in unintended execution of the ver command; see further below for an explanation and the next bullet point for a workaround:
        • foo.exe "3\" of snow" "& ver."
    • For Windows PowerShell, \"" and "^"" are robust, but limited alternatives (see section "Calling PowerShell's CLI ..." below).
  • If you must use \", there are only 3 safe approaches, which are, however quite cumbersome: Tip of the hat to T S for his help.

    • Using (possibly selective) delayed variable expansion in your batch file, you can store literal \" in a variable and reference that variable inside a "..." string using !var! syntax - see T S's helpful answer.

      • The above approach, despite being cumbersome, has the advantage that you can apply it methodically and that it works robustly, with any input.
    • Only with LITERAL strings - ones NOT involving VARIABLES - do you get a similarly methodical approach: categorically ^-escape all cmd.exe metacharacters: " & | < > and - if you also want to suppress variable expansion - %:
      foo.exe ^"3\^" of snow^" ^"^& ver.^"

    • Otherwise, you must formulate your string based on recognizing which portions of the string cmd.exe considers unquoted due to misinterpreting \" as closing delimiters:

      • in literal portions containing shell metacharacters: ^-escape them; using the example above, it is & that must be ^-escaped:
        foo.exe "3\" of snow" "^& ver."

      • in portions with %...%-style variable references: ensure that cmd.exe considers them part of a "..." string and that that the variable values do not themselves have embedded, unbalanced quotes - which is not even always possible.

For background information, read on.


Background

Note: This is based on my own experiments. Do let me know if I'm wrong.

POSIX-like shells such as Bash on Unix-like systems tokenize the argument list (string) before passing arguments individually to the target program: among other expansions, they split the argument list into individual words (word splitting) and remove quoting characters from the resulting words (quote removal). The target program is handed an array of individual arguments, with syntactic quotes removed.

By contrast, the Windows command interpreter apparently does not tokenize the argument list and simply passes the single string comprising all arguments - including quoting chars. - to the target program.
However, some preprocessing takes place before the single string is passed to the target program: ^ escape chars. outside of double-quoted strings are removed (they escape the following char.), and variable references (e.g., %USERNAME%) are interpolated first.

Thus, unlike in Unix, it is the target program's responsibility to parse to parse the arguments string and break it down into individual arguments with quotes removed. Thus, different programs can hypothetically require differing escaping methods and there's no single escaping mechanism that is guaranteed to work with all programs - https://stackoverflow.com/a/4094897/45375 contains excellent background on the anarchy that is Windows command-line parsing.

In practice, \" is very common, but NOT SAFE, as mentioned above:

Since cmd.exe itself doesn't recognize \" as an escaped double-quote, it can misconstrue later tokens on the command line as unquoted and potentially interpret them as commands and/or input/output redirections.
In a nutshell: the problem surfaces, if any of the following characters follow an opening or unbalanced \": & | < >; for example:

foo.exe "3\" of snow" "& ver."

cmd.exe sees the following tokens, resulting from misinterpreting \" as a regular double-quote:

  • "3\"
  • of
  • snow" "
  • rest: & ver.

Since cmd.exe thinks that & ver. is unquoted, it interprets it as & (the command-sequencing operator), followed by the name of a command to execute (ver. - the . is ignored; ver reports cmd.exe's version information).
The overall effect is:

  • First, foo.exe is invoked with the first 3 tokens only.
  • Then, command ver is executed.

Even in cases where the accidental command does no harm, your overall command won't work as designed, given that not all arguments are passed to it.

Many compilers / interpreters recognize ONLY \" - e.g., the GNU C/C++ compiler, Python, Perl, Ruby, even Microsoft's own Windows PowerShell when invoked from cmd.exe - and, except (with limitations) for Windows PowerShell with \"", for them there is no simple solution to this problem.
Essentially, you'd have to know in advance which portions of your command line are misinterpreted as unquoted, and selectively ^-escape all instances of & | < > in those portions.

By contrast, use of "" is SAFE, but is regrettably only supported by Microsoft-compiler-based executables and batch files (in the case of batch files, with the quirks discussed above), which notable excludes PowerShell - see next section.


Calling PowerShell's CLI from cmd.exe or POSIX-like shells:

Note: See the bottom section for how quoting is handled inside PowerShell.

When invoked from the outside - e.g., from cmd.exe, whether from the command line or a batch file:

  • PowerShell [Core] v6+ now properly recognizes "" (in addition to \"), which is both safe to use and whitespace-preserving.

    • pwsh -c " ""a & c"".length " doesn't break and correctly yields 6
  • Windows PowerShell (the legacy edition whose last version is 5.1) recognizes only \" and, on Windows also """ and the more robust \"" / "^"" (even though internally PowerShell uses ` as the escape character in double-quoted strings and also accepts "" - see bottom section):

Calling Windows PowerShell from cmd.exe / a batch file:

  • "" breaks, because it is fundamentally unsupported:

    • powershell -c " ""ab c"".length " -> error "The string is missing the terminator"
  • \" and """ work in principle, but aren't safe:

    • powershell -c " \"ab c\".length " works as intended: it outputs 5 (note the 2 spaces)
    • But it isn't safe, because cmd.exe metacharacters break the command, unless escaped:
      powershell -c " \"a& c\".length " breaks, due to the &, which would have to be escaped as ^&
  • \"" is safe, but normalize interior whitespace, which can be undesired:

    • powershell -c " \""a& c\"".length " outputs 4(!), because the 2 spaces are normalized to 1.
  • "^"" is the best choice for Windows PowerShell specifically, where it is both safe and whitespace-preserving, but with PowerShell Core (on Windows) it is the same as \"", i.e, whitespace-normalizing. Credit goes to Venryx for discovering this approach.

    • powershell -c " "^""a& c"^"".length " works: doesn't break - despite & - and outputs 5, i.e., correctly preserved whitespace.

    • PowerShell Core: pwsh -c " "^""a& c"^"".length " works, but outputs 4, i.e. normalizes whitespace, as \"" does.

On Unix-like platforms (Linux, macOS), when calling PowerShell [Core]'s CLI, pwsh, from a POSIX-like shell such as bash:

You must use \", which, however is both safe and whitespace-preserving:

$ pwsh -c " \"a&  c|\".length" # OK: 5

Related information

  • ^ can only be used as the escape character in unquoted strings - inside double-quoted strings, ^ is not special and treated as a literal.

    • CAVEAT: Use of ^ in parameters passed to the call statement is broken (this applies to both uses of call: invoking another batch file or binary, and calling a subroutine in the same batch file):
      • ^ instances in double-quoted values are inexplicably doubled, altering the value being passed: e.g., if variable %v% contains literal value a^b, call :foo "%v%" assigns "a^^b"(!) to %1 (the first parameter) in subroutine :foo.
      • Unquoted use of ^ with call is broken altogether in that ^ can no longer be used to escape special characters: e.g., call foo.cmd a^&b quietly breaks (instead of passing literal a&b too foo.cmd, as would be the case without call) - foo.cmd is never even invoked(!), at least on Windows 7.
  • Escaping a literal % is a special case, unfortunately, which requires distinct syntax depending on whether a string is specified on the command line vs. inside a batch file; see https://stackoverflow.com/a/31420292/45375

    • The short of it: Inside a batch file, use %%. On the command line, % cannot be escaped, but if you place a ^ at the start, end, or inside a variable name in an unquoted string (e.g., echo %^foo%), you can prevent variable expansion (interpolation); % instances on the command line that are not part of a variable reference are treated as literals (e.g, 100%).
  • Generally, to safely work with variable values that may contain spaces and special characters:

    • Assignment: Enclose both the variable name and the value in a single pair of double-quotes; e.g., set "v=a & b" assigns literal value a & b to variable %v% (by contrast, set v="a & b" would make the double-quotes part of the value). Escape literal % instances as %% (works only in batch files - see above).
    • Reference: Double-quote variable references to make sure their value is not interpolated; e.g., echo "%v%" does not subject the value of %v% to interpolation and prints "a & b" (but note that the double-quotes are invariably printed too). By contrast, echo %v% passes literal a to echo, interprets & as the command-sequencing operator, and therefore tries to execute a command named b.
      Also note the above caveat re use of ^ with the call statement.
    • External programs typically take care of removing enclosing double-quotes around parameters, but, as noted, in batch files you have to do it yourself (e.g., %~1 to remove enclosing double-quotes from the 1st parameter) and, sadly, there is no direct way that I know of to get echo to print a variable value faithfully without the enclosing double-quotes.
      • Neil offers a for-based workaround that works as long as the value has no embedded double quotes; e.g.:
        set "var=^&')|;,%!" for /f "delims=" %%v in ("%var%") do echo %%~v
  • cmd.exe does not recognize single-quotes as string delimiters - they are treated as literals and cannot generally be used to delimit strings with embedded whitespace; also, it follows that the tokens abutting the single-quotes and any tokens in between are treated as unquoted by cmd.exe and interpreted accordingly.

    • However, given that target programs ultimately perform their own argument parsing, some programs such as Ruby do recognize single-quoted strings even on Windows; by contrast, C/C++ executables, Perl and Python do not recognize them.
      Even if supported by the target program, however, it is not advisable to use single-quoted strings, given that their contents are not protected from potentially unwanted interpretation by cmd.exe.

Quoting from within PowerShell:

Windows PowerShell is a much more advanced shell than cmd.exe, and it has been a part of Windows for many years now (and PowerShell Core brought the PowerShell experience to macOS and Linux as well).

PowerShell works consistently internally with respect to quoting:

  • inside double-quoted strings, use `" or "" to escape double-quotes
  • inside single-quoted strings, use '' to escape single-quotes

This works on the PowerShell command line and when passing parameters to PowerShell scripts or functions from within PowerShell.

(As discussed above, passing an escaped double-quote to PowerShell from the outside requires \" or, more robustly, \"" - nothing else works).

Sadly, when invoking external programs from PowerShell, you're faced with the need to both accommodate PowerShell's own quoting rules and to escape for the target program:

This problematic behavior is also discussed and summarized in this answer

Double-quotes inside double-quoted strings:

Consider string "3`" of rain", which PowerShell-internally translates to literal 3" of rain.

If you want to pass this string to an external program, you have to apply the target program's escaping in addition to PowerShell's; say you want to pass the string to a C program, which expects embedded double-quotes to be escaped as \":

foo.exe "3\`" of rain"

Note how both `" - to make PowerShell happy - and the \ - to make the target program happy - must be present.

The same logic applies to invoking a batch file, where "" must be used:

foo.bat "3`"`" of rain"

By contrast, embedding single-quotes in a double-quoted string requires no escaping at all.

Single-quotes inside single-quoted strings do not require extra escaping; consider '2'' of snow', which is PowerShell' representation of 2' of snow.

foo.exe '2'' of snow'
foo.bat '2'' of snow'

PowerShell translates single-quoted strings to double-quoted ones before passing them to the target program.

However, double-quotes inside single-quoted strings, which do not need escaping for PowerShell, do still need to be escaped for the target program:

foo.exe '3\" of rain'
foo.bat '3"" of rain'

PowerShell v3 introduced the magic --% option, called the stop-parsing symbol, which alleviates some of the pain, by passing anything after it uninterpreted to the target program, save for cmd.exe-style environment-variable references (e.g., %USERNAME%), which are expanded; e.g.:

foo.exe --% "3\" of rain" -u %USERNAME%

Note how escaping the embedded " as \" for the target program only (and not also for PowerShell as \`") is sufficient.

However, this approach:

  • does not allow for escaping % characters in order to avoid environment-variable expansions.
  • precludes direct use of PowerShell variables and expressions; instead, the command line must be built in a string variable in a first step, and then invoked with Invoke-Expression in a second.

Thus, despite its many advancements, PowerShell has not made escaping much easier when calling external programs. It has, however, introduced support for single-quoted strings.

I wonder if it's fundamentally possible in the Windows world to ever switch to the Unix model of letting the shell do all the tokenization and quote removal predictably, up front, irrespective of the target program, and then invoke the target program by passing the resulting tokens.

Display label text with line breaks in c#

I had to replace new lines with br

string newString = oldString.Replace("\n", "<br />");

or if you use xml

<asp:Label ID="Label1" runat="server" Text='<%# ShowLineBreaks(Eval("Comments")) %>'></asp:Label>

Then in code behind

public string ShowLineBreaks(object text)
{
    return (text.ToString().Replace("\n", "<br/>"));
}

How do I get whole and fractional parts from double in JSP/Java?

The mantissa and exponent of an IEEE double floating point number are the values such that

value = sign * (1 + mantissa) * pow(2, exponent)

if the mantissa is of the form 0.101010101_base 2 (ie its most sigificant bit is shifted to be after the binary point) and the exponent is adjusted for bias.

Since 1.6, java.lang.Math also provides a direct method to get the unbiased exponent (called getExponent(double))

However, the numbers you're asking for are the integral and fractional parts of the number, which can be obtained using

integral = Math.floor(x)
fractional = x - Math.floor(x)

though you may you want to treat negative numbers differently (floor(-3.5) == -4.0), depending why you want the two parts.

I'd strongly suggest that you don't call these mantissa and exponent.

is there any PHP function for open page in new tab

You can simply use target="_blank" to open a page in a new tab

<a href="whatever.php" target="_blank">Opens On Another Tab</a>

Or you can simply use a javascript for onload

<body onload="window.open(url, '_blank');">

How to run an android app in background?

Starting an Activity is not the right approach for this behavior. Instead have your BroadcastReceiver use an intent to start a Service which can continue to run as long as possible. (See http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle)

See also Persistent service

Compare two MySQL databases

Toad for MySQL has data and schema compare features, and I believe it will even create a synchronization script. Best of all, it's freeware.

Difference between onStart() and onResume()

A particularly feisty example is when you decide to show a managed Dialog from an Activity using showDialog(). If the user rotates the screen while the dialog is still open (we call this a "configuration change"), then the main Activity will go through all the ending lifecycle calls up untill onDestroy(), will be recreated, and go back up through the lifecycles. What you might not expect however, is that onCreateDialog() and onPrepareDialog() (the methods that are called when you do showDialog() and now again automatically to recreate the dialog - automatically since it is a managed dialog) are called between onStart() and onResume(). The pointe here is that the dialog does not cover the full screen and therefore leaves part of the main activity visible. It's a detail but it does matter!

How can I get city name from a latitude and longitude point?

Following Code Works Fine to Get City Name (Using Google Map Geo API) :

HTML

<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>

SCRIPT

var x=document.getElementById("demo");
function getLocation(){
    if (navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else{
        x.innerHTML="Geolocation is not supported by this browser.";
    }
}

function showPosition(position){
    lat=position.coords.latitude;
    lon=position.coords.longitude;
    displayLocation(lat,lon);
}

function showError(error){
    switch(error.code){
        case error.PERMISSION_DENIED:
            x.innerHTML="User denied the request for Geolocation."
        break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is unavailable."
        break;
        case error.TIMEOUT:
            x.innerHTML="The request to get user location timed out."
        break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="An unknown error occurred."
        break;
    }
}

function displayLocation(latitude,longitude){
    var geocoder;
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude);

    geocoder.geocode(
        {'latLng': latlng}, 
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    x.innerHTML = "city name is: " + city;
                }
                else  {
                    x.innerHTML = "address not found";
                }
            }
            else {
                x.innerHTML = "Geocoder failed due to: " + status;
            }
        }
    );
}

What is secret key for JWT based authentication and how to generate it?

You can write your own generator. The secret key is essentially a byte array. Make sure that the string that you convert to a byte array is base64 encoded.

In Java, you could do something like this.

String key = "random_secret_key";
String base64Key = DatatypeConverter.printBase64Binary(key.getBytes());
byte[] secretBytes = DatatypeConverter.parseBase64Binary(base64Key);

How to work with complex numbers in C?

The notion of complex numbers was introduced in mathematics, from the need of calculating negative quadratic roots. Complex number concept was taken by a variety of engineering fields.

Today that complex numbers are widely used in advanced engineering domains such as physics, electronics, mechanics, astronomy, etc...

Real and imaginary part, of a negative square root example:

#include <stdio.h>   
#include <complex.h>

int main() 
{
    int negNum;

    printf("Calculate negative square roots:\n"
           "Enter negative number:");

    scanf("%d", &negNum);

    double complex negSqrt = csqrt(negNum);

    double pReal = creal(negSqrt);
    double pImag = cimag(negSqrt);

    printf("\nReal part %f, imaginary part %f"
           ", for negative square root.(%d)",
           pReal, pImag, negNum);

    return 0;
}

The request was aborted: Could not create SSL/TLS secure channel

Another possibility is that the code being executed doesn't have the required premissions.

In my case, I got this error when using Visual Studio debugger to test a call to a web service. Visual Studio wasn't running as Administrator, which caused this exception.

What techniques can be used to speed up C++ compilation times?

Use

#pragma once

at the top of header files, so if they're included more than once in a translation unit, the text of the header will only get included and parsed once.

Which .NET Dependency Injection frameworks are worth looking into?

Autofac. https://github.com/autofac/Autofac It is really fast and pretty good. Here is a link with comparisons (made after Ninject fixed a memory leak issue).

http://www.codinginstinct.com/2008/05/ioc-container-benchmark-rerevisted.html

How to make the corners of a button round?

This link has all the information you need. Here

Shape.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape      xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">

    <solid   android:color="#EAEAEA"/>

    <corners    android:bottomLeftRadius="8dip"
                android:topRightRadius="8dip"
                android:topLeftRadius="1dip"
                android:bottomRightRadius="1dip"
                />
</shape>

and main.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

    <TextView   android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Hello Android from NetBeans"/>

    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Nishant Nair"
            android:padding="5dip"
            android:layout_gravity="center"
            android:background="@drawable/button_shape"
            />
</LinearLayout>

This should give you your desired result.

Best of luck

Filter LogCat to get only the messages from My Application in Android?

In linux, this worked for me:

adb logcat | grep `adb shell ps | grep your.package | awk '{print $2}'`

Go to Matching Brace in Visual Studio?

On a Hungarian keyboard it is Ctrl + ú.

How do I plot list of tuples in Python?

In matplotlib it would be:

import matplotlib.pyplot as plt

data =  [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x_val = [x[0] for x in data]
y_val = [x[1] for x in data]

print x_val
plt.plot(x_val,y_val)
plt.plot(x_val,y_val,'or')
plt.show()

which would produce:

enter image description here

How to store an output of shell script to a variable in Unix?

You need to start the script with a preceding dot, this will put the exported variables in the current environment.

#!/bin/bash
...
export output="SUCCESS"

Then execute it like so

chmod +x /tmp/test.sh
. /tmp/test.sh

When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate

How to concatenate variables into SQL strings

You can accomplish this (if I understand what you are trying to do) using dynamic SQL.

The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.

So you can use something like this approach:

SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue 
    + ' AS fld1 FROM tbl' + @KeyValue

EXEC (@stmt)

First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:

'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'

At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE (or EXEC for short).

The old-school sp_executesql procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.


FOLLOWUP

EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.

Consider what would happen if @KeyValue contained the string:

'1 AS foo; DROP TABLE students; -- '

The string we would produce as a SQL statement would be:

'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'

When we EXECUTE that string as a SQL statement:

INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...

And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)

One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'. If an illegal character is found, then reject the value, and exit without executing any SQL.

Mean of a column in a data frame, given the column's name

I think what you are being asked to do (or perhaps asking yourself?) is take a character value which matches the name of a column in a particular dataframe (possibly also given as a character). There are two tricks here. Most people learn to extract columns with the "$" operator and that won't work inside a function if the function is passed a character vecor. If the function is also supposed to accept character argument then you will need to use the get function as well:

 df1 <- data.frame(a=1:10, b=11:20)
 mean_col <- function( dfrm, col ) mean( get(dfrm)[[ col ]] )
 mean_col("df1", "b")
 # [1] 15.5

There is sort of a semantic boundary between ordinary objects like character vectors and language objects like the names of objects. The get function is one of the functions that lets you "promote" character values to language level evaluation. And the "$" function will NOT evaluate its argument in a function, so you need to use"[[". "$" only is useful at the console level and needs to be completely avoided in functions.

Linq to Entities join vs groupjoin

Let's suppose you have two different classes:

public class Person
{
    public string Name, Email;
    
    public Person(string name, string email)
    {
        Name = name;
        Email = email;
    }
}
class Data
{
    public string Mail, SlackId;
    
    public Data(string mail, string slackId)
    {
        Mail = mail;
        SlackId = slackId;
    }
}

Now, let's Prepare data to work with:

var people = new Person[]
    {
        new Person("Sudi", "[email protected]"),
        new Person("Simba", "[email protected]"),
        new Person("Sarah", string.Empty)
    };
    
    var records = new Data[]
    {
        new Data("[email protected]", "Sudi_Try"),
        new Data("[email protected]", "Sudi@Test"),
        new Data("[email protected]", "SimbaLion")
    };

You will note that [email protected] has got two slackIds. I have made that for demonstrating how Join works.

Let's now construct the query to join Person with Data:

var query = people.Join(records,
        x => x.Email,
        y => y.Mail,
        (person, record) => new { Name = person.Name, SlackId = record.SlackId});
    Console.WriteLine(query);

After constructing the query, you could also iterate over it with a foreach like so:

foreach (var item in query)
    {
        Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");
    }

Let's also output the result for GroupJoin:

Console.WriteLine(
    
        people.GroupJoin(
            records,
            x => x.Email,
            y => y.Mail,
            (person, recs) => new {
                Name = person.Name,
                SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.
            }
        ));

You will notice that the GroupJoin will put all SlackIds in a single group.

Valid to use <a> (anchor tag) without href attribute?

It is valid. You can, for example, use it to show modals (or similar things that respond to data-toggle and data-target attributes).

Something like:

<a role="button" data-toggle="modal" data-target=".bs-example-modal-sm" aria-hidden="true"><i class="fa fa-phone"></i></a>

Here I use the font-awesome icon, which is better as a a tag rather than a button, to show a modal. Also, setting role="button" makes the pointer change to an action type. Without either href or role="button", the cursor pointer does not change.

How to set zoom level in google map

What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:

20 : 1128.497220

19 : 2256.994440

18 : 4513.988880

17 : 9027.977761

16 : 18055.955520

15 : 36111.911040

14 : 72223.822090

13 : 144447.644200

12 : 288895.288400

11 : 577790.576700

10 : 1155581.153000

9 : 2311162.307000

8 : 4622324.614000

7 : 9244649.227000

6 : 18489298.450000

5 : 36978596.910000

4 : 73957193.820000

3 : 147914387.600000

2 : 295828775.300000

1 : 591657550.500000

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

What does the clearfix class do in css?

How floats work

When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.

float vs display:inline

Before the invention of display:inline-block, websites use float to set elements beside each other. float is preferred over display:inline since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.

Float problems

The main problem is that we're using float against its intended purpose.

Another is that while float allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>, the <div> will not impart 100px in height to the container.

Unlike position:absolute, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.

Clearfix to the rescue

What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear.

Examples

Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.

What you have

Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:

  • The first clearfix you have appends an invisible pseudo-element, which is styled clear:both, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.

  • The second one appends the style display:inline-block which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.

  • This was the reapplication of display:block due to IE-MAC rule above. This rule was "hidden" from IE-MAC.

All in all, these 3 rules keep the .clearfix working cross-browser, with old browsers in mind.

JPA: how do I persist a String into a database field, type MYSQL Text

for mysql 'text':

@Column(columnDefinition = "TEXT")
private String description;

for mysql 'longtext':

@Lob
private String description;

python multithreading wait till all threads finished

From the threading module documentation

There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.

There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be join()ed. They are never deleted, since it is impossible to detect the termination of alien threads.

So, to catch those two cases when you are not interested in keeping a list of the threads you create:

import threading as thrd


def alter_data(data, index):
    data[index] *= 2


data = [0, 2, 6, 20]

for i, value in enumerate(data):
    thrd.Thread(target=alter_data, args=[data, i]).start()

for thread in thrd.enumerate():
    if thread.daemon:
        continue
    try:
        thread.join()
    except RuntimeError as err:
        if 'cannot join current thread' in err.args[0]:
            # catchs main thread
            continue
        else:
            raise

Whereupon:

>>> print(data)
[0, 4, 12, 40]

How to load image to WPF in runtime?

In WPF an image is typically loaded from a Stream or an Uri.

BitmapImage supports both and an Uri can even be passed as constructor argument:

var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);

If the image file is located in a local folder, you would have to use a file:// Uri. You could create such a Uri from a path like this:

var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);

If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:

var uri = new Uri("pack://application:,,,/Bilder/sas.png");

In this case the Visual Studio Build Action for sas.png would have to be Resource.

Once you have created a BitmapImage and also have an Image control like in this XAML

<Image Name="image1" />

you would simply assign the BitmapImage to the Source property of that Image control:

image1.Source = bitmap;

How do you set your pythonpath in an already-created virtualenv?

I modified my activate script to source the file .virtualenvrc, if it exists in the current directory, and to save/restore PYTHONPATH on activate/deactivate.

You can find the patched activate script here.. It's a drop-in replacement for the activate script created by virtualenv 1.11.6.

Then I added something like this to my .virtualenvrc:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"

Add line break within tooltips

Just add a data attribute

data-html="true"

and you're good to go.

Eg. usage:

<i data-html="true" class="tooltip ficon-help-icon" twipsy-content-set="true" data-original-title= "<b>Hello</b> Stackoverflow" </i>

It has worked in majority of the tooltip plugins i have tried as of now.

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

I used this (need to run it only once); also make sure you have rights to execute:

from PowerShell with elevated rights:

Set-ExecutionPolicy=RemoteSigned

then from a bat file:

-----------------------------------------

 ftype Microsoft.PowerShellScript.1="C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe" -noexit ^&'%%1'

 assoc .ps1=Microsoft.PowerShellScript.1

-----------------------------------------
auto exit: remove -noexit 

and voila; double-clicking a *.ps1 will execute it.

Swift: Sort array of objects alphabetically

With Swift 3, you can choose one of the following ways to solve your problem.


1. Using sorted(by:?) with a Movie class that does not conform to Comparable protocol

If your Movie class does not conform to Comparable protocol, you must specify in your closure the property on which you wish to use Array's sorted(by:?) method.

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0.name < $1.name })
// let sortedMovies = movies.sorted { $0.name < $1.name } // also works

print(sortedMovies)

/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/

2. Using sorted(by:?) with a Movie class that conforms to Comparable protocol

However, by making your Movie class conform to Comparable protocol, you can have a much concise code when you want to use Array's sorted(by:?) method.

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible, Comparable {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

    static func ==(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name == rhs.name
    }

    static func <(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name < rhs.name
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0 < $1 })
// let sortedMovies = movies.sorted { $0 < $1 } // also works
// let sortedMovies = movies.sorted(by: <) // also works

print(sortedMovies)

/*
 prints: [Avatar, Piranha II: The Spawning, Titanic]
 */

3. Using sorted() with a Movie class that conforms to Comparable protocol

By making your Movie class conform to Comparable protocol, you can use Array's sorted() method as an alternative to sorted(by:?).

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible, Comparable {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

    static func ==(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name == rhs.name
    }

    static func <(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name < rhs.name
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted()

print(sortedMovies)

/*
 prints: [Avatar, Piranha II: The Spawning, Titanic]
 */

How to initialize a nested struct?

Well, any specific reason to not make Proxy its own struct?

Anyway you have 2 options:

The proper way, simply move proxy to its own struct, for example:

type Configuration struct {
    Val string
    Proxy Proxy
}

type Proxy struct {
    Address string
    Port    string
}

func main() {

    c := &Configuration{
        Val: "test",
        Proxy: Proxy{
            Address: "addr",
            Port:    "port",
        },
    }
    fmt.Println(c)
    fmt.Println(c.Proxy.Address)
}

The less proper and ugly way but still works:

c := &Configuration{
    Val: "test",
    Proxy: struct {
        Address string
        Port    string
    }{
        Address: "addr",
        Port:    "80",
    },
}

Using numpy to build an array of all combinations of two arrays

Here's yet another way, using pure NumPy, no recursion, no list comprehension, and no explicit for loops. It's about 20% slower than the original answer, and it's based on np.meshgrid.

def cartesian(*arrays):
    mesh = np.meshgrid(*arrays)  # standard numpy meshgrid
    dim = len(mesh)  # number of dimensions
    elements = mesh[0].size  # number of elements, any index will do
    flat = np.concatenate(mesh).ravel()  # flatten the whole meshgrid
    reshape = np.reshape(flat, (dim, elements)).T  # reshape and transpose
    return reshape

For example,

x = np.arange(3)
a = cartesian(x, x, x, x, x)
print(a)

gives

[[0 0 0 0 0]
 [0 0 0 0 1]
 [0 0 0 0 2]
 ..., 
 [2 2 2 2 0]
 [2 2 2 2 1]
 [2 2 2 2 2]]

Is there a limit on how much JSON can hold?

It depends on the implementation of your JSON writer/parser. Microsoft's DataContractJsonSerializer seems to have a hard limit around 8kb (8192 I think), and it will error out for larger strings.

Edit: We were able to resolve the 8K limit for JSON strings by setting the MaxJsonLength property in the web config as described in this answer: https://stackoverflow.com/a/1151993/61569

ImportError: No module named _ssl

I had exactly the same problem. I fixed it without rebuilding python, as follows:

  1. Find another server with the same architecture (i386 or x86_64) and the same python version (example: 2.7.5). Yes, this is the hard part. You can try installing python from sources into another server if you can't find any server with the same python version.

  2. In this another server, check if import ssl works. It should work.

  3. If it works, then try to find the _ssl lilbrary as follows:

    [root@myserver]# find / -iname _ssl.so
    /usr/local/python27/lib/python2.7/lib-dynload/_ssl.so
    
  4. Copy this file into the original server. Use the same destination folder: /usr/local/python27/lib/python2.7/lib-dynload/

  5. Double check owner and permissions:

    [root@myserver]# chown root:root _ssl.so
    [root@myserver]# chmod 755 _ssl.so
    
  6. Now you should be able to import ssl.

This worked for me in a CentOS 6.3 x86_64 environment with python 2.7.3. Also I had python 2.6.6 installed, but with ssl working fine.

Force add despite the .gitignore file

Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:

If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.

You should just un-ignore it in the .gitignore file like that: Unignore subdirectories of ignored directories in Git

Why I can't change directories using "cd"?

You can execute some lines in the same subshell if you end lines with backslash.

cd somedir; \
pwd

PHP prepend leading zero before single digit number, on-the-fly

The universal tool for string formatting, sprintf:

$stamp = sprintf('%s%02s', $year, $month);

http://php.net/manual/en/function.sprintf.php

global variable for all controller and views

In Laravel 5.1 I needed a global variable populated with model data accessible in all views.

I followed a similar approach to ollieread's answer and was able to use my variable ($notifications) in any view.

My controller location: /app/Http/Controllers/Controller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

use App\Models\Main as MainModel;
use View;

abstract class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct() {
        $oMainM = new MainModel;
        $notifications = $oMainM->get_notifications();
        View::share('notifications', $notifications);
    }
}

My model location: /app/Models/Main.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class Main extends Model
{
    public function get_notifications() {...

how does array[100] = {0} set the entire array to 0?

It's not magic.

The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).

The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value.

Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:

char array[100] = {};

As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization

Difference between map, applymap and apply methods in Pandas

FOMO:

The following example shows apply and applymap applied to a DataFrame.

map function is something you do apply on Series only. You cannot apply map on DataFrame.

The thing to remember is that apply can do anything applymap can, but apply has eXtra options.

The X factor options are: axis and result_type where result_type only works when axis=1 (for columns).

df = DataFrame(1, columns=list('abc'),
                  index=list('1234'))
print(df)

f = lambda x: np.log(x)
print(df.applymap(f)) # apply to the whole dataframe
print(np.log(df)) # applied to the whole dataframe
print(df.applymap(np.sum)) # reducing can be applied for rows only

# apply can take different options (vs. applymap cannot)
print(df.apply(f)) # same as applymap
print(df.apply(sum, axis=1))  # reducing example
print(df.apply(np.log, axis=1)) # cannot reduce
print(df.apply(lambda x: [1, 2, 3], axis=1, result_type='expand')) # expand result

As a sidenote, Series map function, should not be confused with the Python map function.

The first one is applied on Series, to map the values, and the second one to every item of an iterable.


Lastly don't confuse the dataframe apply method with groupby apply method.

How to subtract 30 days from the current datetime in mysql?

You can also use

select CURDATE()-INTERVAL 30 DAY

Android load from URL to Bitmap

I Prefer these one:

Creates Bitmap from InputStream and returns it:

    public static  Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
            stream.close();
        }
        catch (IOException e1) {
            e1.printStackTrace();
            System.out.println("downloadImage"+ e1.toString());
        }
        return bitmap;
    }

  // Makes HttpURLConnection and returns InputStream

 public static  InputStream getHttpConnection(String urlString)  throws IOException {

        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("downloadImage" + ex.toString());
        }
        return stream;
    }

REMEMBER :

Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. For Gingerbread and later, HttpURLConnection is the best choice.

From Android 3.x Honeycomb or later, you cannot perform Network IO on the UI thread and doing this throws android.os.NetworkOnMainThreadException. You must use Asynctask instead as shown below

/**     AsyncTAsk for Image Bitmap  */
    private class AsyncGettingBitmapFromUrl extends AsyncTask<String, Void, Bitmap> {


        @Override
        protected Bitmap doInBackground(String... params) {

            System.out.println("doInBackground");

            Bitmap bitmap = null;

            bitmap = AppMethods.downloadImage(params[0]);

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {

            System.out.println("bitmap" + bitmap);

        }
    }

How do you change the size of figures drawn with matplotlib?

Deprecation note:
As per the official Matplotlib guide, usage of the pylab module is no longer recommended. Please consider using the matplotlib.pyplot module instead, as described by this other answer.

The following seems to work:

from pylab import rcParams
rcParams['figure.figsize'] = 5, 10

This makes the figure's width 5 inches, and its height 10 inches.

The Figure class then uses this as the default value for one of its arguments.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

You can try this:

for file in *.jpg;
do
  mv $file $somestring_${file:((-7))}
done

You can see "parameter expansion" in man bash to understand the above better.

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

Also make sure the value is not too large or too small for int like in my case.

Google Maps API v3 marker with label

the above solutions wont work on ipad-2

recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)

What's the difference between isset() and array_key_exists()?

array_key_exists will definitely tell you if a key exists in an array, whereas isset will only return true if the key/variable exists and is not null.

$a = array('key1' => '????', 'key2' => null);

isset($a['key1']);             // true
array_key_exists('key1', $a);  // true

isset($a['key2']);             // false
array_key_exists('key2', $a);  // true

There is another important difference: isset doesn't complain when $a does not exist, while array_key_exists does.

How can I replace a regex substring match in Javascript?

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);

Or if you're sure there won't be any other digits in the string:

var str   = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

What is the easiest way to get current GMT time in Unix timestamp format?

Does this help?

from datetime import datetime
import calendar

d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime

How to convert Python UTC datetime object to UNIX timestamp

How can I get a side-by-side diff when I do "git diff"?

Here's an approach. If you pipe through less, the xterm width is set to 80, which ain't so hot. But if you proceed the command with, e.g. COLS=210, you can utilize your expanded xterm.

gitdiff()
{
    local width=${COLS:-$(tput cols)}
    GIT_EXTERNAL_DIFF="diff -yW$width \$2 \$5; echo >/dev/null" git diff "$@"
}

Scanner method to get a char

sc.next().charat(0).........is the method of entering character by user based on the number entered at the run time

example: sc.next().charat(2)------------>>>>>>>>

Function to get yesterday's date in Javascript in format DD/MM/YYYY

The problem here seems to be that you're reassigning $today by assigning a string to it:

$today = $dd+'/'+$mm+'/'+$yyyy;

Strings don't have getDate.

Also, $today.getDate()-1 just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:

$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.

Then just apply the formatting code you wrote:

var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!

var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;

Because of the last statement, $yesterday is now a String (not a Date) containing the formatted date.

DB2 Query to retrieve all table names for a given schema

select name from sysibm.systables 
where name like '%ISP%' 
and type = 'T'

Why is using a wild card with a Java import statement bad?

In a previous project I found that changing from *-imports to specific imports reduced compilation time by half (from about 10 minutes to about 5 minutes). The *-import makes the compiler search each of the packages listed for a class matching the one you used. While this time can be small, it adds up for large projects.

A side affect of the *-import was that developers would copy and paste common import lines rather than think about what they needed.

Can You Get A Users Local LAN IP Address Via JavaScript?

I cleaned up mido's post and then cleaned up the function that they found. This will either return false or an array. When testing remember that you need to collapse the array in the web developer console otherwise it's nonintuitive default behavior may deceive you in to thinking that it is returning an empty array.

function ip_local()
{
 var ip = false;
 window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || false;

 if (window.RTCPeerConnection)
 {
  ip = [];
  var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
  pc.createDataChannel('');
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);

  pc.onicecandidate = function(event)
  {
   if (event && event.candidate && event.candidate.candidate)
   {
    var s = event.candidate.candidate.split('\n');
    ip.push(s[0].split(' ')[4]);
   }
  }
 }

 return ip;
}

Additionally please keep in mind folks that this isn't something old-new like CSS border-radius though one of those bits that is outright not supported by IE11 and older. Always use object detection, test in reasonably older browsers (e.g. Firefox 4, IE9, Opera 12.1) and make sure your newer scripts aren't breaking your newer bits of code. Additionally always detect standards compliant code first so if there is something with say a CSS prefix detect the standard non-prefixed code first and then fall back as in the long term support will eventually be standardized for the rest of it's existence.

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

Use TextAreaFor

@Html.TextAreaFor(model => model.Description, new { @class = "whatever-class", @cols = 80, @rows = 10 })

or use style for multi-line class.

You could also write EditorTemplate for this.

"Cannot instantiate the type..."

You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();.

How to get a complete list of ticker symbols from Yahoo Finance?

I had same problem, but I think I have simple solution(code is from my RoR app): Extract industry ids from yahoo.finance.sectors and add it to db:

    select = "select * from yahoo.finance.sectors"
    generate_query select
    @data.each do |data|
      data["industry"].each do |ind|
        unless ind.kind_of?(Array)
          unless ind["id"].nil?
            id = ind["id"].to_i
            if id > 0
              Industry.where(id: id).first_or_create(name: ind["name"]).update_attribute(:name, ind["name"])
            end
          end
        end
      end
    end

Extract all comanies with their symbols with industry ids:

    ids = Industry.all.map{|ind| "'#{ind.id.to_s}'" }.join(",")
    select = "select * from yahoo.finance.industry where id in"
    generate_query select, ids
    @data.each do |ts|
      unless ts.kind_of?(Array) || ts["company"].nil?
        if ts["company"].count == 2 && ts["company"].first[0] == "name"
          t = ts["company"]
          Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
        else
          ts["company"].each do |t|
            Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
          end
        end
      end
    end
  end

Connection hellper:

def generate_query(select, ids = nil)
    if params[:form] || params[:action] == "sectors" || params[:controller] == "tickets"
      if params[:action] == "sectors" || params[:controller] == "tickets"
        if ids.nil?
          query= select
        else
          query= "#{select} (#{ids})"
        end
      else
        if params[:form][:ids]
          @conditions = params_parse params[:form][:ids]
          query = "#{select} (#{@conditions})"
        end
      end
      yql_execut(query)
    end
  end

  def yql_execut(query)
    # TODO: OAuth ACCESS (http://developer.yahoo.com/yql/guide/authorization.html)
    base_url = "http://query.yahooapis.com/v1/public/yql?&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q="
    dirty_data = JSON.parse(HTTParty.get(base_url +  URI.encode(query)).body)
    if dirty_data["query"]["results"] == nil
      @data, @count, @table_head = nil
    else
      @data = dirty_data["query"]["results"].to_a[0][1].to_a
      @count = dirty_data["query"]["count"]
      if @count == 1
        @table_head = @data.map{|h| h[0].capitalize}
      else
        @table_head = @data.to_a.first.to_a.map{|h| h[0].capitalize}
      end
    end
  end

Sorry for mess, but this is first testing version for my project and I needed it very fast. There are some helpers variabels and other things for my app, sorry for it. But I have question: Have many symbols do you have? I have 5500.

Set Google Chrome as the debugging browser in Visual Studio

  1. Go to the visual studio toolbar and click on the dropdown next to CPU (where it says IIS Express in the screenshot). One of the choices should be "Browse With..."

    Visual Studio Toolbar

  2. Select a browser, e.g. Google Chrome, then click Set as Default

    Browse With...

  3. Click Browse or Cancel.

makefile:4: *** missing separator. Stop

The key point was "HARD TAB" 1. Check whether you used TAB instead of whitespace 2. Check your .vimrc for "set tabstop=X"

How to export data from Excel spreadsheet to Sql Server 2008 table

There are several tools which can import Excel to SQL Server.

I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...

I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.

Proxy setting for R

On Mac OS, I found the best solution here. Quoting the author, two simple steps are:

1) Open Terminal and do the following:

export http_proxy=http://staff-proxy.ul.ie:8080
export HTTP_PROXY=http://staff-proxy.ul.ie:8080

2) Run R and do the following:

Sys.setenv(http_proxy="http://staff-proxy.ul.ie:8080")

double-check this with:

Sys.getenv("http_proxy")

I am behind university proxy, and this solution worked perfectly. The major issue is to export the items in Terminal before running R, both in upper- and lower-case.

Setting up a git remote origin

For anyone who comes here, as I did, looking for the syntax to change origin to a different location you can find that documentation here: https://help.github.com/articles/changing-a-remote-s-url/. Using git remote add to do this will result in "fatal: remote origin already exists."

Nutshell: git remote set-url origin https://github.com/username/repo

(The marked answer is correct, I'm just hoping to help anyone as lost as I was... haha)

Producing a new line in XSLT

I added the DOCTYPE directive you see here:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [
  <!ENTITY nl "&#xa;">
]>
<xsl:stylesheet xmlns:x="http://www.w3.org/2005/02/query-test-XQTSCatalog"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="2.0">

This allows me to use &nl; instead of &#xa; to produce a newline in the output. Like other solutions, this is typically placed inside a <xsl:text> tag.

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

One liner to check if element is in the list

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

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

}

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

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

Excel: last character/string match in a string

Cell A1 = find/the/position/of/the last slash

simple way to do it is reverse the text and then find the first slash as normal. Now you can get the length of the full text minus this number.

Like so:

=LEN(A1)-FIND("/",REVERSETEXT(A1),1)+1

This returns 21, the position of the last /

react hooks useEffect() cleanup for only componentWillUnmount?

you can use more than one useEffect

for example if my variable is data1 i can use all of this in my component

useEffect( () => console.log("mount"), [] );
useEffect( () => console.log("will update data1"), [ data1 ] );
useEffect( () => console.log("will update any") );
useEffect( () => () => console.log("will update data1 or unmount"), [ data1 ] );
useEffect( () => () => console.log("unmount"), [] );

Simple division in Java - is this a bug or a feature?

I find letter identifiers to be more readable and more indicative of parsed type:

1 - 7f / 10
1 - 7 / 10f

or:

1 - 7d / 10
1 - 7 / 10d

Fastest way to convert JavaScript NodeList to Array?

NodeList.prototype.forEach = Array.prototype.forEach;

Now you can do document.querySelectorAll('div').forEach(function()...)

How do I get a class instance of generic type T?

I had this problem in an abstract generic class. In this particular case, the solution is simpler:

abstract class Foo<T> {
    abstract Class<T> getTClass();
    //...
}

and later on the derived class:

class Bar extends Foo<Whatever> {
    @Override
    Class<T> getTClass() {
        return Whatever.class;
    }
}

Combining CSS Pseudo-elements, ":after" the ":last-child"

This works :) (I hope multi-browser, Firefox likes it)

_x000D_
_x000D_
li { display: inline; list-style-type: none; }_x000D_
li:after { content: ", "; }_x000D_
li:last-child:before { content: "and "; }_x000D_
li:last-child:after { content: "."; }
_x000D_
<html>_x000D_
  <body>_x000D_
    <ul>_x000D_
      <li>One</li>_x000D_
      <li>Two</li>_x000D_
      <li>Three</li>_x000D_
    </ul>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do you stash an untracked file?

I thought this could be solved by telling git that the file exists, rather than committing all of the contents of it to the staging area, and then call git stash. Araqnid describes how to do the former.

git add --intent-to-add path/to/untracked-file

or

git update-index --add --cacheinfo 100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 path/to/untracked-file

However, the latter doesn't work:

$ git stash
b.rb: not added yet
fatal: git-write-tree: error building trees
Cannot save the current index state

Combining two expressions (Expression<Func<T, bool>>)

I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:

    public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp) 
    {
        var parameter = Expression.Parameter(sourceType);

        var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
        var left = leftVisitor.Visit(exp.Body);

        var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
        var right = rightVisitor.Visit(newExp.Body);

        var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
        return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
    }

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

Speed comparion (using Wouter's method)

In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))

In [7]: %timeit dict(zip(df.A,df.B))
1000 loops, best of 3: 1.27 ms per loop

In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict()
1000 loops, best of 3: 987 us per loop

Use stored procedure to insert some data into a table

If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.

insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)

There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:

CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int

AS 

If you want to know what the ID of the newly inserted record is add

SELECT @@IDENTITY

to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx

You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.

P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.

how to get selected row value in the KendoUI

There is better way. I'm using it in pages where I'm using kendo angularJS directives and grids has'nt IDs...

change: function (e) {
   var selectedDataItem = e != null ? e.sender.dataItem(e.sender.select()) : null;
}

Closing JFrame with button click

JButton b3 = new JButton("CLOSE");

b3.setBounds(50, 375, 250, 50);

b3.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        System.exit(0);
    }
});

Parsing JSON objects for HTML table

Here is an another way to parse json object into Html table

_x000D_
_x000D_
//EXTRACT VALUE FOR HTML HEADER._x000D_
// ('Book ID', 'Book Name', 'Category' and 'Price')_x000D_
var col = [];_x000D_
_x000D_
for (var i = 0; i < d.length; i++) {_x000D_
  for (var key in d[i]) {_x000D_
if (col.indexOf(key) === -1) {_x000D_
  col.push(key);_x000D_
}_x000D_
  }_x000D_
}_x000D_
_x000D_
// CREATE DYNAMIC TABLE._x000D_
var table = document.createElement("table");_x000D_
_x000D_
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE._x000D_
var tr = table.insertRow(-1);    // TABLE ROW.               _x000D_
                 _x000D_
for (var i = 0; i < col.length; i++) {_x000D_
  var th = document.createElement("th");// TABLE HEADER._x000D_
  th.innerHTML = col[i];_x000D_
  tr.appendChild(th);_x000D_
}_x000D_
_x000D_
// ADD JSON DATA TO THE TABLE AS ROWS._x000D_
for (var i = 0; i < d.length; i++) {_x000D_
  tr = table.insertRow(-1);_x000D_
_x000D_
  for (var j = 0; j < col.length; j++) {_x000D_
var tabCell = tr.insertCell(-1);_x000D_
tabCell.innerHTML = d[i][col[j]];_x000D_
  }_x000D_
}_x000D_
_x000D_
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER._x000D_
var divContainer = document.getElementById("showData");_x000D_
divContainer.innerHTML = "";_x000D_
divContainer.appendChild(table);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

TortoiseSVN icons not showing up under Windows 7

Possible problems and solutions

  1. Limitation of number of usable overlay icons by Windows, refer to Kris Erickson's answer.
  2. Inappropriate setting of TortoiseSVN, refer to Ralph Cowling's answer.
  3. Known bug for updating from earlier version (pre 1.6.10), see here.
  4. TortoiseSVN was not installed for all users, try to install with cmd like below, if all below three solutions don't work, I believe this method will save your life.

rem Set your own path.
set TOOL_ROOT=d:\Tools\TortoiseSVN-1.6.13.20954-win32-svn-1.6.16\tortoisesvn_1.6.16.21511
set PACKAGENAME=TortoiseSVN-1.6.16.21511-x64-svn-1.6.17.msi
set TOOL_INSTALLROOT="c:\Program Files (x86)\TortoiseSVN"

msiexec /i "%TOOL_ROOT%\%PACKAGENAME%" INSTALLDIR=%TOOL_INSTALLROOT% ALLUSERS=1 ARPSYSTEMCOMPONENT=1 RebootYesNo=No REBOOT=ReallySupress /qb-

set ret=%ERRORLEVEL%

rem The installer seems to return same values as MSI
rem These codes mean that the product is properly installed, even though the code is not zero.
rem 1641 ERROR_SUCCESS_REBOOT_INITIATED
rem 3010 ERROR_SUCCESS_REBOOT_REQUIRED
if %ret% EQU 1641 set ret=0
if %ret% EQU 3010 set ret=0
if %ret% GTR 0 exit %ret%

Returning http status code from Web Api controller

Change the GetXxx API method to return HttpResponseMessage and then return a typed version for the full response and the untyped version for the NotModified response.

    public HttpResponseMessage GetComputingDevice(string id)
    {
        ComputingDevice computingDevice =
            _db.Devices.OfType<ComputingDevice>()
                .SingleOrDefault(c => c.AssetId == id);

        if (computingDevice == null)
        {
            return this.Request.CreateResponse(HttpStatusCode.NotFound);
        }

        if (this.Request.ClientHasStaleData(computingDevice.ModifiedDate))
        {
            return this.Request.CreateResponse<ComputingDevice>(
                HttpStatusCode.OK, computingDevice);
        }
        else
        {
            return this.Request.CreateResponse(HttpStatusCode.NotModified);
        }
    }

*The ClientHasStale data is my extension for checking ETag and IfModifiedSince headers.

The MVC framework should still serialize and return your object.

NOTE

I think the generic version is being removed in some future version of the Web API.

What is the difference between Integrated Security = True and Integrated Security = SSPI?

True is only valid if you're using the .NET SqlClient library. It isn't valid when using OLEDB. Where SSPI is bvaid in both either you are using .net SqlClient library or OLEDB.

How to initialize a two-dimensional array in Python?

Usually when you want multidimensional arrays you don't want a list of lists, but rather a numpy array or possibly a dict.

For example, with numpy you would do something like

import numpy
a = numpy.empty((10, 10))
a.fill(foo)

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>

How to handle-escape both single and double quotes in an SQL-Update statement

In C# and VB the SqlCommand object implements the Parameter.AddWithValue method which handles this situation

Change default global installation directory for node.js modules in Windows?

Find the current path of your global node package installation by following command.

npm list -g --depth=0

Change this path to correct path by following command.

npm set prefix C:\Users\username(Number)\AppData\Roaming\npm\node_modules

It worked for me. Read my previous answer for better understanding.

Conditional Count on a field

Using COUNT instead of SUM removes the requirement for an ELSE statement:

SELECT jobId, jobName,
    COUNT(CASE WHEN Priority=1 THEN 1 END) AS Priority1,
    COUNT(CASE WHEN Priority=2 THEN 1 END) AS Priority2,
    COUNT(CASE WHEN Priority=3 THEN 1 END) AS Priority3,
    COUNT(CASE WHEN Priority=4 THEN 1 END) AS Priority4,
    COUNT(CASE WHEN Priority=5 THEN 1 END) AS Priority5
FROM TableName
GROUP BY jobId, jobName

Composer install error - requires ext_curl when it's actually enabled

For anyone who encounters this issue on Windows i couldn't find my answer on google at all. I just tried running composer require ext-curl and this worked. Alternatively add the following in your composer.json file:

"require": {
"ext-curl": "^7.3"
}

Placing/Overlapping(z-index) a view above another view in android

I use this, if you want only one view to be bring to front when needed:

containerView.bringChildToFront(topView);

containerView is container of views to be sorted, topView is view which i want to have as top most in container.

for multiple views to arrange is about to use setChildrenDrawingOrderEnabled(true) and overriding getChildDrawingOrder(int childCount, int i) as mentioned above.

How to get autocomplete in jupyter notebook without using tab?

Without doing this %config IPCompleter.greedy=True after you import a package like numpy or pandas in this way; import numpy as np import pandas as pd.

Then you type in pd. then tap the tab button it brings out all the possible methods to use very easy and straight forward.

How are cookies passed in the HTTP protocol?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).

How to remove leading zeros using C#

Regex rx = new Regex(@"^0+(\d+)$");
rx.Replace("0001234", @"$1"); // => "1234"
rx.Replace("0001234000", @"$1"); // => "1234000"
rx.Replace("000", @"$1"); // => "0" (TrimStart will convert this to "")

// usage
var outString = rx.Replace(inputString, @"$1");

How to implement a FSM - Finite State Machine in Java

Consider the easy, lightweight Java library EasyFlow. From their docs:

With EasyFlow you can:

  • implement complex logic but keep your code simple and clean
  • handle asynchronous calls with ease and elegance
  • avoid concurrency by using event-driven programming approach
  • avoid StackOverflow error by avoiding recursion
  • simplify design, programming and testing of complex java applications

Lightweight Javascript DB for use in Node.js

I wrote jaguarDb to handle some of the things that you are mentioning since I sometimes need a "little" database for demo or test projects too and I don't want to depend on mongoDB or another real database.

https://github.com/hectorcorrea/jaguarDb

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

Image Greyscale with CSS & re-color on mouse-over?

There are numerous methods of accomplishing this, which I'll detail with a few examples below.

Pure CSS (using only one colored image)

img.grayscale {
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
  filter: gray; /* IE6-9 */
  -webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
}

img.grayscale:hover {
  filter: none;
  -webkit-filter: grayscale(0%);
}

_x000D_
_x000D_
img.grayscale {_x000D_
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");_x000D_
  /* Firefox 3.5+, IE10 */_x000D_
  filter: gray;_x000D_
  /* IE6-9 */_x000D_
  -webkit-filter: grayscale(100%);_x000D_
  /* Chrome 19+ & Safari 6+ */_x000D_
  -webkit-transition: all .6s ease;_x000D_
  /* Fade to color for Chrome and Safari */_x000D_
  -webkit-backface-visibility: hidden;_x000D_
  /* Fix for transition flickering */_x000D_
}_x000D_
_x000D_
img.grayscale:hover {_x000D_
  filter: none;_x000D_
  -webkit-filter: grayscale(0%);_x000D_
}_x000D_
_x000D_
svg {_x000D_
  background: url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);_x000D_
}_x000D_
_x000D_
svg image {_x000D_
  transition: all .6s ease;_x000D_
}_x000D_
_x000D_
svg image:hover {_x000D_
  opacity: 0;_x000D_
}
_x000D_
<p>Firefox, Chrome, Safari, IE6-9</p>_x000D_
<img class="grayscale" src="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" width="400">_x000D_
<p>IE10 with inline SVG</p>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 400 377" width="400" height="377">_x000D_
  <defs>_x000D_
     <filter id="filtersPicture">_x000D_
       <feComposite result="inputTo_38" in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />_x000D_
       <feColorMatrix id="filter_38" type="saturate" values="0" data-filterid="38" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image filter="url(&quot;#filtersPicture&quot;)" x="0" y="0" width="400" height="377" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" />_x000D_
   </svg>
_x000D_
_x000D_
_x000D_

You can find an article related to this technique here.

Pure CSS (using a grayscale and colored images)

This approach requires two copies of an image: one in grayscale and the other in full color. Using the CSS :hover psuedoselector, you can update the background of your element to toggle between the two:

#yourimage { 
    background: url(../grayscale-image.png);
}
#yourImage:hover { 
    background: url(../color-image.png};
}

_x000D_
_x000D_
#google {_x000D_
  background: url('http://www.google.com/logos/keystroke10-hp.png');_x000D_
  height: 95px;_x000D_
  width: 275px;_x000D_
  display: block;_x000D_
  /* Optional for a gradual animation effect */_x000D_
  transition: 0.5s;_x000D_
}_x000D_
_x000D_
#google:hover {_x000D_
  background: url('https://graphics217b.files.wordpress.com/2011/02/logo1w.png');_x000D_
}
_x000D_
<a id='google' href='http://www.google.com'></a>
_x000D_
_x000D_
_x000D_

This could also be accomplished by using a Javascript-based hover effect such as jQuery's hover() function in the same manner.

Consider a Third-Party Library

The desaturate library is a common library that allows you to easily switch between a grayscale version and full-colored version of a given element or image.

Cannot connect to SQL Server named instance from another SQL Server

well after spending about 10 days trying to solve this issue, i finally figured it out today and decide to post the solution

in the start menu, type RUN, open it the in the run box, type SERVICES.MSC, click okay

ensure that these two services are started SQL Server(MSSQLSERVER) SQL Server Vss writer

JPA: unidirectional many-to-one and cascading delete

Relationships in JPA are always unidirectional, unless you associate the parent with the child in both directions. Cascading REMOVE operations from the parent to the child will require a relation from the parent to the child (not just the opposite).

You'll therefore need to do this:

  • Either, change the unidirectional @ManyToOne relationship to a bi-directional @ManyToOne, or a unidirectional @OneToMany. You can then cascade REMOVE operations so that EntityManager.remove will remove the parent and the children. You can also specify orphanRemoval as true, to delete any orphaned children when the child entity in the parent collection is set to null, i.e. remove the child when it is not present in any parent's collection.
  • Or, specify the foreign key constraint in the child table as ON DELETE CASCADE. You'll need to invoke EntityManager.clear() after calling EntityManager.remove(parent) as the persistence context needs to be refreshed - the child entities are not supposed to exist in the persistence context after they've been deleted in the database.

IndentationError: unexpected unindent WHY?

you didn't complete your try statement. You need and except in there too.

How do I install command line MySQL client on mac?

For installing mysql-shell with homebrew, run

brew cask install mysql-shell

you can then launch the mysql shell with

mysqlsh

if you want to enter SQL mode directly, run

mysqlsh --sql

Get the year from specified date php

I would use this:

$parts = explode('-', '2068-06-15');
echo $parts[0];

It appears the date is coming from a source where it is always the same, much quicker this way using explode.

Pass Additional ViewData to a Strongly-Typed Partial View

This should also work.

this.ViewData.Add("index", index);

Html.RenderPartial(
      "ProductImageForm", 
       image, 
       this.ViewData
); 

CSS values using HTML5 data attribute

There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation

This fiddle should work like what you need, but will not for now.

Unfortunately, it's still a draft, and isn't fully implemented on major browsers.

It does work for content on pseudo-elements, though.

Are HTTP cookies port specific?

An alternative way to go around the problem, is to make the name of the session cookie be port related. For example:

  • mysession8080 for the server running on port 8080
  • mysession8000 for the server running on port 8000

Your code could access the webserver configuration to find out which port your server uses, and name the cookie accordingly.

Keep in mind that your application will receive both cookies, and you need to request the one that corresponds to your port.

There is no need to have the exact port number in the cookie name, but this is more convenient.

In general, the cookie name could encode any other parameter specific to the server instance you use, so it can be decoded by the right context.

Creating a timer in python

See Timer Objects from threading.

How about

from threading import Timer

def timeout():
    print("Game over")

# duration is in seconds
t = Timer(20 * 60, timeout)
t.start()

# wait for time completion
t.join()

Should you want pass arguments to the timeout function, you can give them in the timer constructor:

def timeout(foo, bar=None):
    print('The arguments were: foo: {}, bar: {}'.format(foo, bar))

t = Timer(20 * 60, timeout, args=['something'], kwargs={'bar': 'else'})

Or you can use functools.partial to create a bound function, or you can pass in an instance-bound method.

Creating a custom JButton in Java

When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.

Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.

alt text
alt text
alt text

Here are the basic steps:

  1. Create a class that extends JComponent
  2. Call parent constructor super() in your constructors
  3. Make sure you class implements MouseListener
  4. Put this in the constructor:

    enableInputMethods(true);   
    addMouseListener(this);
    
  5. Override these methods:

    public Dimension getPreferredSize()  
    public Dimension getMinimumSize()  
    public Dimension getMaximumSize()
    
  6. Override this method:

    public void paintComponent(Graphics g)
    

The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.

And finally, the source code. In case I missed anything.

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

Binding value to input in Angular JS

{{widget.title}} Try this it will work

Difference between try-catch and throw in java

try - Add sensitive code catch - to handle exception finally - always executed whether exception caught or not. Associated with try -catch. Used to close the resource which we opened in try block throw - To handover our created exception to JVM manually. Used to throw customized exception throws - To delegate the responsibility of exception handling to caller method or main method.

A better way to check if a path exists or not in PowerShell

Add the following aliases. I think these should be made available in PowerShell by default:

function not-exist { -not (Test-Path $args) }
Set-Alias !exist not-exist -Option "Constant, AllScope"
Set-Alias exist Test-Path -Option "Constant, AllScope"

With that, the conditional statements will change to:

if (exist $path) { ... }

and

if (not-exist $path) { ... }
if (!exist $path) { ... }

Write / add data in JSON file using Node.js

For synchronous approach

const fs = require('fs')
fs.writeFileSync('file.json', JSON.stringify(jsonVariable));

What is the difference between IQueryable<T> and IEnumerable<T>?

ienumerable:when we want to deal with inprocess memory, i.e without dataconnection iqueryable:when to deal with sql server, i.e with data connection ilist : operations like add object, delete object etc

How to make Bootstrap 4 cards the same height in card-columns?

jsfiddle

Just add the height you want with CSS, example:

.card{
    height: 350px;
}

You will have to add your own CSS.

If you check the documentation, this is for Masonry style - the point of that is they are not all the same height.

Case Statement Equivalent in R

You can use recode from the car package:

library(ggplot2) #get data
library(car)
daimons$new_var <- recode(diamonds$clarity , "'I1' = 'low';'SI2' = 'low';else = 'high';")[1:10]

How to get thread id from a thread pool?

If your class inherits from Thread, you can use methods getName and setName to name each thread. Otherwise you could just add a name field to MyTask, and initialize it in your constructor.

Import error No module named skimage

Hey this is pretty simple to solve this error.Just follow this steps:

First uninstall any existing installation:

pip uninstall scikit-image

or, on conda-based systems:

conda uninstall scikit-image

Now, clone scikit-image on your local computer, and install:

git clone https://github.com/scikit-image/scikit-image.git
cd scikit-image
pip install -e .

To update the installation:

git pull  # Grab latest source
pip install -e .  # Reinstall

For other os and manual process please check this Link.

Service will not start: error 1067: the process terminated unexpectedly

This is a problem related permission. Make sure that the current user has access to the folder which contains installation files.

Nginx no-www to www and www to no-www

location / { 
    if ($http_host !~ "^www.domain.com"){ 
        rewrite ^(.*)$ $scheme://www.domain.com/$1 redirect; 
    } 
}

Get only part of an Array in Java?

You can use subList(int fromIndex, int toIndex) method on your integers arr, something like this:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        List<Integer> partialArr = arr.subList(1, 3);

        // print the subArr
        for (Integer i: partialArr)
            System.out.println(i + " ");
    }
}

Output will be: 2 3.

Note that subList(int fromIndex, int toIndex) method performs minus 1 on the 2nd variable it receives (var2 - 1), i don't know exactly why, but that's what happens, maybe to reduce the chance of exceeding the size of the array.

How to list only top level directories in Python?

directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]

Map HTML to JSON

I had a similar issue where I wanted to represent HTML as JSON in the following way:

  • For HTML text nodes, use a string
  • For HTML elements, use an array with:
    • The (tag) name of the element
    • An object, mapping attribute keys to attribute values
    • The (inlined) list of children nodes

Example:

<div>
  <span>text</span>Text2
</div>

becomes

[
   'div',
   {},
   ['span', {}, 'text'],
   'Text2'
]

I wrote a function which handles transforming a DOM Element into this kind of JS structure. You can find this function at the end of this answer. The function is written in Typescript. You can use the Typescript playground to convert it to clean JavaScript.


Furthermore, if you need to parse an html string into DOM, assign to .innerHtml:

let element = document.createElement('div')
element.innerHtml = htmlString

Also, this one is common knowledge but if you need a JSON string output, use JSON.stringify.


/**
 * A NodeDescriptor stands for either an (HTML) Element, or for a text node
 */
export type NodeDescriptor = ElementDescriptor | string

/**
 * Array representing an HTML Element. It consists of:
 *
 * - The (tag) name of the element
 * - An object, mapping attribute keys to attribute values
 * - The (inlined) list of children nodes
 */
export type ElementDescriptor = [
   string,
   Record<string, string>,
   ...NodeDescriptor[]
]

export let htmlToJs = (element: Element, trim = true): ElementDescriptor => {
   let convertElement = (element: Element): ElementDescriptor => {
      let attributeObject: Record<string, string> = {}
      for (let { name, value } of element.attributes) {
         attributeObject[name] = value
      }

      let childArray: NodeDescriptor[] = []
      for (let node of element.childNodes) {
         let converter = htmlToJsDispatch[node.nodeType]
         if (converter) {
            let descriptor = converter(node as any)
            let skip = false

            if (trim && typeof descriptor === 'string') {
               descriptor = descriptor.trim()
               if (descriptor === '') skip = true
            }

            if (!skip) childArray.push(descriptor)
         }
      }

      return [element.tagName.toLowerCase(), attributeObject, ...childArray]
   }

   let htmlToJsDispatch = {
      [element.ELEMENT_NODE]: convertElement,
      [element.TEXT_NODE]: (node: Text): string => node.data,
   }

   return convertElement(element)
}

How can I check that JButton is pressed? If the isEnable() is not work?

The method you are trying to use checks if the button is active:

btnAdd.isEnabled()

When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.

This method does not check if the button is pressed.

If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".

Try disabling your button at start: btnAdd.setEnabled(false) or after the user presses "Check out"

How do I write output in same place on the console?

Python 2

I like the following:

print 'Downloading File FooFile.txt [%d%%]\r'%i,

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print 'Downloading File FooFile.txt [%d%%]\r'%i,

Python 3

print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

PyCharm Debugger Console with Python 3

# On PyCharm Debugger console, \r needs to come before the text.
# Otherwise, the text may not appear at all, or appear inconsistently.
# tested on PyCharm 2019.3, Python 3.6

import time

print('Start.')
for i in range(100):
    time.sleep(0.02)
    print('\rDownloading File FooFile.txt [%d%%]'%i, end="")
print('\nDone.')

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

For a Node.js app, in the server.js file before registering all of my own routes, I put the code below. It sets the headers for all responses. It also ends the response gracefully if it is a pre-flight "OPTIONS" call and immediately sends the pre-flight response back to the client without "nexting" (is that a word?) down through the actual business logic routes. Here is my server.js file. Relevant sections highlighted for Stackoverflow use.

// server.js

// ==================
// BASE SETUP

// import the packages we need
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
var jwt        = require('jsonwebtoken'); // used to create, sign, and verify tokens

// ====================================================
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Logger
app.use(morgan('dev'));

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

//Set CORS header and intercept "OPTIONS" preflight call from AngularJS
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    if (req.method === "OPTIONS") 
        res.send(200);
    else 
        next();
}

// -------------------------------------------------------------
// STACKOVERFLOW -- END OF THIS SECTION, ONE MORE SECTION BELOW
// -------------------------------------------------------------


// =================================================
// ROUTES FOR OUR API

var route1 = require("./routes/route1");
var route2 = require("./routes/route2");
var error404 = require("./routes/error404");


// ======================================================
// REGISTER OUR ROUTES with app

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

app.use(allowCrossDomain);

// -------------------------------------------------------------
//  STACKOVERFLOW -- OK THAT IS THE LAST THING.
// -------------------------------------------------------------

app.use("/api/v1/route1/", route1);
app.use("/api/v1/route2/", route2);
app.use('/', error404);

// =================
// START THE SERVER

var port = process.env.PORT || 8080;        // set our port
app.listen(port);
console.log('API Active on port ' + port);

How to set the Default Page in ASP.NET?

I had done all the above solutions but it did not work.

My default page wasn't an aspx page, it was an html page.

This article solved the problem. https://weblog.west-wind.com/posts/2013/aug/15/iis-default-documents-vs-aspnet-mvc-routes

Basically, in my \App_Start\RouteConfig.cs file, I had to add a line:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("");   // This was the line I had to add here!

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Hope this helps someone, it took me a goodly while to find the answer.

Cannot find java. Please use the --jdkhome switch

If like me, you got that message after installing jenv, simply add netbeans_jdkhome="$JAVA_HOME" to your [netbeans-installation-directory]/etc/netbeans.conf file

IE8 support for CSS Media Query

Taken from the css3mediaqueries.js project page.

Note: Doesn't work on @import'ed stylesheets (which you shouldn't use anyway for performance reasons). Also won't listen to the media attribute of the <link> and <style> elements.

Setting a property with an EventTrigger

As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.

How to check if Location Services are enabled?

To check for network provider you just need to change the string passed to isProviderEnabled to LocationManager.NETWORK_PROVIDER if you check the return values for both GPS provider and NETwork provider - both false means no location services

How do I get the path of the Python script I am running in?

If you have even the relative pathname (in this case it appears to be ./) you can open files relative to your script file(s). I use Perl, but the same general solution can apply: I split the directory into an array of folders, then pop off the last element (the script), then push (or for you, append) on whatever I want, and then join them together again, and BAM! I have a working pathname that points to exactly where I expect it to point, relative or absolute.

Of course, there are better solutions, as posted. I just kind of like mine.

ActionBarActivity is deprecated

Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity.

Read here and here for more information.

What is the difference between an int and an Integer in Java and C#?

In platforms like Java, ints are primitives while Integer is an object which holds a integer field. The important distinction is that primitives are always passed around by value and by definition are immutable.

Any operation involving a primitive variable always returns a new value. On the other hand, objects are passed around by reference. One could argue that the point to the object (AKA the reference) is also being passed around by value, but the contents are not.

How to style a clicked button in CSS

button:hover is just when you move the cursor over the button.
Try button:active instead...will work for other elements as well

_x000D_
_x000D_
button:active{_x000D_
  color: red;_x000D_
}
_x000D_
_x000D_
_x000D_

Convert digits into words with JavaScript

 var units = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];



function convert7digitIntoWords(num) {
    var remainder = num % 1000000
    var hun = num - remainder;
    var div = Math.floor(num / 100000);
    if (remainder !== 0)
        return (convert2digitIntoWords(div) + " lakhs " + convert5digitIntoWords(remainder % 100000))
    else
        return (convert2digitIntoWords(div) + " lakhs ")
}

function convert6digitIntoWords(num) {
    var remainder = num % 100000
    var hun = num - remainder;
    var div = Math.floor(num / 100000);
    if (remainder !== 0)
        return (units[div] + " lakh " + convert5digitIntoWords(remainder))
    else
        return (units[div] + " lakh ")
}

function convert5digitIntoWords(num) {
    var remainder = num % 10000
    var hun = num - remainder;
    var div = Math.floor(num / 1000);
    if (remainder !== 0)
        return (convert2digitIntoWords(div) + " thousand " + convert3digitIntoWords(remainder % 1000))
    else
        return (convert2digitIntoWords(div) + " thousand")
}

function convert4digitIntoWords(num) {
    var remainder = num % 1000
    var hun = num - remainder;
    var div = Math.floor(num / 1000);
    if (remainder !== 0)
        return (units[div] + " thousand " + convert3digitIntoWords(remainder))
    else
        return (units[div] + " thousand")
}


function convert3digitIntoWords(num) {
    var remainder = num % 100
    var hun = num - remainder;
    var div = Math.floor(num / 100);
    if (remainder !== 0)
        return (units[div] + " hundred " + convert2digitIntoWords(remainder))
    else
        return (units[div] + " hundred ")
}

function convert2digitIntoWords(num) {
    var remainder = num % 10;
    var div = Math.floor(num / 10);
    return (tens[div] + " " + convertNumIntoWords(remainder));
}

function convertNumIntoWords(num) {

    switch (("" + num).length) {
        case 1:
            return units[num];
        case 2:
            return convert2digitIntoWords(num);
        case 3:
            return convert3digitIntoWords(num)
        case 4:
            return convert4digitIntoWords(num)
        case 5:
            return convert5digitIntoWords(num)
        case 6:
            return convert6digitIntoWords(num)
        case 7:
            return convert7digitIntoWords(num)
        default:
            return "cannot be converted"
    }
}

console.log(convertNumIntoWords(3445125));

Excel concatenation quotes

I was Forming some Programming Logic Used CHAR(34) for Quotes at Excel : A small Part of same I am posting which can be helpfull ,Hopefully

1   Customers
2   Invoices

Formula Used :

=CONCATENATE("listEvents.Add(",D4,",",CHAR(34),E4,CHAR(34),");")

Result :

listEvents.Add(1,"Customers");
listEvents.Add(2,"Invoices");

Java Refuses to Start - Could not reserve enough space for object heap

You're using a 32-bit OS, so you're going to be seeing limits on the total size due to that. Other answers have covered this in more detail, so I'll avoid repeating their information.

A behaviour that I noticed with our servers recently is that specifying a maximum heap size with -Xmx while not specifying a minimum heap size with -Xms would lead to Java's server VM immediately attempting to allocate all of the memory needed for the maximum heap size. And sure, if the app gets up to that heap size, that's the amount of memory that you'll need. But the chances are, your apps will be starting out with comparitively small heaps and may require the larger heap at some later point. Additionally specifying the minimum heap size will let you start your app start with a smaller heap and gradually grow that heap.

All of this isn't going to help you increase your maximum heap size, but I figured it might help, so...

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

Similar error as well. Realized I had an .htpasswd setup for the particular host. Uncommented it from the .htaccess file and worked fine.

Amazon S3 - HTTPS/SSL - Is it possible?

payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:

https://s3-<region>.amazonaws.com/your.domain.com/some/asset

Where <region> is the bucket location name. For example, if your bucket is in the us-west-2 (Oregon) region, you can do this:

https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset

How to set a cron job to run every 3 hours

Change Minute to be 0. That's it :)

Note: you can check your "crons" in http://cronchecker.net/

Example

How to run an external program, e.g. notepad, using hyperlink?

Sorry this answer sucks, but you can't launch an just any external application via a click, as this would be a serious security issue, this functionality isn't available in HTML or javascript. Think of just launching cmd.exe with args...you want to launch WinMerge with arguments, but you can see the security problems introduced by allowing this for anything.

The only possibly viable exception I can think of would be a protocol handler (since these are explicitly defined handlers), like winmerge://, though the best way to pass 2 file parameters I'm not sure of, if it's an option it's worth looking into, but I'm not sure what you are or are not allowed to do to the client, so this may be a non-starter solution.

Force Java timezone as GMT/UTC

Also if you can set JVM timezone this way

System.setProperty("user.timezone", "EST");

or -Duser.timezone=GMT in the JVM args.

Setting paper size in FPDF

They say it right there in the documentation for the FPDF constructor:

FPDF([string orientation [, string unit [, mixed size]]])

This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...

size

The size used for pages. It can be either one of the following values (case insensitive):

A3 A4 A5 Letter Legal

or an array containing the width and the height (expressed in the unit given by unit).

They even give an example with custom size:

Example with a custom 100x150 mm page size:

$pdf = new FPDF('P','mm',array(100,150));

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Actually your Windows firewall is blocking the connection. You need to enter these commands into cmd.exe from Administrator.

netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=tcp
netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=udp

In case something goes wrong then you can revert by this:

netsh advfirewall firewall delete rule name="FTP" program=%SystemRoot%\System32\ftp.exe

How to read a text file in project's root directory?

In this code you access to root directory project:

 string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

then:

StreamReader r = new StreamReader(_filePath + "/cities2.json"))

What's the difference between HEAD^ and HEAD~ in Git?

TLDR

~ is what you want most of the time, it references past commits to the current branch

^ references parents (git-merge creates a 2nd parent or more)

A~ is always the same as A^
A~~ is always the same as A^^, and so on
A~2 is not the same as A^2 however,
because ~2 is shorthand for ~~
while ^2 is not shorthand for anything, it means the 2nd parent

How do you remove a specific revision in the git history?

I also landed in a similar situation. Use interactive rebase using the command below and while selecting, drop 3rd commit.

git rebase -i remote/branch

How do I convert an interval into a number of hours with postgres?

If you want integer i.e. number of days:

SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int

ASP MVC href to a controller/view

Try the following:

<a asp-controller="Users" asp-action="Index"></a>

(Valid for ASP.NET 5 and MVC 6)

fs: how do I locate a parent folder?

i'm running electron app and i can get the parent folder by path.resolve()

parent 1 level:path.resolve(__dirname, '..') + '/'

parent 2 levels:path.resolve(__dirname, '..', '..') + '/'

How to select the Date Picker In Selenium WebDriver

From Java 8 you can use this simple method for picking a random date from the date picker

List<WebElement> datePickerDays = driver.findElements(By.tagName("td"));
datePickerDays.stream().filter(e->e.getText().equals(whichDateYouWantToClick)).findFirst().get().click();

Android Preventing Double Click On A Button

My solution (Kotlin):

class OnDebouncedClickListener(private val delayInMilliSeconds: Long, val action: () -> Unit) : View.OnClickListener {
    var enable = true

    override fun onClick(view: View?) {
        if (enable) {
            enable = false
            view?.postDelayed(delayInMilliSeconds) { enable = true }
            action()
        }
    }
}

fun View.setOnDebouncedClickListener(delayInMilliSeconds: Long = 500, action: () -> Unit) {
    val onDebouncedClickListener = OnDebouncedClickListener(delayInMilliSeconds, action)
    setOnClickListener(onDebouncedClickListener)
}

Use :

button.apply {       
            setOnDebouncedClickListener {
                //your action on click
            }
        }

How to use in jQuery :not and hasClass() to get a specific element without a class

I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.

 $(this).siblings(':not(.closedTab)');

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

try grant privileges again.

GRANT ALL PRIVILEGES ON the_database.* TO 'the_user'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;

How do I add a new sourceset to Gradle?

If you're using

To get IntelliJ to recognize custom sourceset as test sources root:

plugin {
    idea
}

idea {
    module {
        testSourceDirs = testSourceDirs + sourceSets["intTest"].allJava.srcDirs
        testResourceDirs = testResourceDirs + sourceSets["intTest"].resources.srcDirs
    }
}

What is the difference between Serializable and Externalizable in Java?

To add to the other answers, by implementating java.io.Serializable, you get "automatic" serialization capability for objects of your class. No need to implement any other logic, it'll just work. The Java runtime will use reflection to figure out how to marshal and unmarshal your objects.

In earlier version of Java, reflection was very slow, and so serializaing large object graphs (e.g. in client-server RMI applications) was a bit of a performance problem. To handle this situation, the java.io.Externalizable interface was provided, which is like java.io.Serializable but with custom-written mechanisms to perform the marshalling and unmarshalling functions (you need to implement readExternal and writeExternal methods on your class). This gives you the means to get around the reflection performance bottleneck.

In recent versions of Java (1.3 onwards, certainly) the performance of reflection is vastly better than it used to be, and so this is much less of a problem. I suspect you'd be hard-pressed to get a meaningful benefit from Externalizable with a modern JVM.

Also, the built-in Java serialization mechanism isn't the only one, you can get third-party replacements, such as JBoss Serialization, which is considerably quicker, and is a drop-in replacement for the default.

A big downside of Externalizable is that you have to maintain this logic yourself - if you add, remove or change a field in your class, you have to change your writeExternal/readExternal methods to account for it.

In summary, Externalizable is a relic of the Java 1.1 days. There's really no need for it any more.

Best practice to look up Java Enum

We do all our enums like this when it comes to Rest/Json etc. It has the advantage that the error is human readable and also gives you the accepted value list. We are using a custom method MyEnum.fromString instead of MyEnum.valueOf, hope it helps.

public enum MyEnum {

    A, B, C, D;

    private static final Map<String, MyEnum> NAME_MAP = Stream.of(values())
            .collect(Collectors.toMap(MyEnum::toString, Function.identity()));

    public static MyEnum fromString(final String name) {
        MyEnum myEnum = NAME_MAP.get(name);
        if (null == myEnum) {
            throw new IllegalArgumentException(String.format("'%s' has no corresponding value. Accepted values: %s", name, Arrays.asList(values())));
        }
        return myEnum;
    }
}

so for example if you call

MyEnum value = MyEnum.fromString("X");

you'll get an IllegalArgumentException with the following message:

'X' has no corresponding value. Accepted values: [A, B, C, D]

you can change the IllegalArgumentException to a custom one.

In Java how does one turn a String into a char or a char into a String?

String someString = "" + c;
char c = someString.charAt(0);

Why not inherit from List<T>?

Design > Implementation

What methods and properties you expose is a design decision. What base class you inherit from is an implementation detail. I feel it's worth taking a step back to the former.

An object is a collection of data and behaviour.

So your first questions should be:

  • What data does this object comprise in the model I'm creating?
  • What behaviour does this object exhibit in that model?
  • How might this change in future?

Bear in mind that inheritance implies an "isa" (is a) relationship, whereas composition implies a "has a" (hasa) relationship. Choose the right one for your situation in your view, bearing in mind where things might go as your application evolves.

Consider thinking in interfaces before you think in concrete types, as some people find it easier to put their brain in "design mode" that way.

This isn't something everyone does consciously at this level in day to day coding. But if you're mulling this sort of topic, you're treading in design waters. Being aware of it can be liberating.

Consider Design Specifics

Take a look at List<T> and IList<T> on MSDN or Visual Studio. See what methods and properties they expose. Do these methods all look like something someone would want to do to a FootballTeam in your view?

Does footballTeam.Reverse() make sense to you? Does footballTeam.ConvertAll<TOutput>() look like something you want?

This isn't a trick question; the answer might genuinely be "yes". If you implement/inherit List<Player> or IList<Player>, you're stuck with them; if that's ideal for your model, do it.

If you decide yes, that makes sense, and you want your object to be treatable as a collection/list of players (behaviour), and you therefore want to implement ICollection or IList, by all means do so. Notionally:

class FootballTeam : ... ICollection<Player>
{
    ...
}

If you want your object to contain a collection/list of players (data), and you therefore want the collection or list to be a property or member, by all means do so. Notionally:

class FootballTeam ...
{
    public ICollection<Player> Players { get { ... } }
}

You might feel that you want people to be able to only enumerate the set of players, rather than count them, add to them or remove them. IEnumerable<Player> is a perfectly valid option to consider.

You might feel that none of these interfaces are useful in your model at all. This is less likely (IEnumerable<T> is useful in many situations) but it's still possible.

Anyone who attempts to tell you that one of these it is categorically and definitively wrong in every case is misguided. Anyone who attempts to tell you it is categorically and definitively right in every case is misguided.

Move on to Implementation

Once you've decided on data and behaviour, you can make a decision about implementation. This includes which concrete classes you depend on via inheritance or composition.

This may not be a big step, and people often conflate design and implementation since it's quite possible to run through it all in your head in a second or two and start typing away.

A Thought Experiment

An artificial example: as others have mentioned, a team is not always "just" a collection of players. Do you maintain a collection of match scores for the team? Is the team interchangable with the club, in your model? If so, and if your team isa collection of players, perhaps it also isa collection of staff and/or a collection of scores. Then you end up with:

class FootballTeam : ... ICollection<Player>, 
                         ICollection<StaffMember>,
                         ICollection<Score>
{
    ....
}

Design notwithstanding, at this point in C# you won't be able to implement all of these by inheriting from List<T> anyway, since C# "only" supports single inheritance. (If you've tried this malarky in C++, you may consider this a Good Thing.) Implementing one collection via inheritance and one via composition is likely to feel dirty. And properties such as Count become confusing to users unless you implement ILIst<Player>.Count and IList<StaffMember>.Count etc. explicitly, and then they're just painful rather than confusing. You can see where this is going; gut feeling whilst thinking down this avenue may well tell you it feels wrong to head in this direction (and rightly or wrongly, your colleagues might also if you implemented it this way!)

The Short Answer (Too Late)

The guideline about not inheriting from collection classes isn't C# specific, you'll find it in many programming languages. It is received wisdom not a law. One reason is that in practice composition is considered to often win out over inheritance in terms of comprehensibility, implementability and maintainability. It's more common with real world / domain objects to find useful and consistent "hasa" relationships than useful and consistent "isa" relationships unless you're deep in the abstract, most especially as time passes and the precise data and behaviour of objects in code changes. This shouldn't cause you to always rule out inheriting from collection classes; but it may be suggestive.

Convert string to Time

string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);

string t = date.ToString("HH:mm:ss tt");

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

How to add scroll bar to the Relative Layout?

Check the following sample layout file

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@color/white">
<RelativeLayout android:layout_height="fill_parent"
    android:layout_width="fill_parent">
    <ImageView android:id="@+id/image1"
        android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"
        android:layout_marginLeft="15dip" android:layout_marginTop="15dip"
        android:src="@drawable/btn_blank" android:clickable="true" /> </RelativeLayout> </ScrollView>

py2exe - generate single executable file

PyInstaller will create a single .exe file with no dependencies; use the --onefile option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see minty's answer)

I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It's been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more.

How to initialize an array of custom objects

Maybe you mean like this? I like to make an object and use Format-Table:

> $array = @()
> $object = New-Object -TypeName PSObject
> $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value 'Joe'
> $object | Add-Member -Name 'Age' -MemberType Noteproperty -Value 32
> $object | Add-Member -Name 'Info' -MemberType Noteproperty -Value 'something about him'
> $array += $object
> $array | Format-Table

Name                                                                        Age Info
----                                                                        --- ----
Joe                                                                          32  something about him

This will put all objects you have in the array in columns according to their properties.

Tip: Using -auto sizes the table better

> $array | Format-Table -Auto

Name Age Info
---- --- ----
Joe   32 something about him

You can also specify which properties you want in the table. Just separate each property name with a comma:

> $array | Format-Table Name, Age -Auto

Name Age
---- ---
Joe   32

How to create a JPA query with LEFT OUTER JOIN

If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:

select a, (select b from B b where b.joinProperty = a.joinProperty) from A a

This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

The docs give a fair indicator of what's required., however requests allow us to skip a few steps:

You only need to install the security package extras (thanks @admdrew for pointing it out)

$ pip install requests[security]

or, install them directly:

$ pip install pyopenssl ndg-httpsclient pyasn1

Requests will then automatically inject pyopenssl into urllib3


If you're on ubuntu, you may run into trouble installing pyopenssl, you'll need these dependencies:

$ apt-get install libffi-dev libssl-dev

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :

  1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols
  2. Cross Origin Resource Sharing with Credentials

Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.

Change URL parameters

Ben Alman has a good jquery querystring/url plugin here that allows you to manipulate the querystring easily.

As requested -

Goto his test page here

In firebug enter the following into the console

jQuery.param.querystring(window.location.href, 'a=3&newValue=100');

It will return you the following amended url string

http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3

Notice the a querystring value for a has changed from X to 3 and it has added the new value.

You can then use the new url string however you wish e.g using document.location = newUrl or change an anchor link etc

How to resolve the error on 'react-native start'

I had the same problem I altered the E:\NodeJS\ReactNativeApp\ExpoTest\node_modules\metro-config\src\defaults\blacklist.js in my project

from

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
 /heapCapture\/bundle\.js/,
 /.*\/__tests__\/.*/
];

to

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

this worked perfectly for me

Create a batch file to run an .exe with an additional parameter

Found another solution for the same. It will be more helpful.

START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"

finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".

$apply already in progress error

If scope must be applied in some cases, then you can set a timeout so that the $apply is deferred until the next tick

setTimeout(function(){ scope.$apply(); });

or wrap your code in a $timeout(function(){ .. }); because it will automatically $apply the scope at the end of execution. If you need your function to behave synchronously, I'd do the first.

DateTimePicker: pick both date and time

Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP.

To use the DateTimePicker for times, set the Format property to either Time or Custom (Use Custom if you want to control the format of the time using the CustomFormat property). Then set the ShowUpDown property to true.

Although a user may set the date and time together manually, they cannot use the GUI to set both.

Bootstrap get div to align in the center

When I align elements in center I use the bootstrap class text-center:

<div class="text-center">Centered content goes here</div>

align divs to the bottom of their container

The way I solved this was using flexbox. By using flexbox to layout the contents of your container div, you can have flexbox automatically distribute free space to an item above the one you want to have "stick to the bottom".

For example, say this is your container div with some other block elements inside it, and that the blue box (third one down) is a paragraph and the purple box (last one) is the one you want to have "stick to the bottom".

enter image description here

By setting this layout up with flexbox, you can set flex-grow: 1; on just the paragraph (blue box) and, if it is the only thing with flex-grow: 1;, it will be allocated ALL of the remaining space, pushing the element(s) after it to the bottom of the container like this:

enter image description here

(apologies for the terrible, quick-and-dirty graphics)

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

how to remove key+value from hash in javascript

You're looking for delete:

delete myhash['key2']

See the Core Javascript Guide

Password Protect a SQLite DB. Is it possible?

You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.

Quoting SQLite documentation:

The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.

You can find more info about this addon in this link.

How do I replace whitespaces with underscore?

Surprisingly this library not mentioned yet

python package named python-slugify, which does a pretty good job of slugifying:

pip install python-slugify

Works like this:

from slugify import slugify

txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")

txt = 'Nín hao. Wo shì zhong guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")

txt = '?????????'
r = slugify(txt)
self.assertEquals(r, "kompiuter")

txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a") 

Removing highcharts.com credits link

It's said here that you should be able to add the following to your chart config:

  credits: {
    enabled: false
  },

that will remove the "Highcharts.com" text from the bottom of the chart.

Simple example of threading in C++

#include <thread>
#include <iostream>
#include <vector>
using namespace std;

void doSomething(int id) {
    cout << id << "\n";
}

/**
 * Spawns n threads
 */
void spawnThreads(int n)
{
    std::vector<thread> threads(n);
    // spawn n threads:
    for (int i = 0; i < n; i++) {
        threads[i] = thread(doSomething, i + 1);
    }

    for (auto& th : threads) {
        th.join();
    }
}

int main()
{
    spawnThreads(10);
}

Comparing Arrays of Objects in JavaScript

The objectsAreSame function mentioned in @JasonBunting's answer works fine for me. However, there's a little problem: If x[propertyName] and y[propertyName] are objects (typeof x[propertyName] == 'object'), you'll need to call the function recursively in order to compare them.

Padding zeros to the left in postgreSQL

The to_char() function is there to format numbers:

select to_char(column_1, 'fm000') as column_2
from some_table;

The fm prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000 simply defines the number of digits you want to have.

psql (9.3.5)
Type "help" for help.

postgres=> with sample_numbers (nr) as (
postgres(>     values (1),(11),(100)
postgres(> )
postgres-> select to_char(nr, 'fm000')
postgres-> from sample_numbers;
 to_char
---------
 001
 011
 100
(3 rows)

postgres=>

For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html

Resize background image in div using css

With the background-size property in those browsers which support this very new feature of CSS.

How to find cube root using Python?

The best way is to use simple math

>>> a = 8
>>> a**(1./3.)
2.0

EDIT

For Negative numbers

>>> a = -8
>>> -(-a)**(1./3.)
-2.0

Complete Program for all the requirements as specified

x = int(input("Enter an integer: "))
if x>0:
    ans = x**(1./3.)
    if ans ** 3 != abs(x):
        print x, 'is not a perfect cube!'
else:
    ans = -((-x)**(1./3.))
    if ans ** 3 != -abs(x):
        print x, 'is not a perfect cube!'

print 'Cube root of ' + str(x) + ' is ' + str(ans)

asynchronous vs non-blocking

In many circumstances they are different names for the same thing, but in some contexts they are quite different. So it depends. Terminology is not applied in a totally consistent way across the whole software industry.

For example in the classic sockets API, a non-blocking socket is one that simply returns immediately with a special "would block" error message, whereas a blocking socket would have blocked. You have to use a separate function such as select or poll to find out when is a good time to retry.

But asynchronous sockets (as supported by Windows sockets), or the asynchronous IO pattern used in .NET, are more convenient. You call a method to start an operation, and the framework calls you back when it's done. Even here, there are basic differences. Asynchronous Win32 sockets "marshal" their results onto a specific GUI thread by passing Window messages, whereas .NET asynchronous IO is free-threaded (you don't know what thread your callback will be called on).

So they don't always mean the same thing. To distil the socket example, we could say:

  • Blocking and synchronous mean the same thing: you call the API, it hangs up the thread until it has some kind of answer and returns it to you.
  • Non-blocking means that if an answer can't be returned rapidly, the API returns immediately with an error and does nothing else. So there must be some related way to query whether the API is ready to be called (that is, to simulate a wait in an efficient way, to avoid manual polling in a tight loop).
  • Asynchronous means that the API always returns immediately, having started a "background" effort to fulfil your request, so there must be some related way to obtain the result.

How to hide app title in android?

use

<activity android:name=".ActivityName" 
          android:theme="@android:style/Theme.NoTitleBar">

Correct use of flush() in JPA/Hibernate

Probably the exact details of em.flush() are implementation-dependent. In general anyway, JPA providers like Hibernate can cache the SQL instructions they are supposed to send to the database, often until you actually commit the transaction. For example, you call em.persist(), Hibernate remembers it has to make a database INSERT, but does not actually execute the instruction until you commit the transaction. Afaik, this is mainly done for performance reasons.

In some cases anyway you want the SQL instructions to be executed immediately; generally when you need the result of some side effects, like an autogenerated key, or a database trigger.

What em.flush() does is to empty the internal SQL instructions cache, and execute it immediately to the database.

Bottom line: no harm is done, only you could have a (minor) performance hit since you are overriding the JPA provider decisions as regards the best timing to send SQL instructions to the database.

Plot a bar using matplotlib using a dictionary

Why not just:

import seaborn as sns

sns.barplot(list(D.keys()), list(D.values()))

Math functions in AngularJS bindings

Either bind the global Math object onto the scope (remember to use $window not window)

$scope.abs = $window.Math.abs;

Use the binding in your HTML:

<p>Distance from zero: {{abs(distance)}}</p>

Or create a filter for the specific Math function you're after:

module.filter('abs', ['$window', function($window) {
  return function(n) {
    return $window.Math.abs($window.parseInt(n));
  };
});

Use the filter in your HTML:

<p>Distance from zero: {{distance | abs}}</p>