Programs & Examples On #Cascade filtering

Read Post Data submitted to ASP.Net Form

NameValueCollection nvclc = Request.Form;
string   uName= nvclc ["txtUserName"];
string   pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);

Define make variable at rule execution time

I dislike "Don't" answers, but... don't.

make's variables are global and are supposed to be evaluated during makefile's "parsing" stage, not during execution stage.

In this case, as long as the variable local to a single target, follow @nobar's answer and make it a shell variable.

Target-specific variables, too, are considered harmful by other make implementations: kati, Mozilla pymake. Because of them, a target can be built differently depending on if it's built standalone, or as a dependency of a parent target with a target-specific variable. And you won't know which way it was, because you don't know what is already built.

How do I make a file:// hyperlink that works in both IE and Firefox?

At least with Chrome, (I don't know about Firefox) You can drag the icon to the left of the URL in the browser to a folder location on your desktop and it will create a file that behaves as an internet shortcut.

I don't know if the file format is universal yet, however Chrome seems to know what to do with it.

The file produced is a .url file and contains the following:

[InternetShortcut] URL=

You can replace the URL with anything you'd like.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

    android:src="@drawable/banner_portrait" />

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

<link rel="stylesheet" type="text/css" href="file.css">

You can simply write:

<link rel="stylesheet" href="file.css">

Add new value to an existing array in JavaScript

There are several ways:

Instantiating the array:

var arr;

arr = new Array(); // empty array

// ---

arr = [];          // empty array

// ---

arr = new Array(3);
alert(arr.length);  // 3
alert(arr[0]); // undefined

// ---

arr = [3];
alert(arr.length);  // 1
alert(arr[0]); // 3

Pushing to the array:

arr = [3];     // arr == [3]
arr[1] = 4;    // arr == [3, 4]
arr[2] = 5;    // arr == [3, 4, 5]
arr[4] = 7;    // arr == [3, 4, 5, undefined, 7]

// ---

arr = [3];
arr.push(4);        // arr == [3, 4]
arr.push(5);        // arr == [3, 4, 5]
arr.push(6, 7, 8);  // arr == [3, 4, 5, 6, 7, 8]

Using .push() is the better way to add to an array, since you don't need to know how many items are already there, and you can add many items in one function call.

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Open this Link and select follow the instructions google servers blocks any attempts from unknown servers so once you click on captcha check every thing will be fine

Utils to read resource text file to String (Java)

I'm using the following for reading resource files from the classpath:

import java.util.Scanner;

public class ResourceUtilities
    public static String resourceToString(String filePath) throws IOException, URISyntaxException
        try (InputStream inputStream = ResourceUtilities.class.getClassLoader().getResourceAsStream(filePath))
            return inputStreamToString(inputStream);

    private static String inputStreamToString(InputStream inputStream)
        try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"))
            return scanner.hasNext() ? : "";

No third party dependencies required.

What is the difference between the | and || or operators?

For bitwise | and Logicall ||


bitwise & and logicall &&

it means if( a>b | a==0) in this first left a>b will be evaluated and then a==0 will be evaluated then | operation will be done

but in|| if a>b then if wont check for next RHS

Similarly for & and &&

if(A>0 & B>0)

it will evalue LHS and then RHS then do bitwise & but

in(A>0 && B>0)

if(A>0) is false(LHS) it will directly return false;

How to check is Apache2 is stopped in Ubuntu?

You can also type "top" and look at the list of running processes.

How to use moment.js library in angular 2 typescript app?


Using external libraries is in the documentation here:

Simply install your library via

npm install lib-name --save

and import it in your code. If the library does not include typings, you can install them using:

npm install lib-name --save

npm install @types/lib-name --save-dev

Then open src/ and add it to the types array:

"types":[ "lib-name" ]

If the library you added typings for is only to be used on your e2e tests, instead use e2e/tsconfig.e2e.json. The same goes for unit tests and src/tsconfig.spec.json.

If the library doesn't have typings available at @types/, you can still use it by manually adding typings for it:

First, create a typings.d.ts file in your src/ folder.

This file will be automatically included as global type definition. Then, in src/typings.d.ts, add the following code:

declare module 'typeless-package';

Finally, in the component or file that uses the library, add the following code:

import * as typelessPackage from 'typeless-package'; typelessPackage.method();

Done. Note: you might need or find useful to define more typings for the library that you're trying to use.

What is the dual table in Oracle?

A utility table in Oracle with only 1 row and 1 column. It is used to perform a number of arithmetic operations and can be used generally where one needs to generate a known output.


will give a single row, with a single column named "DUMMY" and a value of "X" as shown here:


sql try/catch rollback/commit - preventing erroneous commit after rollback

I used below ms sql script pattern several times successfully which uses Try-Catch,Commit Transaction- Rollback Transaction,Error Tracking.

Your TRY block will be as follows

 //your script block

Your CATCH block will be as follows

DECLARE @ErrMsg NVarChar(4000), 
        @ErrNum Int, 
        @ErrSeverity Int, 
        @ErrState Int, 
        @ErrLine Int, 
        @ErrProc NVarChar(200)
 SELECT @ErrNum = Error_Number(), 
       @ErrSeverity = Error_Severity(), 
       @ErrState = Error_State(), 
       @ErrLine = Error_Line(), 
       @ErrProc = IsNull(Error_Procedure(), '-')
 SET @ErrMsg = N'ErrLine: ' + rtrim(@ErrLine) + ', proc: ' + RTRIM(@ErrProc) + ', 
       Message: '+ Error_Message()

Your ROLLBACK script will be part of CATCH block as follows

PRINT SUBSTRING(@ErrMsg,1,4000);   


Above different script blocks you need to use as one block. If any error happens in the TRY block it will go the the CATCH block. There it is setting various details about the error number,error severity,error line ..etc. At last all these details will get append to @ErrMsg parameter. Then it will check for the count of transaction (@@TRANCOUNT >0) , ie if anything is there in the transaction for rollback. If it is there then show the error message and ROLLBACK TRANSACTION. Otherwise simply print the error message.

We have kept our COMMIT TRANSACTION T script towards the last line of TRY block in order to make sure that it should commit the transaction(final change in the database) only after all the code in the TRY block has run successfully.

How do I append to a table in Lua

foo = {}

This works because the # operator computes the length of the list. The empty list has length 0, etc.

If you're using Lua 5.3+, then you can do almost exactly what you wanted:

foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"

Expressions are not statements in Lua and they need to be used somehow.

In Java, remove empty elements from a list of Strings

There are a few approaches that you could use:

  1. Iterate over the list, calling Iterator.remove() for the list elements you want to remove. This is the simplest.

  2. Repeatedly call List.remove(Object). This is simple too, but performs worst of all ... because you repeatedly scan the entire list. (However, this might be an option for a mutable list whose iterator didn't support remove ... for some reason.)

  3. Create a new list, iterate over the old list, adding elements that you want to retain to a new list.

  4. If you can't return the new list, as 3. above and then clear the old list and use addAll to add the elements of the new list back to it.

Which of these is fastest depends on the class of the original list, its size, and the number of elements that need to be removed. Here are some of the factors:

  • For an ArrayList, each individual remove operation is O(N), where N is the list size. It is expensive to remove multiple elements from a large ArrayList using the Iterator.remove() method (or the ArrayList.remove(element) method).

    By contrast, the Iterator.remove method for a LinkedList is O(1).

  • For an ArrayList, creating and copying a list is O(N) and relatively cheap, especially if you can ensure that the destination list's capacity is large enough (but not too large).

    By contrast, creating and copying to a LinkedList is also O(N), but considerably more expensive.

All of this adds up to a fairly complicated decision tree. If the lists are small (say 10 or less elements) you can probably get away with any of the approaches above. If the lists could be large, you need to weigh up all of the issues in the list of the expected list size and expected number of removals. (Otherwise you might end up with quadratic performance.)

extract digits in a simple way from a python string

Without using regex, you can just do:

def get_num(x):
    return int(''.join(ele for ele in x if ele.isdigit()))


>>> get_num(x)
>>> get_num(y)
>>> get_num(banana)
>>> get_num(orange)


Answering the follow up question.

If we know that the only period in a given string is the decimal point, extracting a float is quite easy:

def get_num(x):
    return float(''.join(ele for ele in x if ele.isdigit() or ele == '.'))


>>> get_num('dfgd 45.678fjfjf')

How to condense if/else into one line in Python?

There is the conditional expression:

a if cond else b

but this is an expression, not a statement.

In if statements, the if (or elif or else) can be written on the same line as the body of the block if the block is just one like:

if something: somefunc()
else: otherfunc()

but this is discouraged as a matter of formatting-style.

Remove Duplicate objects from JSON Array

The following works for me:

_.uniq(standardsList, JSON.stringify)

This would probably be slow for very long lists, however.

How to Flatten a Multidimensional Array?

The trick is passing the both the source and destination arrays by reference.

function flatten_array(&$arr, &$dst) {
    if(!isset($dst) || !is_array($dst)) {
        $dst = array();
    if(!is_array($arr)) {
        $dst[] = $arr;
    } else {
        foreach($arr as &$subject) {
            flatten_array($subject, $dst);

$recursive = array('1', array('2','3',array('4',array('5','6')),'7',array(array(array('8'),'9'),'10')));
echo "Recursive: \r\n";
$flat = null;
flatten_array($recursive, $flat);

echo "Flat: \r\n";

// If you change line 3 to $dst[] = &$arr; , you won't waste memory,
// since all you're doing is copying references, and imploding the array 
// into a string will be both memory efficient and fast:)

echo "String:\r\n";
echo implode(',',$flat);

How to create cron job using PHP?

Better use the project Cron in combination with the Linux cronjob for this task. It allows you to configure run times in your PHP Code, support background jobs and is easy to use.

First step call a PHP Script every minute:

* * * * * /usr/local/bin/run.php &> /dev/null

Second Step use the cron/cron Package to configure run times directly in PHP.

$deprecatedStatus = new ShellJob();
$deprecatedStatus->setCommand('cd /app && /usr/local/bin/php cron/updateDeprecatedStatus.php');
$deprecatedStatus->setSchedule(new CrontabSchedule('* * * * */2'));

$displayDate = new ShellJob();
$displayDate->setCommand('cd /app && /usr/local/bin/php cron/updateDisplayDate.php');
$displayDate->setSchedule(new CrontabSchedule('* * * * */5'));

You found the details how to use in the linked repository.

In Python, how do you convert a `datetime` object to seconds?

from the python docs:


Return the total number of seconds contained in the duration. Equivalent to

(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

computed with true division enabled.

Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.

This functionality is new in version 2.7.

How to HTML encode/escape a string? Is there a built-in?

The h helper method:

<%=h "<p> will be preserved" %>

How to add AUTO_INCREMENT to an existing column?

Simply just add auto_increment Constraint In column or MODIFY COLUMN :-


Or add a column first then change column as -

1. Alter TABLE `emp` ADD COLUMN `id`;


Proper way to use **kwargs in Python

You'd do

self.attribute = kwargs.pop('name', default_value)


self.attribute = kwargs.get('name', default_value)

If you use pop, then you can check if there are any spurious values sent, and take the appropriate action (if any).

Printing an int list in a single line python3

Maybe this code will help you.

>>> def sort(lists):
...     lists.sort()
...     return lists
>>> datalist = [6,3,4,1,3,2,9]
>>> print(*sort(datalist), end=" ")
1 2 3 3 4 6 9

you can use an empty list variable to collect the user input, with method append(). and if you want to print list in one line you can use print(*list)

What is it exactly a BLOB in a DBMS context


BLOB (Binary Large Object) is a large object data type in the database system. BLOB could store a large chunk of data, document types and even media files like audio or video files. BLOB fields allocate space only whenever the content in the field is utilized. BLOB allocates spaces in Giga Bytes.


You can write a binary large object (BLOB) to a database as either binary or character data, depending on the type of field at your data source. To write a BLOB value to your database, issue the appropriate INSERT or UPDATE statement and pass the BLOB value as an input parameter. If your BLOB is stored as text, such as a SQL Server text field, you can pass the BLOB as a string parameter. If the BLOB is stored in binary format, such as a SQL Server image field, you can pass an array of type byte as a binary parameter.

A useful link : Storing documents as BLOB in Database - Any disadvantages ?

Counting duplicates in Excel

You can achieve your result in two steps. First, create a list of unique entries using Advanced Filter... from the pull down Filter menu. To do so, you have to add a name of the column to be sorted out. It is necessary, otherwise Excel will treat first row as a name rather than an entry. Highlight column that you want to filter (A in the example below), click the filter icon and chose 'Advanced Filter...'. That will bring up a window where you can select an option to "Copy to another location". Choose that one, as you will need your original list to do counts (in my example I will choose C:C). Also, select "Unique record only". That will give you a list of unique entries. Then you can count their frequencies using =COUNTIF() command. See screedshots for details.

Hope this helps!

  |   A    |   B   |   C    |         D         |
1 | ToSort |       | ToSort |                   |
2 |  GL15  |       | GL15   | =COUNTIF(A:A, C2) |
3 |  GL15  |       | GL16   | =COUNTIF(A:A, C3) |
4 |  GL15  |       | GL17   | =COUNTIF(A:A, C4) |
5 |  GL16  |       |        |                   |
6 |  GL17  |       |        |                   |
7 |  GL17  |       |        |                   |

Step 1Step 2Step 3

What are the most common naming conventions in C?

Here's an (apparently) uncommon one, which I've found useful: module name in CamelCase, then an underscore, then function or file-scope name in CamelCase. So for example:


CSS: center element within a <div> element

First of all you can do it with left:50% to center it relative to parent div but for that you need to learn CSS positioning.

One possible solution from many is to do something like

    div.parent { text-align:center; }    //will center align every thing in this div as well as in the children element
    div.parent div { text-align:left;}   //to restore so every thing would start from left

if your your div to be centered is positioned relatively, you can just do

    .mydiv { position:relative; margin:0 auto; } 

How to keep an iPhone app running on background fully operational

May be the link will Help bcz u might have to implement the code in Appdelegate in app run in background method .. Also consult the site for application class Here is link for runing app in background

Using os.walk() to recursively traverse directories in Python

Recursive walk through a directory where you get ALL files from all dirs in the current directory and you get ALL dirs from the current directory - because codes above don't have a simplicity (imho):

for root, dirs, files in os.walk(rootFolderPath):
    for filename in files:
        doSomethingWithFile(os.path.join(root, filename))
    for dirname in dirs:
        doSomewthingWithDir(os.path.join(root, dirname))

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

I had this same error in an MVC 4 application using Razor. In an attempt to clean up the web.config files, I removed the two webpages: configuration values:

  <add key="webpages:Version" value="" />
  <add key="webpages:Enabled" value="false" />

Once I restored these configuration values, the pages would compile correctly and the errors regarding the .Partial() extension method disappeared.

if condition in sql server update query

Since you're using SQL 2008:


     = CASE
        WHEN @flag = '1' THEN @new_value
        ELSE 0
    END + column_A,

     = CASE
        WHEN @flag = '0' THEN @new_value
        ELSE 0
    END + column_B 
    ID = @ID

If you were using SQL 2012:

    column_A  = column_A + IIF(@flag = '1', @new_value, 0),
    column_B  = column_B + IIF(@flag = '0', @new_value, 0)
    ID = @ID

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

String Concatenation in EL

Since Expression Language 3.0, it is valid to use += operator for string concatenation.

${(empty value)? "none" : value += " enabled"}  // valid as of EL 3.0

Quoting EL 3.0 Specification.

String Concatenation Operator

To evaluate

A += B 
  • Coerce A and B to String.
  • Return the concatenated string of A and B.

How to remove blank lines from a Unix file

Use grep to match any line that has nothing between the start anchor (^) and the end anchor ($):

grep -v '^$' infile.txt > outfile.txt

If you want to remove lines with only whitespace, you can still use grep. I am using Perl regular expressions in this example, but here are other ways:

grep -P -v '^\s*$' infile.txt > outfile.txt

or, without Perl regular expressions:

grep -v '^[[:space:]]*$' infile.txt > outfile.txt

How can I use pointers in Java?

Not really, no.

Java doesn't have pointers. If you really wanted you could try to emulate them by building around something like reflection, but it would have all of the complexity of pointers with none of the benefits.

Java doesn't have pointers because it doesn't need them. What kind of answers were you hoping for from this question, i.e. deep down did you hope you could use them for something or was this just curiousity?

How to detect Ctrl+V, Ctrl+C using JavaScript?

Live Demo :

$(document).ready(function() {

        copy : function(){
            $('span').text('copy behaviour detected!');
        paste : function(){
            $('span').text('paste behaviour detected!');
        cut : function(){
            $('span').text('cut behaviour detected!');


Printing the correct number of decimal points with cout

setprecision(n) applies to the entire number, not the fractional part. You need to use the fixed-point format to make it apply to the fractional part: setiosflags(ios::fixed)

In Bootstrap 3,How to change the distance between rows in vertical?

Use <br> tags

<div class="container">   
    <div class="row" id="a">
        <img src="">

    <br><br> <!--insert one, two, or more here-->

    <div class="row" id="b">

Find the item with maximum occurrences in a list

Simple and best code:

def max_occ(lst,x):
    for i in lst:
        if (i==x):
    return count

lst=[1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
print(x,"occurs ",max_occ(lst,x),"times")

Output: 4 occurs 6 times

Send an Array with an HTTP Get

I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.

You have to write the query adding "[]" to foo like this:


Convert string to title case with JavaScript

Here's a really simple & concise ES6 function to do this:

const titleCase = (str) => {
  return str.replace(/\w\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });

export default titleCase;

Works well included in a utilities folder and used as follows:

import titleCase from './utilities/titleCase.js';

const string = 'my title & string';

console.log(titleCase(string)); //-> 'My Title & String'

tsconfig.json: Build:No inputs were found in config file

When using Visual Studio Code, building the project (i.e. pressing Ctrl + Shift + B), moves your .ts file into the .vscode folder (I don't know why it does this), then generates the TS18003 error. What I did was move my .ts file out of the .vscode folder, back into the root folder and build the project again.

The project built successfully!

How to search by key=>value in a multidimensional array in PHP

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

Processing Symbol Files in Xcode

It downloads the (debug) symbols from the device, so it becomes possible to debug on devices with that specific iOS version and also to symbolicate crash reports that happened on that iOS version.

Since symbols are CPU specific, the above only works if you have imported the symbols not only for a specific iOS device but also for a specific CPU type. The currently CPU types needed are armv7 (e.g. iPhone 4, iPhone 4s), armv7s (e.g. iPhone 5) and arm64 (e.g. iPhone 5s).

So if you want to symbolicate a crash report that happened on an iPhone 5 with armv7s and only have the symbols for armv7 for that specific iOS version, Xcode won't be able to (fully) symbolicate the crash report.

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

I understand this has been marked as answered but I ran into a bit of a problem when I was working on a project where I have my EF Core Data Access Layer in a .DLL Project separated from the rest of my project, API, Auth and Web and mostly will like my other projects to reference this Data project. And I don't want to want to come into the Data project to change connection strings everytime.

STEP 1: Include this in the OnConfiguring Method

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
           var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
           IConfigurationRoot configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false)
                .AddJsonFile($"appsettings.{envName}.json", optional: false)

NOTE: .SetBasePath(Path.Combine(Directory.GetCurrentDirectory())) This will negate or invalidate the need to copy the file to a directory as ASP.NET CORE is smart enough to pick the the right file. Also the environment specified will pick right file when the building for Release or Production, assuming the Prod environment file is selected.

STEP 2: Create appsettings.json

"ConnectionStrings": {       
  "DefaultConnection": "Server=YOURSERVERNAME; Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"        


PLEASE: Referece: Microsoft.Extensions.Configuration

Can you write nested functions in JavaScript?

Not only can you return a function which you have passed into another function as a variable, you can also use it for calculation inside but defining it outside. See this example:

    function calculate(a,b,fn) {
      var c = a * 3 + b + fn(a,b);
      return  c;

    function sum(a,b) {
      return a+b;

    function product(a,b) {
      return a*b;

    document.write(calculate (10,20,sum)); //80
    document.write(calculate (10,20,product)); //250

How to insert a row in an HTML table body in JavaScript

Basic approach:

This should add HTML-formatted content and show the newly added row.

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;

Open mvc view in new window from controller

I assigned the javascript in my Controller:

model.linkCode = "'', '_blank')";

And in my view:

@section Scripts{
    <script @Html.CspScriptNonce()>

    $(function () {

        @if (!String.IsNullOrEmpty(Model.linkCode))

That opened a new tab with the link, and went to it.

Interestingly, run locally it engaged a popup blocker, but seemed to work fine on the servers.

An URL to a Windows shared folder

This depend on how you want to incorporate it. The scenario 1. click on a link 2. explorer window popped up

<a href="\\server\folder\path" target="_blank">click</a>

If there is a need in a fancy UI - then it will barely serve as a solution.

String is immutable. What exactly is the meaning?

You are actually getting a reference to a new string, the string itself is not being changed as it is immutable. This is relevant.


Immutable objects on Wikipedia

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

You can try the code below, it works perfectly.

Here we share to some specific apps, that are Facebook, Messenger, Twitter, Google Plus and Gmail.

public void shareIntentSpecificApps() {
        List<Intent> intentShareList = new ArrayList<Intent>();
        Intent shareIntent = new Intent();
        List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(shareIntent, 0);

        for (ResolveInfo resInfo : resolveInfoList) {
            String packageName = resInfo.activityInfo.packageName;
            String name =;
            Log.d(TAG, "Package Name : " + packageName);
            Log.d(TAG, "Name : " + name);

            if (packageName.contains("com.facebook") ||
                    packageName.contains("") ||
                    packageName.contains("") ||
                    packageName.contains("")) {

                if (name.contains("")) {

                Intent intent = new Intent();
                intent.setComponent(new ComponentName(packageName, name));
                intent.putExtra(Intent.EXTRA_SUBJECT, "Your Subject");
                intent.putExtra(Intent.EXTRA_TEXT, "Your Content");

        if (intentShareList.isEmpty()) {
            Toast.makeText(MainActivity.this, "No apps to share !", Toast.LENGTH_SHORT).show();
        } else {
            Intent chooserIntent = Intent.createChooser(intentShareList.remove(0), "Share via");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentShareList.toArray(new Parcelable[]{}));

De-obfuscate Javascript code to make it readable again

From the first link on google;

function call_func(_0x41dcx2) {
 var _0x41dcx3 = eval('(' + _0x41dcx2 + ')');
 var _0x41dcx4 = document['createElement']('div');
 var _0x41dcx5 = _0x41dcx3['id'];
 var _0x41dcx6 = _0x41dcx3['Student_name'];
 var _0x41dcx7 = _0x41dcx3['student_dob'];
 var _0x41dcx8 = '<b>ID:</b>';
 _0x41dcx8 += '<a href="/learningyii/index.php?r=student/view&amp; id=' + _0x41dcx5 + '">' + _0x41dcx5 + '</a>';
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student Name:</b>';
 _0x41dcx8 += _0x41dcx6;
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student DOB:</b>';
 _0x41dcx8 += _0x41dcx7;
 _0x41dcx8 += '<br/>';
 _0x41dcx4['innerHTML'] = _0x41dcx8;
 _0x41dcx4['setAttribute']('class', 'view');

It won't get you all the way back to source, and that's not really possible, but it'll get you out of a hole.

less than 10 add 0 to number

I was bored and playing around JSPerf trying to beat the currently selected answer prepending a zero no matter what and using slice(-2). It's a clever approach but the performance gets a lot worse as the string gets longer.

For numbers zero to ten (one and two character strings) I was able to beat by about ten percent, and the fastest approach was much better when dealing with longer strings by using charAt so it doesn't have to traverse the whole string.

This follow is not quit as simple as slice(-2) but is 86%-89% faster when used across mostly 3 digit numbers (3 character strings).

var prepended = ( 1 === string.length && string.charAt( 0 ) !== "0" ) ? '0' + string : string;

How to create a numpy array of arbitrary length strings?

You can do so by creating an array of dtype=object. If you try to assign a long string to a normal numpy array, it truncates the string:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'], 

But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)

Indeed, because it's an array of objects, you can assign any kind of python object to the array:

>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)

However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:

>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop

Uploading/Displaying Images in MVC 4

Here is a short tutorial:


namespace ImageUploadApp.Models
    using System;
    using System.Collections.Generic;

    public partial class Image
        public int ID { get; set; }
        public string ImagePath { get; set; }


  1. Create:

    @model ImageUploadApp.Models.Image
        ViewBag.Title = "Create";
    @using (Html.BeginForm("Create", "Image", null, FormMethod.Post, 
                                  new { enctype = "multipart/form-data" })) {
            <div class="editor-label">
                @Html.LabelFor(model => model.ImagePath)
            <div class="editor-field">
                <input id="ImagePath" title="Upload a product image" 
                                      type="file" name="file" />
            <p><input type="submit" value="Create" /></p>
        @Html.ActionLink("Back to List", "Index")
    @section Scripts {
  2. Index (for display):

    @model IEnumerable<ImageUploadApp.Models.Image>
        ViewBag.Title = "Index";
        @Html.ActionLink("Create New", "Create")
                @Html.DisplayNameFor(model => model.ImagePath)
    @foreach (var item in Model) {
                @Html.DisplayFor(modelItem => item.ImagePath)
                @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
                @Html.ActionLink("Details", "Details", new { id=item.ID }) |
                @Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
  3. Controller (Create)

    public ActionResult Create(Image img, HttpPostedFileBase file)
        if (ModelState.IsValid)
            if (file != null)
                                                      + file.FileName);
                img.ImagePath = file.FileName;
            return RedirectToAction("Index");
        return View(img);

Hope this will help :)

RESTful Authentication

It's certainly not about "session keys" as it is generally used to refer to sessionless authentication which is performed within all of the constraints of REST. Each request is self-describing, carrying enough information to authorize the request on its own without any server-side application state.

The easiest way to approach this is by starting with HTTP's built-in authentication mechanisms in RFC 2617.

How can I disable inherited css styles?

If you control both the HTML and CSS, I'd suggest switching to using ID's on all the divs needed for the rounded corner.


#d1 {
    background: #CFFEB6 url('tr.gif') no-repeat top right;
#d2 {
    background: url('br.gif') no-repeat bottom right;
#d3 {
    background: url('bl.gif') no-repeat bottom left;
#d4 {
    padding: 10px;


<div id="d1"><div id="d2"><div id="d3"><div id="d4">
    <div class='button'><a href='#'>Test</a></div>

Ansible - read inventory hosts and variables to group_vars/all file

If you want to programmatically access the inventory entries to include them in a task for example. You can refer to it like this:

{{ hostvars.tomcat }}

This returns you a structure with all variables related with that host. If you want just an IP address (or hostname), you can refer to it like this:

{{ hostvars.jboss5.ansible_ssh_host }}

Here is a list of variables which you can refer to: click. Moreover, you can declare a variable and set it with for example result of some step in a playbook.

- name: Change owner and group of some file
  file: path=/tmp/my-file owner=new-owner group=new-group
  register: chown_result

Then if you play this step on tomcat, you can access it from jboss5 like this:

- name: Print out the result of chown
  debug: msg="{{ hostvars.tomcat.chown_result }}"

Hibernate Criteria Query to get specific columns

I like this approach because it is simple and clean:

    String getCompaniesIdAndName = " select "
            + " as id, "
            + " as name "
            + " from Company c ";

    @Query(value = getCompaniesWithoutAccount)
    Set<CompanyIdAndName> findAllIdAndName();

    public static interface CompanyIdAndName extends DTO {
        Integer getId();

        String getName();


Jmeter - get current date and time

JMeter is using java SimpleDateFormat

For UTC with timezone use this


IndentationError: unindent does not match any outer indentation level

For SPYDER users: I'm using spyder 3.3.2 with python 3.7.1 and I solved this, setting indentation to use tabs, with the following steps, click on:

  • Tools.
  • Preferences.
  • Editor.
  • Advanced settings.
  • Indentation characters -> Tabs.

Then I reset the "unidented" line using tab key.

For some reason, without this setting, I got the ghost IndentationError sometimes.

Add a CSS border on hover without moving the element

Add a border to the regular item, the same color as the background, so that it cannot be seen. That way the item has a border: 1px whether it is being hovered or not.

Field 'id' doesn't have a default value?

This is caused by MySQL having a strict mode set which won’t allow INSERT or UPDATE commands with empty fields where the schema doesn’t have a default value set.

There are a couple of fixes for this.

First ‘fix’ is to assign a default value to your schema. This can be done with a simple ALTER command:

ALTER TABLE `details` CHANGE COLUMN `delivery_address_id` `delivery_address_id` INT(11) NOT NULL DEFAULT 0 ;

However, this may need doing for many tables in your database schema which will become tedious very quickly. The second fix is to remove sql_mode STRICT_TRANS_TABLES on the mysql server.

If you are using a brew installed MySQL you should edit the my.cnf file in the MySQL directory. Change the sql_mode at the bottom:


Save the file and restart Mysql.


Cannot find the declaration of element 'beans'

Add this code ..It helped me

<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="" 

Setting JDK in Eclipse

Some additional steps may be needed to set both the project and default workspace JRE correctly, as MayoMan mentioned. Here is the complete sequence in Eclipse Luna:

  • Right click your project > properties
  • Select “Java Build Path” on left, then “JRE System Library”, click Edit…
  • Select "Workspace Default JRE"
  • Click "Installed JREs"
  • If you see JRE you want in the list select it (selecting a JDK is OK too)
  • If not, click Search…, navigate to Computer > Windows C: > Program Files > Java, then click OK
  • Now you should see all installed JREs, select the one you want
  • Click OK/Finish a million times

Easy.... not.

Is there a "between" function in C#?

Refer to this link. A one line solution to that question.

How to elegantly check if a number is within a range?

int x = 30;
if (Enumerable.Range(1,100).Contains(x))

if (x >= 1 && x <= 100)

I know the post is pretty old, but It may help others..

Loop through all the resources in a .resx file

You should always use the resource manager and not read files directly to ensure globalization is taken into account.

using System.Collections;
using System.Globalization;
using System.Resources;


/* Reference to your resources class -- may be named differently in your case */
ResourceManager MyResourceClass =
    new ResourceManager(typeof(Resources));

ResourceSet resourceSet =
    MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
    string resourceKey = entry.Key.ToString();
    object resource = entry.Value;

jquery remove "selected" attribute of option?

Another alternative:

$('option:selected', $('#mySelectParent')).removeAttr("selected");

Hope it helps

How can I initialize C++ object member variables in the constructor?

Regarding the first (and great) answer from chris who proposed a solution to the situation where the class members are held as a "true composite" members (i.e.- not as pointers nor references):

The note is a bit large, so I will demonstrate it here with some sample code.

When you chose to hold the members as I mentioned, you have to keep in mind also these two things:

  1. For every "composed object" that does not have a default constructor - you must initialize it in the initialization list of all the constructor's of the "father" class (i.e.- BigMommaClass or MyClass in the original examples and MyClass in the code below), in case there are several (see InnerClass1 in the example below). Meaning, you can "comment out" the m_innerClass1(a) and m_innerClass1(15) only if you enable the InnerClass1 default constructor.

  2. For every "composed object" that does have a default constructor - you may initialize it within the initialization list, but it will work also if you chose not to (see InnerClass2 in the example below).

See sample code (compiled under Ubuntu 18.04 (Bionic Beaver) with g++ version 7.3.0):

#include <iostream>

using namespace std;

class InnerClass1
        InnerClass1(int a) : m_a(a)
            cout << "InnerClass1::InnerClass1 - set m_a:" << m_a << endl;

        /* No default constructor
        InnerClass1() : m_a(15)
            cout << "InnerClass1::InnerClass1() - set m_a:" << m_a << endl;

            cout << "InnerClass1::~InnerClass1" << endl;

        int m_a;

class InnerClass2
        InnerClass2(int a) : m_a(a)
            cout << "InnerClass2::InnerClass2 - set m_a:" << m_a << endl;

        InnerClass2() : m_a(15)
            cout << "InnerClass2::InnerClass2() - set m_a:" << m_a << endl;

            cout << "InnerClass2::~InnerClass2" << endl;

        int m_a;

class MyClass
        MyClass(int a, int b) : m_innerClass1(a), /* m_innerClass2(a),*/ m_b(b)
            cout << "MyClass::MyClass(int b) - set m_b to:" << m_b << endl;

         MyClass() : m_innerClass1(15), /*m_innerClass2(15),*/ m_b(17)
            cout << "MyClass::MyClass() - m_b:" << m_b << endl;

            cout << "MyClass::~MyClass" << endl;

        InnerClass1 m_innerClass1;
        InnerClass2 m_innerClass2;
        int m_b;

int main(int argc, char** argv)
    cout << "main - start" << endl;

    MyClass obj;

    cout << "main - end" << endl;
    return 0;

How to make the overflow CSS property work with hidden as value

Evidently, sometimes, the display properties of parent of the element containing the matter that shouldn't overflow should also be set to overflow:hidden as well, e.g.:

<div style="overflow: hidden">
  <div style="overflow: hidden">some text that should not overflow<div>

Why? I have no idea but it worked for me. See (ignore the sniping at stackoverflow!)

bash export command

SHELL is an environment variable, and so it's not the most reliable for what you're trying to figure out. If your tool is using a shell which doesn't set it, it will retain its old value.

Use ps to figure out what's really going on.

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

Comprehensive answer is here:

Your problem can be related to incorrect login which varies depending on AMIs. Use following logins on following AMIs:

  • ubuntu or root on ubuntu AMIs
  • ec2-user on Amazon Linux AMI
  • centos on Centos AMI
  • debian or root on Debian AMIs
  • ec2-user or fedora on Fedora
  • ec2-user or root on: RHEL AMI, SUSE AMI, other ones.

If you are using OS:

  • Windows - get PEM key from AWS website and generate PPK file using PuttyGen. Then use Putty to use the PPK (select it using left-column: Connection->SSH->Auth: Private key for authorization)
  • Linux - run: ssh -i your-ssh-key.pem login@IP-or-DNS

Good luck.

Explain why constructor inject is better than other options

By using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner

We need the assurance from the IoC container that, before using any bean, the injection of necessary beans must be done.

In setter injection strategy, we trust the IoC container that it will first create the bean first but will do the injection right before using the bean using the setter methods. And the injection is done according to your configuration. If you somehow misses to specify any beans to inject in the configuration, the injection will not be done for those beans and your dependent bean will not function accordingly when it will be in use!

But in constructor injection strategy, container imposes (or must impose) to provide the dependencies properly while constructing the bean. This was addressed as " container-agnostic manner", as we are required to provide dependencies while creating the bean, thus making the visibility of dependency, independent of any IoC container.


Q1: And how to prevent container from creating bean by constructor with null values instead of missing beans?

You have no option to really miss any <constructor-arg> (in case of Spring), because you are imposed by IoC container to provide all the constructor arguments needed to match a provided constructor for creating the bean. If you provide null in your <constructor-arg> intentionally. Then there is nothing IoC container can do or need to do with it!

css h1 - only as wide as the text

align-self-start, align-self-center... in flexbox

.centercol h1{
    background: #F2EFE9;
    border-left: 3px solid #C6C1B8;
    color: #006BB6;
    display: block;
    align-self: center;
    font-weight: normal;
    font-size: 18px;
    padding: 3px 3px 3px 6px;

Add column to SQL Server

Add new column to Table

ADD Column1 Datatype



If User wants to make it auto incremented then


How to link to specific line number on github

a permalink to a code snippet is pasted into a pull request comment field

You can you use permalinks to include code snippets in issues, PRs, etc.


HTML input type=file, get the image before submitting the form

Here is the complete example for previewing image before it gets upload.


<link class="jsbin" href="" rel="stylesheet" type="text/css" />
<script class="jsbin" src=""></script>
<script class="jsbin" src=""></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src=""></script>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />

JavaScript :

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {

Best data type to store money values in MySQL

You can use DECIMAL or NUMERIC both are same

The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following remarks about DECIMAL apply equally to NUMERIC. : MySQL

i.e. DECIMAL(10,2)

Example settings

Good read

'tuple' object does not support item assignment

PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do:

pixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels]

Also, if the pixel is already too red, adding 20 will overflow the value. You probably want something like min(pixel[0] + 20, 255) or int(255 * (pixel[0] / 255.) ** 0.9) instead of pixel[0] + 20.

And, to be able to handle images in lots of different formats, do image = image.convert("RGB") after opening the image. The convert method will ensure that the pixels are always (r, g, b) tuples.

how to add super privileges to mysql database?

On Centos 5 I was getting all sorts of errors trying to make changes to some variable values from the MySQL shell, after having logged in with the proper uid and pw (with root access). The error that I was getting was something like this:

mysql> -- Set some variable value, for example
mysql> SET GLOBAL general_log='ON';
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In a moment of extreme serendipity I did the following:

OS-Shell> sudo mysql                          # no DB uid, no DB pw

Kindly note that I did not provide the DB uid and password

mysql> show variables;
mysql> -- edit the variable of interest to the desired value, for example
mysql> SET GLOBAL general_log='ON';

It worked like a charm

button image as form input submit button?

You could use an image submit button:

<input type="image" src="images/login.jpg" alt="Submit Form" />

Strtotime() doesn't work with dd/mm/YYYY format

If you know it's in dd/mm/YYYY, you can do:

    $regex = '#([/d]{1,2})/([/d]{1,2})/([/d]{2,4})#';
    $match = array();
    if (preg_match($regex, $date, $match)) {
        if (strlen($match[3]) == 2) {
            $match[3] = '20' . $match[3];
        return mktime(0, 0, 0, $match[2], $match[1], $match[3]);
    return strtotime($date);

It will match dates in the form d/m/YY or dd/mm/YYYY (or any combination of the two)...

If you want to support more separators than just /, you can change the regex to:

    $regex = '#([\d]{1,2})[/-]([\d]{1,2})[/-]([\d]{2,4})#';

And then add any characters you want into the [/-] bit (Note, the - character needs to be last)

Find files in created between a date range

Try this:

find /var/tmp -mtime +2 -a -mtime -8 -ls

to find files older than 2 days but not older than 8 days.

How to execute a command in a remote computer?

    string AppPath = "\\\\spri11U1118\\SampleBatch\\Bin\\";
    string strFilePath = AppPath + "ABCED120D_XXX.bat";
    System.Diagnostics.Process proc = new System.Diagnostics.Process();

    proc.StartInfo.FileName = strFilePath;
    string pwd = "s44erver";

    proc.StartInfo.Domain = "abcd";
    proc.StartInfo.UserName = "sysfaomyulm";

    System.Security.SecureString secret = new System.Security.SecureString();
    foreach (char c in pwd)


    proc.StartInfo.Password = secret;
    proc.StartInfo.UseShellExecute = false;

    proc.StartInfo.WorkingDirectory = "psexec \\\\spri11U1118\\SampleBatch\\Bin ";

    while (!proc.HasExited)
        // Thread.Sleep(1000);

catch (Exception ex)
    throw ex;

How to run a maven created jar file using just the command line

I am not sure in your case. But as I know to run any jar file from cmd we can use following command:

Go up to the directory where your jar file is saved:

java -jar <jarfilename>.jar

But you can check following links. I hope it'll help you:

Run Netbeans maven project from command-line?

Set focus on <input> element

To make the execution after the boolean has changed and avoid the usage of timeout you can do:

import { ChangeDetectorRef } from '@angular/core';

constructor(private cd: ChangeDetectorRef) {}

showSearch(){ = !;;

How can I create an editable combo box in HTML/Javascript?

Forget datalist element that good solution for autocomplete function, but not for combobox feature.


.combobox {
    display: inline-block;
    position: relative;

.combobox select {
    display: none;
    position: absolute;
    overflow-y: auto;


<div class="combobox">
    <input type="number" name="" value="" min="" max="" step=""/><br/>
    <select size="3">
        <option value="0"> 0</option>
        <option value="25"> 25</option>
        <option value="40"> 40</option>

js (jQuery):

$('.combobox').each(function() {
        $input = $(this).find('input'),
        $select = $(this).find('select');
    function hideSelect() {
        setTimeout(function() {
            if (!$':focus') && !$':focus')) {
                    .css('z-index', 1);
        }, 20);
        .focusin(function() {
            if (!$':visible')) {
                    .css('z-index', 100);
        .on('input', function() {
        .change(function() {

This works properly even when you use text input instead of number.

macro run-time error '9': subscript out of range

"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.

Mod in Java produces negative numbers

if b > 0:
    int mod = (mod = a % b) < 0 ? a + b : a;

Doesn't use the % operator twice.

Is there a way to programmatically minimize a window

<form>.WindowState = FormWindowState.Minimized;

Set multiple system properties Java command line

You may be able to use the JAVA_TOOL_OPTIONS environment variable to set options. It worked for me with Rasbian. See Environment Variables and System Properties which has this to say:

In many environments, the command line is not readily accessible to start the application with the necessary command-line options.

This often happens with applications that use embedded VMs (meaning they use the Java Native Interface (JNI) Invocation API to start the VM), or where the startup is deeply nested in scripts. In these environments the JAVA_TOOL_OPTIONS environment variable can be useful to augment a command line.

When this environment variable is set, the JNI_CreateJavaVM function (in the JNI Invocation API), the JNI_CreateJavaVM function adds the value of the environment variable to the options supplied in its JavaVMInitArgs argument.

However this environment variable use may be disabled for security reasons.

In some cases, this option is disabled for security reasons. For example, on the Oracle Solaris operating system, this option is disabled when the effective user or group ID differs from the real ID.

See this example showing the difference between specifying on the command line versus using the JAVA_TOOL_OPTIONS environment variable.

screenshot showing use of JAVA_TOOL_OPTIONS environment variable

HashMap to return default value for non-found keys?

I found the LazyMap quite helpful.

When the get(Object) method is called with a key that does not exist in the map, the factory is used to create the object. The created object will be added to the map using the requested key.

This allows you to do something like this:

    Map<String, AtomicInteger> map = LazyMap.lazyMap(new HashMap<>(), ()->new AtomicInteger(0));

The call to get creates a default value for the given key. You specify how to create the default value with the factory argument to LazyMap.lazyMap(map, factory). In the example above, the map is initialized to a new AtomicInteger with value 0.

How to access the GET parameters after "?" in Express?

The express manual says that you should use req.query to access the QueryString.

// Requesting /display/post?size=small
app.get('/display/post', function(req, res, next) {

  var isSmall = req.query.size === 'small'; // > true
  // ...


How do I remove a single file from the staging area (undo git add)?

git rm --cached FILE


git rm -r --cached CVS */CVS

How do I run Google Chrome as root?

i followed these steps

Step 1. Open /etc/chromium/default file with editor
Step 2. Replace or add this line 
CHROMIUM_FLAGS="--password-store=detect --user-data-dir=/root/chrome-profile/"
Step 3. Save it..

Thats it.... Start the browser...

New features in java 7

Java SE 7 Features and Enhancements from JDK 7 Release Notes

This is the Java 7 new features summary from the OpenJDK 7 features page:

vm  JSR 292: Support for dynamically-typed languages (InvokeDynamic)
        Strict class-file checking
lang    JSR 334: Small language enhancements (Project Coin)
core    Upgrade class-loader architecture
        Method to close a URLClassLoader
        Concurrency and collections updates (jsr166y)
i18n    Unicode 6.0
        Locale enhancement
        Separate user locale and user-interface locale
ionet   JSR 203: More new I/O APIs for the Java platform (NIO.2)
        NIO.2 filesystem provider for zip/jar archives
        SCTP (Stream Control Transmission Protocol)
        SDP (Sockets Direct Protocol)
        Use the Windows Vista IPv6 stack
        TLS 1.2
sec     Elliptic-curve cryptography (ECC)
jdbc    JDBC 4.1
client  XRender pipeline for Java 2D
        Create new platform APIs for 6u10 graphics features
        Nimbus look-and-feel for Swing
        Swing JLayer component
        Gervill sound synthesizer [NEW]
web     Update the XML stack
mgmt    Enhanced MBeans [UPDATED]

Code examples for new features in Java 1.7

Try-with-resources statement


BufferedReader br = new BufferedReader(new FileReader(path));
try {
   return br.readLine();
} finally {


try (BufferedReader br = new BufferedReader(new FileReader(path)) {
   return br.readLine();

You can declare more than one resource to close:

try (
   InputStream in = new FileInputStream(src);
   OutputStream out = new FileOutputStream(dest))
 // code

Underscores in numeric literals

int one_million = 1_000_000;

Strings in switch

String s = ...
switch(s) {
 case "quux":
    // fall-through

  case "foo":
  case "bar":

  case "baz":
    // fall-through


Binary literals

int binary = 0b1001_1001;

Improved Type Inference for Generic Instance Creation

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();


Map<String, List<String>> anagrams = new HashMap<>();

Multiple exception catching


} catch (FirstException ex) {
     throw ex;
} catch (SecondException ex) {
     throw ex;


} catch (FirstException | SecondException ex) {
    throw ex;



@SuppressWarnings({"unchecked", "varargs"})
public static void printAll(List<String>... lists){
    for(List<String> list : lists){


public static void printAll(List<String>... lists){
    for(List<String> list : lists){

C++ delete vector, objects, free memory

You can free memory used by vector by this way:

//Removes all elements in vector

//Frees the memory which is not used by the vector

Get the last item in an array

Just putting another option here.

loc_array.splice(-1)[0] === 'index.html'

I found the above approach more clean and short onliner. Please, free feel to try this one.

Note: It will modify the original array, if you don't want to modify it you can use slice()

loc_array.slice(-1)[0] === 'index.html'

Thanks @VinayPai for pointing this out.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

var datatable_jquery_script = document.createElement("script");
datatable_jquery_script.src = "vendor/datatables/jquery.dataTables.min.js";
    var datatable_bootstrap_script = document.createElement("script");
    datatable_bootstrap_script.src = "vendor/datatables/dataTables.bootstrap4.min.js";

I used setTimeOut to make sure datatables.min.js loads first. I inspected the waterfall loading of each, bootstrap4.min.js always loads first.

Version vs build in Xcode

The marketing release number is for the customers, called version number. It starts with 1.0 and goes up for major updates to 2.0, 3.0, for minor updates to 1.1, 1.2 and for bug fixes to 1.0.1, 1.0.2 . This number is oriented about releases and new features.

The build number is mostly the internal number of builds that have been made until then. But some use other numbers like the branch number of the repository. This number should be unique to distinguish the different nearly the same builds.

As you can see, the build number is not necessary and it is up to you which build number you want to use. So if you update your Xcode to a major version, the build field is empty. The version field may not be empty!.

To get the build number as a NSString variable:

NSString * appBuildString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];

To get the version number as a NSString variable:

NSString * appVersionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];

If you want both in one NSString:

NSString * versionBuildString = [NSString stringWithFormat:@"Version: %@ (%@)", appVersionString, appBuildString];

This is tested with Xcode Version 4.6.3 (4H1503). The build number is often written in parenthesis / braces. The build number is in hexadecimal or decimal.


In Xcode you can auto-increment the build number as a decimal number by placing the following in the Run script build phase in the project settings

buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

For hexadecimal build number use this script

buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$(($buildNumber + 1)) 
buildNumber=$(printf "%X" $buildNumber)
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"


Moment get current date

Just call moment as a function without any arguments:


For timezone information with moment, look at the moment-timezone package:

Bootstrap button drop-down inside responsive table not visible because of scroll

I have a solution using only CSS, just use position relative for dropdowns inside the table-responsive:

@media (max-width: 767px) {
  .table-responsive .dropdown-menu {
    position: relative; /* Sometimes needs !important */

Why should text files end with a newline?

I was always under the impression the rule came from the days when parsing a file without an ending newline was difficult. That is, you would end up writing code where an end of line was defined by the EOL character or EOF. It was just simpler to assume a line ended with EOL.

However I believe the rule is derived from C compilers requiring the newline. And as pointed out on “No newline at end of file” compiler warning, #include will not add a newline.

Check if an array contains duplicate values

The best solution ever.

 Array.prototype.checkIfArrayIsUnique = function() {
    for ( var i = 1; i < this.length; i++ ){
        if(this[i-1] == this[i])
            return false;
    return true;

What is the right way to populate a DropDownList from a database?

public void getClientNameDropDowndata()
    getConnection = Connection.SetConnection(); // to connect with data base Configure manager
    string ClientName = "Select  ClientName from Client ";
    SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
    ClientNameCommand.CommandType = CommandType.Text;
    SqlDataReader ClientNameData;
    ClientNameData = ClientNameCommand.ExecuteReader();
    if (ClientNameData.HasRows)
        DropDownList_ClientName.DataSource = ClientNameData;
        DropDownList_ClientName.DataValueField = "ClientName";
        MessageBox.Show("No is found");
        CloseConnection = new Connection();
        CloseConnection.closeConnection(); // close the connection 

jQuery UI tabs. How to select a tab based on its id not based on index

                <div id="tabs" style="width: 290px">
                    <ul >
                        <li><a id="myTab1" href="#tabs-1" style="color: Green">Báo cáo chu?n</a></li>
                        <li><a id="myTab2" href="#tabs-2" style="color: Green">Báo cáo m? r?ng</a></li>
                    <div id="tabs-1" style="overflow-x: auto">
                        <ul class="nav">

                            <li><a href="@Url.Content("~/Report/ReportDate")"><span class=""></span>Báo cáo theo ngày</a></li>

                    <div id="tabs-2" style="overflow-x: auto; height: 290px">
                        <ul class="nav">

                            <li><a href="@Url.Content("~/Report/PetrolReport#tabs-2")"><span class=""></span>Báo cáo nhiên li?u</a></li>

        var index = $("#tabs div").index($("#tabs-1" ));
        $("#tabs").tabs("select", index);

Shortcut to comment out a block of code with sublime text

The shortcut to comment out or uncomment the selected text or current line:

  • Windows: Ctrl+/
  • Mac: Command ?+/
  • Linux: Ctrl+Shift+/

Alternatively, use the menu: Edit > Comment

For the block comment you may want to use:

  • Windows: Ctrl+Shift+/
  • Mac: Command ?+Option/Alt+/

Tesseract OCR simple example

In my case I had all these worked except for the correct character recognition.

But you need to consider these few things:

  • Use correct tessnet2 library
  • use correct tessdata language version
  • tessdata should be somewhere out of your application folder where you can put in full path in the init parameter. use ocr.Init(@"c:\tessdata", "eng", true);
  • Debugging will cause you headache. Then you need to update your app.config use this. (I can't put the xml code here. give me your email i will email it to you)

hope that this helps

Detect touch press vs long press vs movement?

I think you should implement GestureDetector.OnGestureListener as described in Using GestureDetector to detect Long Touch, Double Tap, Scroll or other touch events in Android and androidsnippets and then implement tap logic in onSingleTapUp and move logic in onScroll events

Check if an element has event listener on it. No jQuery

There is no JavaScript function to achieve this. However, you could set a boolean value to true when you add the listener, and false when you remove it. Then check against this boolean before potentially adding a duplicate event listener.

Possible duplicate: How to check whether dynamically attached event listener exists or not?

How to force a component's re-rendering in Angular 2?

I force reload my component using *ngIf.

All the components inside my container goes back to the full lifecycle hooks .

In the template :

<ng-container *ngIf="_reload">
    components here 

Then in the ts file :

public _reload = true;

private reload() {
    setTimeout(() => this._reload = false);
    setTimeout(() => this._reload = true);

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

In my case it turns out my
new server was running MySQL 5.5,
old server was running MySQL 5.6.
So I got this error when trying to import the .sql file I'd exported from my old server.

MySQL 5.5 does not support utf8mb4_unicode_520_ci, but
MySQL 5.6 does.

Updating to MySQL 5.6 on the new server solved collation the error !

If you want to retain MySQL 5.5, you can:
- make a copy of your exported .sql file
- replace instances of utf8mb4unicode520_ci and utf8mb4_unicode_520_ci
...with utf8mb4_unicode_ci
- import your updated .sql file.

Docker - Cannot remove dead container

Most likely, an error occurred when the daemon attempted to cleanup the container, and he is now stuck in this "zombie" state.

I'm afraid your only option here is to manually clean it up:

$ sudo rm -rf /var/lib/docker/<storage_driver>/11667ef16239.../

Where <storage_driver> is the name of your driver (aufs, overlay, btrfs, or devicemapper).

How to convert list data into json in java

You can use the following method which uses Jackson library

public static <T> List<T> convertToList(String jsonString, Class<T> target) {
    if(StringUtils.isEmpty(jsonString)) return List.of();

        return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
                constructCollectionType(List.class, target));
    } catch ( JsonProcessingException | JSONException e) {
        return List.of();

Parsing JSON in Java without knowing JSON format

Here is a sample I wrote shows how I parse a json and mess every number inside it:

public class JsonParser {

    public static Object parseAndMess(Object object) throws IOException {
        String json = JsonUtil.toJson(object);
        JsonNode jsonNode = parseAndMess(json);
        if(null != jsonNode)
            return JsonUtil.toObject(jsonNode, object.getClass());

        return null;

    public static JsonNode parseAndMess(String json) throws IOException {
        JsonNode rootNode = parse(json);
        return mess(rootNode, new Random());

    private static JsonNode parse(String json) throws IOException {
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        JsonNode rootNode = mapper.readTree(json);
        return rootNode;


    private static JsonNode mess(JsonNode rootNode, Random rand) throws IOException {
        if (rootNode instanceof ObjectNode) {
            Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
            while (fieldsIterator.hasNext()) {
                Map.Entry<String, JsonNode> field =;
                replaceObjectNode((ObjectNode) rootNode, field, rand);
        } else if (rootNode instanceof ArrayNode) {
            ArrayNode arrayNode = ((ArrayNode) rootNode);
            replaceArrayNode(arrayNode, rand);
        return rootNode;

    private static void replaceObjectNode(ObjectNode rootNode, Map.Entry<String, JsonNode> field, Random rand)
            throws IOException {
        JsonNode childNode = field.getValue();
        if (childNode instanceof IntNode) {
            (rootNode).put(field.getKey(), rand.nextInt(1000));
        } else if (childNode instanceof LongNode) {
            (rootNode).put(field.getKey(), rand.nextInt(1000000));
        } else if (childNode instanceof FloatNode) {
            (rootNode).put(field.getKey(), format(rand.nextFloat()));
        } else if (childNode instanceof DoubleNode) {
            (rootNode).put(field.getKey(), format(rand.nextFloat()));
        } else {
            mess(childNode, rand);

    private static void replaceArrayNode(ArrayNode arrayNode, Random rand) throws IOException {
        int arrayLength = arrayNode.size();
        if(arrayLength == 0)
        if (arrayNode.get(0) instanceof IntNode) {
            for (int i = 0; i < arrayLength; i++) {
                arrayNode.set(i, new IntNode(rand.nextInt(10000)));
        } else if (arrayNode.get(0) instanceof LongNode) {
            for (int i = 0; i < arrayLength; i++) {
        } else if (arrayNode.get(0) instanceof FloatNode) {
            for (int i = 0; i < arrayLength; i++) {
        } else if (arrayNode.get(0) instanceof DoubleNode) {
            for (int i = 0; i < arrayLength; i++) {
        } else {
            for (int i = 0; i < arrayLength; i++) {
                mess(arrayNode.get(i), rand);

    public static void print(JsonNode rootNode) throws IOException {

    private static double format(float a) {
        return Math.round(a * 10000.0) / 100.0;

Javascript Audio Play on click


<button onclick="play()">Play File</button>
<audio id="audio" src=""></audio>


let play = function(){document.getElementById("audio").play()}

Error - is not marked as serializable

Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:

Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable

Due to a class with an attribute IEnumerable<int> eg:

class MySessionData{
    public int ID;
    public IEnumerable<int> RelatedIDs; //This can be an issue

Originally the problem instance of MySessionData was set from a non-serializable list:

MySessionData instance = new MySessionData(){ 
    ID = 123,
    RelatedIDs = nonSerizableList.Select<int>(item => item.ID)

The cause here is the concrete class that the Select<int>(...) returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int> to resolve it.

RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();

Add line break within tooltips

Hi this code will work in all browser !!i used for new line in chrome and safari and ul li for IE

 function genarateMultiLIneCode(){
        var =values["a","b","c"];
        const liStart = '<li>';
              const liEnd = '</li>';
              const bullet = '&#8226; ';     
              var mergedString = ' ';
              const unOrderListStart='<ul>'
              const unOrderListEnd='</ul>'
              const fakeNewline = '&#013;&#010;';
              for (let i = 0; i < values.length; i++) {
                   mergedString += liStart + bullet + values[i] + liEnd + fakeNewline;
              const tempElement = document.createElement("div");
              tempElement.innerHTML = unOrderListStart + mergedString + unOrderListEnd;    
              return tempElement.innerText;

setImmediate vs. nextTick

In the comments in the answer, it does not explicitly state that nextTick shifted from Macrosemantics to Microsemantics.

before node 0.9 (when setImmediate was introduced), nextTick operated at the start of the next callstack.

since node 0.9, nextTick operates at the end of the existing callstack, whereas setImmediate is at the start of the next callstack

check out for tools and details

Sending and receiving data over a network using TcpClient

I have had luck using the socket object directly (rather than the TCP client). I create a Server object that looks something like this (I've edited some stuff such as exception handling out for brevity, but I hope that the idea comes across.)...

public class Server()
    private Socket sock;
    // You'll probably want to initialize the port and address in the
    // constructor, or via accessors, but to start your server listening
    // on port 8080 and on any IP address available on the machine...
    private int port = 8080;
    private IPAddress addr = IPAddress.Any;

    // This is the method that starts the server listening.
    public void Start()
        // Create the new socket on which we'll be listening.
        this.sock = new Socket(
        // Bind the socket to the address and port.
        sock.Bind(new IPEndPoint(this.addr, this.port));
        // Start listening.
        // Set up the callback to be notified when somebody requests
        // a new connection.
        this.sock.BeginAccept(this.OnConnectRequest, sock);

    // This is the method that is called when the socket recives a request
    // for a new connection.
    private void OnConnectRequest(IAsyncResult result)
        // Get the socket (which should be this listener's socket) from
        // the argument.
        Socket sock = (Socket)result.AsyncState;
        // Create a new client connection, using the primary socket to
        // spawn a new socket.
        Connection newConn = new Connection(sock.EndAccept(result));
        // Tell the listener socket to start listening again.
        sock.BeginAccept(this.OnConnectRequest, sock);

Then, I use a separate Connection class to manage the individual connection with the remote host. That looks something like this...

public class Connection()
    private Socket sock;
    // Pick whatever encoding works best for you.  Just make sure the remote 
    // host is using the same encoding.
    private Encoding encoding = Encoding.UTF8;

    public Connection(Socket s)
        this.sock = s;
        // Start listening for incoming data.  (If you want a multi-
        // threaded service, you can start this method up in a separate
        // thread.)

    // Call this method to set this connection's socket up to receive data.
    private void BeginReceive()
                this.dataRcvBuf, 0,
                new AsyncCallback(this.OnBytesReceived),

    // This is the method that is called whenever the socket receives
    // incoming bytes.
    protected void OnBytesReceived(IAsyncResult result)
        // End the data receiving that the socket has done and get
        // the number of bytes read.
        int nBytesRec = this.sock.EndReceive(result);
        // If no bytes were received, the connection is closed (at
        // least as far as we're concerned).
        if (nBytesRec <= 0)
        // Convert the data we have to a string.
        string strReceived = this.encoding.GetString(
            this.dataRcvBuf, 0, nBytesRec);

        // ...Now, do whatever works best with the string data.
        // You could, for example, look at each character in the string
        // one-at-a-time and check for characters like the "end of text"
        // character ('\u0003') from a client indicating that they've finished
        // sending the current message.  It's totally up to you how you want
        // the protocol to work.

        // Whenever you decide the connection should be closed, call 
        // sock.Close() and don't call sock.BeginReceive() again.  But as long 
        // as you want to keep processing incoming data...

        // Set up again to get the next chunk of data.
            this.dataRcvBuf, 0,
            new AsyncCallback(this.OnBytesReceived),


You can use your Connection object to send data by calling its Socket directly, like so...

this.sock.Send(this.encoding.GetBytes("Hello to you, remote host."));

As I said, I've tried to edit the code here for posting, so I apologize if there are any errors in it.

psql: server closed the connection unexepectedly

this is an old post but...

just surprised that nobody talk about pg_hba file as it can be a good reason to get this error code.

Check here for those who forgot to configure it:

best way to get the key of a key/value javascript object

best way to get key/value of object.

let obj = {_x000D_
        'key1': 'value1',_x000D_
        'key2': 'value2',_x000D_
        'key3': 'value3',_x000D_
        'key4': 'value4'_x000D_
    Object.keys(obj).map(function(k){ _x000D_
    console.log("key with value: "+k +" = "+obj[k])    _x000D_

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

How to compare two vectors for equality element by element in C++?

Your code (vector1 == vector2) is correct C++ syntax. There is an == operator for vectors.

If you want to compare short vector with a portion of a longer vector, you can use theequal() operator for vectors. (documentation here)

Here's an example:

using namespace std;

if( equal(vector1.begin(), vector1.end(), vector2.begin()) )

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

What's the difference between "static" and "static inline" function?

One difference that's not at the language level but the popular implementation level: certain versions of gcc will remove unreferenced static inline functions from output by default, but will keep plain static functions even if unreferenced. I'm not sure which versions this applies to, but from a practical standpoint it means it may be a good idea to always use inline for static functions in headers.

what is right way to do API call in react js?

In this case, you can do ajax call inside componentDidMount, and then update state

export default class UserList extends React.Component {
  constructor(props) {

    this.state = {person: []};

  componentDidMount() {

  UserList() {
      .then(({ results }) => this.setState({ person: results }));

  render() {
    const persons =, i) => (
        <h1>{ }</h1>
        <span>{ item.cell }, { }</span>

    return (
      <div id="layout-content" className="layout-content-wrapper">
        <div className="panel-list">{ persons }</div>

What is the equivalent of Java static methods in Kotlin?

All static member and function should be inside companion block

  companion object {
    fun main(args: Array<String>) {

    fun staticMethod() {

Convert List<Object> to String[] in Java

You could use toArray() to convert into an array of Objects followed by this method to convert the array of Objects into an array of Strings:

Object[] objectArray = lst.toArray();
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

How do you properly use WideCharToMultiByte

Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.

// Convert a wide Unicode string to an UTF8 string
std::string utf8_encode(const std::wstring &wstr)
    if( wstr.empty() ) return std::string();
    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string strTo( size_needed, 0 );
    WideCharToMultiByte                  (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
    return strTo;

// Convert an UTF8 string to a wide Unicode String
std::wstring utf8_decode(const std::string &str)
    if( str.empty() ) return std::wstring();
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
    std::wstring wstrTo( size_needed, 0 );
    MultiByteToWideChar                  (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
    return wstrTo;

Change PictureBox's image to image from my resources?

You must specify the full path of the resource file as the name of 'image within the resources of your application, see example below.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    PictureBox1.Image = My.Resources.Chrysanthemum
End Sub

In the path assigned to the Image property after MyResources specify the name of the resource.

But before you do whatever you have to import in the resource section of your application from an image file exists or it can create your own.


Reading integers from binary file in Python

As you are reading the binary file, you need to unpack it into a integer, so use struct module for that

import struct
fin = open("hi.bmp", "rb")
firm =  
file_size, = struct.unpack("i",

Random String Generator Returning Same String

Combining the answer by "Pushcode" and the one using the seed for the random generator. I needed it to create a serie of pseudo-readable 'words'.

private int RandomNumber(int min, int max, int seed=0)
    Random random = new Random((int)DateTime.Now.Ticks + seed);
    return random.Next(min, max);

Easy login script without database

***LOGIN script that doesnt link to a database or external file. Good for a global password -

Place on Login form page - place this at the top of the login page - above everything else***



if(strtolower($_POST["username"])=="ChangeThis" && $_POST["password"]=="ChangeThis"){
$_SESSION['logged_in'] = TRUE;
header("Location: ./YourPageAfterLogin.php");

}else {
$error= "Login failed !";

*Login on following pages - Place this at the top of every page that needs to be protected by login. this checks the session and if a user name and password has *

if(!isset($_SESSION['logged_in']) OR $_SESSION['logged_in'] != TRUE){

header("Location: ./YourLoginPage.php");

Creating a new user and password with Ansible

Well I'am totally late to party :) I had the need for ansible play that creates multiple local users with randoms passwords. This what I came up with, used some of examples from top and put them together with some changes.


# create_user playbook

- hosts: all
  become: True
  user: root
#Create following user
    - test24
    - test25
#with group
   group: wheel
    - create-user-with-password


- name: Generate password for new user
  local_action: shell pwgen -s -N 1 20
  register: user_password
  with_items: "{{ users }}"
  run_once: true

- name: Generate encrypted password
  local_action: shell python -c 'import crypt; print(crypt.crypt( "{{ item.stdout }}", crypt.mksalt(crypt.METHOD_SHA512)))'
  register: encrypted_user_password
  with_items: "{{ user_password.results }}"
  run_once: true

- name: Create new user with group
    name: "{{ item }}"
    groups: "{{ group }}"
    shell: /bin/bash
    append: yes
    createhome: yes
    comment: 'Created with ansible'
    - "{{ users }}"
  register: user_created

- name: Update user Passwords
    name: '{{ item.0 }}'
    password: '{{ item.1.stdout }}'
    - "{{ users }}"
    - "{{ encrypted_user_password.results }}"
  when: user_created.changed

- name: Force user to change the password at first login
  shell: chage -d 0 "{{ item }}"
    - "{{ users }}"
  when: user_created.changed

- name: Save Passwords Locally
  become: no
  local_action: copy content={{ item.stdout }} dest=./{{ item.item }}.txt
  with_items: "{{ user_password.results }}"
  when: user_created.changed

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

From this post:

To get the entire PC CPU and Memory usage:

using System.Diagnostics;

Then declare globally:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

Then to get the CPU time, simply call the NextValue() method:


This will get you the CPU usage

As for memory usage, same thing applies I believe:

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Memory", "Available MBytes");

Then to get the memory usage, simply call the NextValue() method:


For a specific process CPU and Memory usage:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Process", "% Processor Time",              

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Process", "Working Set",

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?

To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters

The difference between Processor\% Processor Time and Process\% Processor Time is Processor is from the PC itself and Process is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters

An alternative to using the Performance Counter

Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.

Centering a background image, using CSS

background-position:center center;

Does not vertically center the background image when using a html 4.01 'STRICT' doctype.


background-attachment: fixed;

Should fix the problem

(So Alexander is right)

Request Monitoring in Chrome

I know this is an old thread but I thought I would chime in.

Chrome currently has a solution built in.

  1. Use CTRL+SHIFT+I (or navigate to Current Page Control > Developer > Developer Tools. In the newer versions of Chrome, click the Wrench icon > Tools > Developer Tools.) to enable the Developer Tools.
  2. From within the developer tools click on the Network button. If it isn't already, enable it for the session or always.
  3. Click the "XHR" sub-button.
  4. Initiate an AJAX call.
  5. You will see items begin to show up in the left column under "Resources".
  6. Click the resource and there are 2 tabs showing the headers and return content.

Make a DIV fill an entire table cell

I'm not sure what you want to do but you might try this one:

<td width="661" valign="top"><div>Content for New Div Tag Goes Here</div></td>

WebView and Cookies on Android

If you are using Android Lollipop i.e. SDK 21, then:


won't work. You need to use:

CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

I ran into same issue and the above line worked as a charm.

scroll image with continuous scrolling using marquee tag

Marquee (<marquee>) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!

Creating a LINQ select from multiple tables

If the anonymous type causes trouble for you, you can create a simple data class:

public class PermissionsAndPages
     public ObjectPermissions Permissions {get;set}
     public Pages Pages {get;set}

and then in your query:

select new PermissionsAndPages { Permissions = op, Page = pg };

Then you can pass this around:

return queryResult.SingleOrDefault(); // as PermissionsAndPages

No Activity found to handle Intent : android.intent.action.VIEW

I have two ideas:

First: if you want to play 3gp file you should use mime types "audio/3gpp" or "audio/mpeg"

And second: you can try use method setData(data) for intent without any mime type.

Padding characters in printf

Trivial (but working) solution:

echo -e "---------------------------- [UP]\r$PROC_NAME "

Using subprocess to run Python script on Windows

Yes subprocess.Popen(cmd, ..., shell=True) works like a charm. On Windows the .py file extension is recognized, so Python is invoked to process it (on *NIX just the usual shebang). The path environment controls whether things are seen. So the first arg to Popen is just the name of the script.

subprocess.Popen(['', 'arg1', ...], ..., shell=True)

Is the Javascript date object always one day off?

There are several crazy things that happen with a JS DATE object that convert strings, for example consider the following date you provided

Note: The following examples may or may not be ONE DAY OFF depending on YOUR timezone and current time.

new Date("2011-09-24"); // Year-Month-Day
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.

However, if we rearrange the string format to Month-Day-Year...

new Date("09-24-2011");
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

Another strange one

new Date("2011-09-24");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF AS BEFORE.

new Date("2011/09/24"); // change from "-" to "/".
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

We could easily change hyphens in your date "2011-09-24" when making a new date

new Date("2011-09-24".replace(/-/g, '\/')); // => "2011/09/24".
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

What if we had a date string like "2011-09-24T00:00:00"

new Date("2011-09-24T00:00:00");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.

Now change hyphen to forward slash as before; what happens?

new Date("2011/09/24T00:00:00");
// => Invalid Date.

I typically have to manage the date format 2011-09-24T00:00:00 so this is what I do.

new Date("2011-09-24T00:00:00".replace(/-/g, '\/').replace(/T.+/, ''));
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.


If you provide separate arguments to the Date constructor you can get other useful outputs as described below

Note: arguments can be of type Number or String. I'll show examples with mixed values.

Get the first month and day of a given year

new Date(2011, 0); // Normal behavior as months in this case are zero based.
// => Sat Jan 01 2011 00:00:00 GMT-0700 (MST)

Get the last month and day of a year

new Date((2011 + 1), 0, 0); // The second zero roles back one day into the previous month's last day.
// => Sat Dec 31 2011 00:00:00 GMT-0700 (MST)

Example of Number, String arguments. Note the month is March because zero based months again.

new Date(2011, "02"); 
// => Tue Mar 01 2011 00:00:00 GMT-0700 (MST)

If we do the same thing but with a day of zero, we get something different.

new Date(2011, "02", 0); // Again the zero roles back from March to the last day of February.
// => Mon Feb 28 2011 00:00:00 GMT-0700 (MST)

Adding a day of zero to any year and month argument will get the last day of the previous month. If you continue with negative numbers you can continue rolling back another day

new Date(2011, "02", -1);
// => Sun Feb 27 2011 00:00:00 GMT-0700 (MST)

console.log(result) returns [object Object]. How do I get

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

How to show text on image when hovering?

.container {_x000D_
  position: relative;_x000D_
  width: 50%;_x000D_
.image {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
.overlay {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  opacity: 0;_x000D_
  transition: .5s ease;_x000D_
  background-color: #008CBA;_x000D_
.container:hover .overlay {_x000D_
  opacity: 1;_x000D_
.text {_x000D_
  color: white;_x000D_
  font-size: 20px;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  -ms-transform: translate(-50%, -50%);_x000D_
<!DOCTYPE html>_x000D_
<div class="container">_x000D_
  <img src="" alt="Avatar" class="image">_x000D_
  <div class="overlay">_x000D_
    <div class="text">Hello World</div>_x000D_

Reference Link W3schools with multiple styles

jquery function setInterval

// simple example using the concept of setInterval

var g = $('.jumping');
function blink(){
  g.animate({ 'left':'50px' 

TypeError: string indices must be integers, not str // working with dict

I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:

from itertools import chain

def involved(courses, person):
    courses_info = chain.from_iterable(x.values() for x in courses.values())
    return filter(lambda x: x['teacher'] == person, courses_info)

print involved(courses, 'Dave')

The first thing I do is getting the list of the courses and then filter by teacher's name.

Change the On/Off text of a toggle button Android

You can use the following to set the text from the code:

// Sets the text for when the button is first created.

// Sets the text for when the button is not in the checked state.

// Sets the text for when the button is in the checked state.

To set the text using xml, use the following:

android:textOff="The text for the button when it is not checked."
android:textOn="The text for the button when it is checked." 

This information is from here

Can HTML be embedded inside PHP "if" statement?


<?  if($my_name == 'someguy') { ?>
<?  } ?>

Cannot set some HTTP headers when using System.Net.WebRequest

All the previous answers describe the problem without providing a solution. Here is an extension method which solves the problem by allowing you to set any header via its string name.


HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.SetRawHeader("content-type", "application/json");

Extension Class

public static class HttpWebRequestExtensions
    static string[] RestrictedHeaders = new string[] {

    static Dictionary<string, PropertyInfo> HeaderProperties = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);

    static HttpWebRequestExtensions()
        Type type = typeof(HttpWebRequest);
        foreach (string header in RestrictedHeaders)
            string propertyName = header.Replace("-", "");
            PropertyInfo headerProperty = type.GetProperty(propertyName);
            HeaderProperties[header] = headerProperty;

    public static void SetRawHeader(this HttpWebRequest request, string name, string value)
        if (HeaderProperties.ContainsKey(name))
            PropertyInfo property = HeaderProperties[name];
            if (property.PropertyType == typeof(DateTime))
                property.SetValue(request, DateTime.Parse(value), null);
            else if (property.PropertyType == typeof(bool))
                property.SetValue(request, Boolean.Parse(value), null);
            else if (property.PropertyType == typeof(long))
                property.SetValue(request, Int64.Parse(value), null);
                property.SetValue(request, value, null);
            request.Headers[name] = value;


I wrote a wrapper for HttpWebRequest and didn't want to expose all 13 restricted headers as properties in my wrapper. Instead I wanted to use a simple Dictionary<string, string>.

Another example is an HTTP proxy where you need to take headers in a request and forward them to the recipient.

There are a lot of other scenarios where its just not practical or possible to use properties. Forcing the user to set the header via a property is a very inflexible design which is why reflection is needed. The up-side is that the reflection is abstracted away, it's still fast (.001 second in my tests), and as an extension method feels natural.


Header names are case insensitive per the RFC,

Node.js project naming conventions for files & folders

Most people use camelCase in JS. If you want to open-source anything, I suggest you to use this one :-)

Check for file exists or not in sql server?

Create a function like so:

CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
     DECLARE @result INT
     EXEC master.dbo.xp_fileexist @path, @result OUTPUT
     RETURN cast(@result as bit)

Edit your table and add a computed column (IsExists BIT). Set the expression to:


Then just select:

SELECT * FROM dbo.MyTable where IsExists = 1


To use the function outside a computed column:

select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable


If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.

And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.

embedding image in html email

One additional hint to Pavel Perna's post which helped me very much (cannot comment with my reputation, that's why I post this as answer): In some versions of Microsoft Exchange, the inline contents disposition is removed (see this post by Microsoft). The image is simply not part in the mail the user sees in Outlook. As a workaround, use "Content-Disposition: attachement" instead. Outlook 2016 won't show images as attachement that are used in the mail message, although they use the "Content-Disposition: attachement".

passing form data to another HTML page

<form action="display.html" method="post">_x000D_
    <input type="text" name="serialNumber" />_x000D_
    <input type="submit" value="Submit" />_x000D_

In display.html you should add the following code.

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));

var sn = getParameterByName('serialNumber');

document.getElementById("write").innerHTML = sn;


Twitter Bootstrap Modal Form Submit

Old, but maybe useful for readers to have a full example of how use modal.

I do like following ( working example jsfiddle ) :



$.post('getpostcodescript.php', $('form').serialize(), function(data, status, xhr)
        // do something here with response;;;;
    .done(function() {
        // do something here if done ;
        alert( "saved" );
    .fail(function() {
        // do something here if there is an error ;
        alert( "error" );
    .always(function() {
        // maybe the good state to close the modal
        alert( "finished" );
        // Set a timeout to hide the element again
        }, 3000);

To deal easier with modals, I recommend using eModal, which permit to go faster on base use of bootstrap 3 modals.

How do I set Java's min and max heap size through environment variables?

I think your only option is to wrap java in a script that substitutes the environment variables into the command line

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

I resolved the same issue using next sql and restarting MySQL server:

update mysql.user set Select_priv='Y',Insert_priv='Y',Update_priv='Y',Delete_priv='Y',Create_priv='Y',Drop_priv='Y',Reload_priv='Y',Shutdown_priv='Y',Process_priv='Y',File_priv='Y',Grant_priv='Y',References_priv='Y',Index_priv='Y',Alter_priv='Y',Show_db_priv='Y',Super_priv='Y',Create_tmp_table_priv='Y',Lock_tables_priv='Y',Execute_priv='Y',Repl_slave_priv='Y',Repl_client_priv='Y',Create_view_priv='Y',Show_view_priv='Y',Create_routine_priv='Y',Alter_routine_priv='Y',Create_user_priv='Y',Event_priv='Y',Trigger_priv='Y',Create_tablespace_priv='Y'
where user='root';

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

What you're checking


but there's no variable name called "submit". well i want you to understand why it doesn't works. lets imagine if you give your submit button name delete <input type="submit" value="Submit" name="delete" /> and check if(isset($_POST['delete'])) then it works in this code you didn't give any name to submit button and checking its exist or not with isset(); function so php didn't find any variable like "submit" so its not working now try this :

<input type="submit" name="submit" value="Submit" />

Using Chrome, how to find to which events are bound to an element

Edit: in lieu of my own answer, this one is quite excellent: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)

Google Chromes developer tools has a search function built into the scripts section

If you are unfamiliar with this tool: (just in case)

  • right click anywhere on a page (in chrome)
  • click 'Inspect Element'
  • click the 'Scripts' tab
  • Search bar in the top right

Doing a quick search for the #ID should take you to the binding function eventually.

Ex: searching for #foo would take you to

$('#foo').click(function(){ alert('bar'); })

enter image description here

How do I get the result of a command in a variable in windows?

@echo off
setlocal EnableDelayedExpansion
FOR /F "tokens=1 delims= " %%i IN ('echo hola') DO (
    set TXT=%%i
echo 'TXT: %TXT%'

the result is 'TXT: hola'

jQuery trigger file input

Correct code:

    .upload input[type='file']{
        position: absolute;
        float: left;
        opacity: 0; /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
        -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; /* For IE5 - 7 */
        filter: alpha(opacity=0);
        width: 100px; height: 30px; z-index: 51
    .upload input[type='button']{
        width: 100px;
        height: 30px;
        z-index: 50;
    .upload input[type='submit']{
        display: none;
        width: 100px; height: 30px
<div class="upload">
    <input type='file' ID="flArquivo" onchange="upload();" />
    <input type="button" value="Selecionar" onchange="open();" />
    <input type='submit' ID="btnEnviarImagem"  />

<script type="text/javascript">
    function open() {
    function upload() {

What are the differences between WCF and ASMX web services?

There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.

  • Its true that novice web service developers will get started easily in asmx web services. Visual Studio does all the work for them and readily creates a Hello World project.
  • But if you can learn WCF (which off course wont take much time) then you can get to see that WCF is also quite simple, and you can go ahead easily.
  • Its important to remember that these said complexities in WCF are actually attributed to the beautiful features that it brings along with it. There are addressing, bindings, contracts and endpoints, services & clients all mentioned in the config file. The beauty is your business logic is segregated and maintained safely. Tomorrow if you need to change the binding from basicHttpBinding to netTcpBinding you can easily create a binding in config file and use it. So all the changes related to clients, communication channels, bindings etc are to be done in the configuration leaving the business logic safe & intact, which makes real good sense.
  • WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
  • Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. You can host your WCF services in Console, Windows Services, IIS & WAS, which are again different ways of creating new projects in Visual Studio.
  • ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
  • You will always like to use Visual Studio for NET 4.0 or 4.5 as it makes life easy while creating WCF services.
  • The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer. That's why WCF performs way better than other communication technology counterparts from .NET like asmx, .NET remoting etc.

Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!

Best way to save a trained model in PyTorch?

If you want to save the model and wants to resume the training later:

Single GPU: Save:

state = {
        'epoch': epoch,
        'state_dict': model.state_dict(),
        'optimizer': optimizer.state_dict(),


checkpoint = torch.load('checkpoint.t7')
epoch = checkpoint['epoch']

Multiple GPU: Save

state = {
        'epoch': epoch,
        'state_dict': model.module.state_dict(),
        'optimizer': optimizer.state_dict(),


checkpoint = torch.load('checkpoint.t7')
epoch = checkpoint['epoch']

#Don't call DataParallel before loading the model otherwise you will get an error

model = nn.DataParallel(model) #ignore the line if you want to load on Single GPU

How to read pdf file and write it to outputStream


public class FileRead {

    public static void main(String[] args) throws IOException {

        File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");

        OutputStream oos = new FileOutputStream("test.pdf");

        byte[] buf = new byte[8192];

        InputStream is = new FileInputStream(f);

        int c = 0;

        while ((c =, 0, buf.length)) > 0) {
            oos.write(buf, 0, c);




The easiest way so far. Hope this helps.

Using Pip to install packages to Anaconda Environment

All above answers are mainly based on use of virtualenv. I just have fresh installation of anaconda3 and don't have any virtualenv installed in it. So, I have found a better alternative to it without wondering about creating virtualenv.

If you have many pip and python version installed in linux, then first run below command to list all installed pip paths.

whereis pip

You will get something like this as output.

pip: /usr/bin/pip /home/prabhakar/anaconda3/bin/pip /usr/share/man/man1/pip.1.gz

Copy the path of pip which you want to use to install your package and paste it after sudo replacing /home/prabhakar/anaconda3/bin/pip in below command.

sudo /home/prabhakar/anaconda3/bin/pip install <package-name>

This worked pretty well for me. If you have any problem installing, please comment.

How to set the part of the text view is clickable

i coded an example to solve your question in Kotlin.

This is the Code:

    val completeText = getString(R.string.terms_description)
    val textToFind = getString(R.string.show_terms)
    val spannableString: Spannable = SpannableString(completeText)
    val startFocus = completeText.indexOf(textToFind)
    val endFocus = startFocus + textToFind.length

    spannableString.setSpan(object: ClickableSpan() {
        override fun onClick(p0: View) {
    }, startFocus, endFocus, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    show_terms.text = spannableString
    show_terms.movementMethod = LinkMovementMethod.getInstance();
    show_terms.highlightColor = Color.TRANSPARENT;

This is the XML



This is how it looks

enter image description here

How to execute a stored procedure inside a select query

Create a dynamic view and get result from it.......

CREATE PROCEDURE dbo.usp_userwise_columns_value
    @userid BIGINT
        DECLARE @maincmd NVARCHAR(max);
        DECLARE @columnlist NVARCHAR(max);
        DECLARE @columnname VARCHAR(150);
        DECLARE @nickname VARCHAR(50);

        SET @maincmd = '';
        SET @columnname = '';
        SET @columnlist = '';
        SET @nickname = '';

            SELECT columnname , nickname
            FROM dbo.v_userwise_columns 
            WHERE userid = @userid

        IF @@ERROR <> 0

        INTO @columnname, @nickname

        WHILE @@FETCH_STATUS = 0
                SET @columnlist = @columnlist + @columnname + ','

                INTO @columnname, @nickname

        IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'v_userwise_columns_value')
                SET @maincmd = 'CREATE VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , ' 
                            + CHAR(39) + @nickname + CHAR(39) + ' as nickname, ' 
                            + @columnlist + ' compcode FROM dbo.SJOTran '
                SET @maincmd = 'ALTER VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , ' 
                            + CHAR(39) + @nickname + CHAR(39) + ' as nickname, ' 
                            + @columnlist + ' compcode FROM dbo.SJOTran '

        EXECUTE sp_executesql @maincmd

SELECT * FROM dbo.v_userwise_columns_value

Is there any way to kill a Thread?

Here's yet another way to do it, but with extremely clean and simple code, that works in Python 3.7 in 2021:

import ctypes 

def kill_thread(thread):
    thread: a threading.Thread object
    thread_id = thread.ident
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit))
    if res > 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
        print('Exception raise failure')

Adapted from here:

How do I know if jQuery has an Ajax request pending?

 $(function () {
        function checkPendingRequest() {
            if ($.active > 0) {
                window.setTimeout(checkPendingRequest, 1000);
                //Mostrar peticiones pendientes ejemplo: $("#control").val("Peticiones pendientes" + $.active);
            else {

                alert("No hay peticiones pendientes");


        window.setTimeout(checkPendingRequest, 1000);

What is the correct format to use for Date/Time in an XML file

The XmlConvert class provides these kinds of facilities. About DateTimes, in particular, be careful about obsolete methods. See also:

Why AVD Manager options are not showing in Android Studio

It happens when there is no runnable module for Android App in your project. Creating new project definitely solves this.

You can check this using Run > Edit Configurations > Adding Android App. If there is not runnable Android App module then you can't see "AVD Manager" in the menu.


I had the same problem which is solved using the following:

Try to rename all the folders to not to be more than 8 characters and without spaces.

Descending order by date filter in AngularJs

Perhaps this can be useful for someone:

In my case, I was getting an array of objects, each containing a date set by Mongoose.

I used:

ng-repeat="comment in post.comments | orderBy : sortComment : true"

And defined the function:

$scope.sortComment = function(comment) {
    var date = new Date(comment.created);
    return date;

This worked for me.

Could not connect to SMTP host:, port: 465, response: -1

Port 465 is for "smtp over SSL".

[...] For example, use
    props.put("mail.smtp.port", "888");
to set the mail.smtp.port property, which is of type int.

Note that if you're using the "smtps" protocol to access SMTP over SSL, 
all the properties would be named "mail.smtps.*"

What I can do to resolve "1 commit behind master"?

If the message is "n commits behind master."

You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.


git checkout master
git pull        #this will update your local master
git checkout yourDevBranch
git rebase master

there can be some merge conflicts which you have to resolve.

How to set limits for axes in ggplot2 R plots?

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000))


coord_cartesian(xlim = c(-5000, 5000)) 

Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.

You can also use the shorthand function xlim (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000)

For more information check the description of coord_cartesian.

The RStudio cheatsheet for ggplot2 makes this quite clear visually. Here is a small section of that cheatsheet:

enter image description here

Distributed under CC BY.

Adding a custom header to HTTP request using angular.js

If you want to add your custom headers to ALL requests, you can change the defaults on $httpProvider to always add this header…

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.headers.common = { 
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json;odata=verbose'

SQL DELETE with JOIN another table for WHERE condition

Try this sample SQL scripts for easy understanding,







Your case is:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=

I had this issue when I upgraded to v3.0.0.preview4, so a downgrade to a stable version fixed this.

The ternary (conditional) operator in C

Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const correctness in a compact way.

Something like this:

const int n = (x != 0) ? 10 : 20;

so basically n is a const whose initial value is dependent on a condition statement. The easiest alternative is to make n not a const, this would allow an ordinary if to initialize it. But if you want it to be const, it cannot be done with an ordinary if. The best substitute you could make would be to use a helper function like this:

int f(int x) {
    if(x != 0) { return 10; } else { return 20; }

const int n = f(x);

but the ternary if version is far more compact and arguably more readable.

How can I align text in columns using Console.WriteLine?

I really like those libraries mentioned here but I had an idea that could be simpler than just padding or doing tons of string manipulations,

You could just manually set your cursor using the maximum string length of your data. Here's some code to get the idea (not tested):

var column1[] = {"test", "longer test", "etc"}
var column2[] = {"data", "more data", "etc"}
var offset = strings.OrderByDescending(s => s.Length).First().Length;
for (var i = 0; i < column.Length; i++) {
    Console.CursorLeft = offset + 1;

you could easily extrapolate if you have more rows.

Convert Iterator to ArrayList

List result = new ArrayList();
while (i.hasNext()){

C# Help reading foreign characters using StreamReader

File.OpenText() always uses an UTF-8 StreamReader implicitly. Create your own StreamReader instance instead and specify the desired encoding. like

using (StreamReader reader =  new StreamReader(@"C:\test.txt", Encoding.Default)
 // ...

Android - Start service on boot

Just to make searching easier, as mentioned in comments, this is not possible since 3.1

Bootstrap radio button "checked" flag

Assuming you want a default button checked.

<div class="row">
    <h1>Radio Group #2</h1>
    <label for="year" class="control-label input-group">Year</label>
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="radio" name="year" value="2011">2011
        <label class="btn btn-default">
            <input type="radio" name="year" value="2012">2012
        <label class="btn btn-default active">
            <input type="radio" name="year" value="2013" checked="">2013

Add the active class to the button (label tag) you want defaulted and checked="" to its input tag so it gets submitted in the form by default.

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

if (x) 

coerces x using JavaScript's internal toBoolean (

x == false

coerces both sides using internal toNumber coercion ( or toPrimitive for objects (

For full details see

Enable vertical scrolling on textarea

You can try adding:

    height: 100px;
    max-height: 100px;  

Rotate an image in image source in html

You can do this:

<img src="your image" style="transform:rotate(90deg);">

it is much easier.

How can I create a dynamic button click event on a dynamic button?

Simply add the eventhandler to the button when creating it.

 button.Click += new EventHandler(this.button_Click);

void button_Click(object sender, System.EventArgs e)
//your stuff...

What is causing this error - "Fatal error: Unable to find local grunt"

I had the same issue in Vagrant.

I have used sudo to run the command to install.

sudo npm install -g grunt-cli

It worked for me.

Do you get charged for a 'stopped' instance on EC2?

Short answer - no.

You will only be charged for the time that your instance is up and running, in hour increments. If you are using other services in conjunction you may be charged for those but it would be separate from your server instance.

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    return "note";

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}


Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>