Programs & Examples On #Mvchtmlstring

Display encoded html with razor

I store encoded HTML in the database.

Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:

<div class='content'>
    @Model.Content
</div>

How to use ternary operator in razor (specifically on HTML attributes)?

A simpler version, for easy eyes!

@(true?"yes":"no")

What is an MvcHtmlString and when should I use it?

You would use an MvcHtmlString if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.

Joining three tables using MySQL

SELECT 
employees.id, 
CONCAT(employees.f_name," ",employees.l_name) AS   'Full Name', genders.gender_name AS 'Sex', 
depts.dept_name AS 'Team Name', 
pay_grades.pay_grade_name AS 'Band', 
designations.designation_name AS 'Role' 
FROM employees 
LEFT JOIN genders ON employees.gender_id = genders.id 
LEFT JOIN depts ON employees.dept_id = depts.id 
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id 
LEFT JOIN designations ON employees.designation_id = designations.id 
ORDER BY employees.id;

You can JOIN multiple TABLES like this example above.

Incrementing in C++ - When to use x++ or ++x?

I agree with @BeowulfOF, though for clarity I would always advocate splitting the statements so that the logic is absolutely clear, i.e.:

i++;
x += i;

or

x += i;
i++;

So my answer is if you write clear code then this should rarely matter (and if it matters then your code is probably not clear enough).

Spring Data JPA and Exists query

Spring Data JPA 1.11 now supports the exists projection in repository query derivation.

See documentation here.

In your case the following will work:

public interface MyEntityRepository extends CrudRepository<MyEntity, String> {  
    boolean existsByFoo(String foo);
}

Flask Download a File

To download file on flask call. File name is Examples.pdf When I am hitting 127.0.0.1:5000/download it should get download.

Example:

from flask import Flask
from flask import send_file
app = Flask(__name__)

@app.route('/download')
def downloadFile ():
    #For windows you need to use drive name [ex: F:/Example.pdf]
    path = "/Examples.pdf"
    return send_file(path, as_attachment=True)

if __name__ == '__main__':
    app.run(port=5000,debug=True) 

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

This expression will force the first letter to be alphabetic and the remaining characters to be alphanumeric or any of the following special characters: @,#,%,&,*

^[A-Za-z][A-Za-z0-9@#%&*]*$

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

How to scale Docker containers in production

A sensible approach to scaling Docker could be:

  1. Each service will be a docker container
  2. Intra container service discovery managed through links (new feature from docker 0.6.5)
  3. Containers will be deployed through Dokku
  4. Applications will be managed through Shipyard which in its turn is using hipache

Another docker open sourced project from Yandex:

Your branch is ahead of 'origin/master' by 3 commits

Came across this issue after I merged a pull request on Bitbucket.

Had to do

git fetch

and that was it.

How to throw an exception in C?

In C you could use the combination of the setjmp() and longjmp() functions, defined in setjmp.h. Example from Wikipedia

#include <stdio.h>
#include <setjmp.h>

static jmp_buf buf;

void second(void) {
    printf("second\n");         // prints
    longjmp(buf,1);             // jumps back to where setjmp 
                                //   was called - making setjmp now return 1
}

void first(void) {
    second();
    printf("first\n");          // does not print
}

int main() {   
    if ( ! setjmp(buf) ) {
        first();                // when executed, setjmp returns 0
    } else {                    // when longjmp jumps back, setjmp returns 1
        printf("main");         // prints
    }

    return 0;
}

Note: I would actually advise you not to use them as they work awful with C++ (destructors of local objects wouldn't get called) and it is really hard to understand what is going on. Return some kind of error instead.

change directory in batch file using variable

simple way to do this... here are the example

cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause

this will mount the ISO image to the specific drive...use

How do I set/unset a cookie with jQuery?

There is no need to use jQuery particularly to manipulate cookies.

From QuirksMode (including escaping characters)

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ')
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0)
            return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

Take a look at

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

Collections.emptyList() returns a List<Object>?

You want to use:

Collections.<String>emptyList();

If you look at the source for what emptyList does you see that it actually just does a

return (List<T>)EMPTY_LIST;

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Route [login] not defined

Try to add this at Header of your request: Accept=application/json postman or insomnia add header

dlib installation on Windows 10

As you can see many answers above, But i would like to post a quick solution which works for sure in Anaconda3. I haven't chosen Visual Studio as it consumes lot of memory.

Please follow the below steps.

Step 1:
Install windows cmake.msi and configure environment variable
Step 2:
Create a conda environment, and install cmake using the below command.
pip install cmake
Step 3:
conda install -c conda-forge dlib

Note you can find few other dlib packages, but the above one will works perfectly with this procedure.

dlib will be successfully installed.

Convert multiple rows into one with comma as separator

 select
   distinct  
    stuff((
        select ',' + u.username
        from users u
        where u.username = username
        order by u.username
        for xml path('')
    ),1,1,'') as userlist
from users
group by username

had a typo before, the above works

SHA-256 or MD5 for file integrity

Every answer seems to suggest that you need to use secure hashes to do the job but all of these are tuned to be slow to force a bruteforce attacker to have lots of computing power and depending on your needs this may not be the best solution.

There are algorithms specifically designed to hash files as fast as possible to check integrity and comparison (murmur, XXhash...). Obviously these are not designed for security as they don't meet the requirements of a secure hash algorithm (i.e. randomness) but have low collision rates for large messages. This features make them ideal if you are not looking for security but speed.

Examples of this algorithms and comparison can be found in this excellent answer: Which hashing algorithm is best for uniqueness and speed?.

As an example, we at our Q&A site use murmur3 to hash the images uploaded by the users so we only store them once even if users upload the same image in several answers.

Does Java have something like C#'s ref and out keywords?

java has no standard way of doing it. Most swaps will be made on the list that is packaged in the class. but there is an unofficial way to do it:

package Example;

import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;



 public class Test{


private static <T> void SetValue(T obj,T value){
    try {
        Field f = obj.getClass().getDeclaredField("value");
        f.setAccessible(true);
        f.set(obj,value);
        } catch (IllegalAccessException | IllegalArgumentException | 
            NoSuchFieldException | SecurityException ex) {
            Logger.getLogger(CautrucjavaCanBan.class.getName()).log(Level.SEVERE, 
       null, ex);
        }
}
private  static  void permutation(Integer a,Integer b){
    Integer tmp = new Integer(a);
    SetValue(a, b);
    SetValue(b, tmp);
}
 private  static  void permutation(String a,String b){
    char[] tmp = a.toCharArray();
    SetValue(a, b.toCharArray());
    SetValue(b, tmp);
}
public static void main(String[] args) {
    {
        Integer d = 9;
        Integer e = 8;
        HoanVi(d, e);
        System.out.println(d+" "+ e);
    }
    {
        String d = "tai nguyen";
        String e = "Thai nguyen";
        permutation(d, e);
        System.out.println(d+" "+ e);
    }
}

}

NoClassDefFoundError - Eclipse and Android

Acutally you have reached the infamous 64k limit issue, you need to enable multidex.

This is how you do it. https://developer.android.com/tools/building/multidex.html

Convert a JSON String to a HashMap

If you hate recursion - using a Stack and javax.json to convert a Json String into a List of Maps:

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.json.Json;
import javax.json.stream.JsonParser;

public class TestCreateObjFromJson {
    public static List<Map<String,Object>> extract(InputStream is) {
        List extracted = new ArrayList<>();
        JsonParser parser = Json.createParser(is);

        String nextKey = "";
        Object nextval = "";
        Stack s = new Stack<>();
        while(parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch(event) {
                case START_ARRAY :  List nextList = new ArrayList<>();
                                    if(!s.empty()) {
                                        // If this is not the root object, add it to tbe parent object
                                        setValue(s,nextKey,nextList);
                                    }
                                    s.push(nextList);
                                    break;
                case START_OBJECT : Map<String,Object> nextMap = new HashMap<>();
                                    if(!s.empty()) {
                                        // If this is not the root object, add it to tbe parent object
                                        setValue(s,nextKey,nextMap);
                                    }
                                    s.push(nextMap);
                                    break;
                case KEY_NAME : nextKey = parser.getString();
                                break;
                case VALUE_STRING : setValue(s,nextKey,parser.getString());
                                    break;
                case VALUE_NUMBER : setValue(s,nextKey,parser.getLong());
                                    break;
                case VALUE_TRUE :   setValue(s,nextKey,true);
                                    break;
                case VALUE_FALSE :  setValue(s,nextKey,false);
                                    break;
                case VALUE_NULL :   setValue(s,nextKey,"");
                                    break;
                case END_OBJECT :   
                case END_ARRAY  :   if(s.size() > 1) {
                                        // If this is not a root object, move up
                                        s.pop(); 
                                    } else {
                                        // If this is a root object, add ir ro rhw final 
                                        extracted.add(s.pop()); 
                                    }
                default         :   break;
            }
        }

        return extracted;
    }

    private static void setValue(Stack s, String nextKey, Object v) {
        if(Map.class.isAssignableFrom(s.peek().getClass()) ) ((Map)s.peek()).put(nextKey, v);
        else ((List)s.peek()).add(v);
    }
}

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

I first came across this back with ADO and classic asp, the answer i got was: performance. if you do a straight

Select * from tablename

and pass that in as an sql command/text you will get a noticeable performance increase with the

Where 1=1

added, it was a visible difference. something to do with table headers being returned as soon as the first condition is met, or some other craziness, anyway, it did speed things up.

json_encode is returning NULL?

For me, an issue where json_encode would return null encoding of an entity was because my jsonSerialize implementation fetched entire objects for related entities; I solved the issue by making sure that I fetched the ID of the related/associated entity and called ->toArray() when there were more than one entity associated with the object to be json serialized. Note, I'm speaking about cases where one implements JsonSerializable on entities.

How to convert a Bitmap to Drawable in android?

Try this it converts a Bitmap type image to Drawable

Drawable d = new BitmapDrawable(getResources(), bitmap);

Getting cursor position in Python

sudo add-apt-repository ppa:deadsnakes
sudo apt-get update
sudo apt-get install python3.5 python3.5-tk
# or 2.7, 3.6 etc
# sudo apt-get install python2.7 python2.7-tk
# mouse_position.py
import Tkinter
p=Tkinter.Tk()
print(p.winfo_pointerxy()

Or with one-liner from the command line:

python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
(1377, 379)

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

how to extract only the year from the date in sql server 2008?

year(table_column)

Example:

select * from mytable where year(transaction_day)='2013' 

The type or namespace name could not be found

Other problem that might be causing such behavior are build configurations.

I had two projects with configurations set to be built to specific folders. Like Debug and Any CPU and in second it was Debug and x86.

What I did I went to Solution->Context menu->Properties->Configuration properties->Configuration and I set all my projects to use same configurations Debug and x86 and also checked Build tick mark.

Then projects started to build correctly and were able to see namespaces.

How should I unit test multithreaded code?

I also had serious problems testing multi- threaded code. Then I found a really cool solution in "xUnit Test Patterns" by Gerard Meszaros. The pattern he describes is called Humble object.

Basically it describes how you can extract the logic into a separate, easy-to-test component that is decoupled from its environment. After you tested this logic, you can test the complicated behaviour (multi- threading, asynchronous execution, etc...)

Access parent's parent from javascript object

Here you go:

var life={
        users:{
             guys:function(){ life.mameAndDestroy(life.users.girls); },
             girls:function(){ life.kiss(life.users.guys); }
        },
        mameAndDestroy : function(group){ 
          alert("mameAndDestroy");
          group();
        },
        kiss : function(group){
          alert("kiss");
          //could call group() here, but would result in infinite loop
        }
};

life.users.guys();
life.users.girls();

Also, make sure you don't have a comma after the "girls" definition. This will cause the script to crash in IE (any time you have a comma after the last item in an array in IE it dies).

See it run

Writing unit tests in Python: How do I start?

There are, in my opinion, three great python testing frameworks that are good to check out.
unittest - module comes standard with all python distributions
nose - can run unittest tests, and has less boilerplate.
pytest - also runs unittest tests, has less boilerplate, better reporting, lots of cool extra features

To get a good comparison of all of these, read through the introductions to each at http://pythontesting.net/start-here.
There's also extended articles on fixtures, and more there.

Get month and year from a datetime in SQL Server 2005

The following works perfectly! I just used it, try it out.

date_format(date,'%Y-%c')

Javascript + Regex = Nothing to repeat error?

Building off of @Bohemian, I think the easiest approach would be to just use a regex literal, e.g.:

if (name.search(/[\[\]?*+|{}\\()@.\n\r]/) != -1) {
    // ... stuff ...
}

Regex literals are nice because you don't have to escape the escape character, and some IDE's will highlight invalid regex (very helpful for me as I constantly screw them up).

How to get object length

In jQuery i've made it in a such way:

len = function(obj) {
    var L=0;
    $.each(obj, function(i, elem) {
        L++;
    });
    return L;
}

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Bin size in Matplotlib (Histogram)

I use quantiles to do bins uniform and fitted to sample:

bins=df['Generosity'].quantile([0,.05,0.1,0.15,0.20,0.25,0.3,0.35,0.40,0.45,0.5,0.55,0.6,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1]).to_list()

plt.hist(df['Generosity'], bins=bins, normed=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')

enter image description here

Using an image caption in Markdown Jekyll

For Kramdown, you can use {:refdef: style="text-align: center;"} to align center

{:refdef: style="text-align: center;"}
![example](https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg){: width="50%" .shadow}
{: refdef}
{:refdef: style="text-align: center;"}
*Fig.1: This is an example image. [Source](https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg)*
{: refdef}

Remove all whitespace in a string

In addition, strip has some variations:

Remove spaces in the BEGINNING and END of a string:

sentence= sentence.strip()

Remove spaces in the BEGINNING of a string:

sentence = sentence.lstrip()

Remove spaces in the END of a string:

sentence= sentence.rstrip()

All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:

" 1. Step 1\n".strip(" ")

Or you could remove extra commas when reading in a string list:

"1,2,3,".strip(",")

How to generate a GUID in Oracle?

You can run the following query

 select sys_guid() from dual
 union all
 select sys_guid() from dual
 union all 
 select sys_guid() from dual

One line if statement not working

if else condition can be covered with ternary operator

@item.rigged? ? 'Yes' : 'No'

converting date time to 24 hour format

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date date = new Date();
    Date date2 = new Date("2014/08/06 15:59:48");

    String currentDate = dateFormat.format(date).toString();
    String anyDate = dateFormat.format(date2).toString();

    System.out.println(currentDate);
    System.out.println(anyDate);

Why am I not getting a java.util.ConcurrentModificationException in this example?

This snippet will always throw a ConcurrentModificationException.

The rule is "You may not modify (add or remove elements from the list) while iterating over it using an Iterator (which happens when you use a for-each loop)".

JavaDocs:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

Hence if you want to modify the list (or any collection in general), use iterator, because then it is aware of the modifications and hence those will be handled properly.

Hope this helps.

How to set selected value from Combobox?

I suspect something is not right when you are saving to the db. Do i understand your steps as:

  1. populate and bind
  2. user selects and item, hit and save.. then you save in the db
  3. now if you select another item it won't select?

got more code, especially when saving? where in your code are initializing and populating the bindinglist

Group by with union mysql select query

This may be what your after:

SELECT Count(Owner_ID), Name
FROM (
    SELECT M.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Motorbike As M
    WHERE T.Type = 'Motorbike'
    AND O.Owner_ID = M.Owner_ID
    AND T.Type_ID = M.Motorbike_ID

    UNION ALL

    SELECT C.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Car As C
    WHERE T.Type = 'Car'
    AND O.Owner_ID = C.Owner_ID
    AND T.Type_ID = C.Car_ID
)
GROUP BY Owner_ID

Adding a month to a date in T SQL

select * from Reference where reference_dt = DateAdd(month,1,another_date_reference)

Determine whether an array contains a value

I prefer simplicity:

var days = [1, 2, 3, 4, 5];
if ( 2 in days ) {console.log('weekday');}

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Transaction marked as rollback only: How do I find the cause

Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/

1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.

OR:

2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.

How do I create a basic UIButton programmatically?

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];

Change the color of a checked menu item in a navigation drawer

Here's how you can do it in your Activity's onCreate method:

NavigationView navigationView = findViewById(R.id.nav_view);
ColorStateList csl = new ColorStateList(
    new int[][] {
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_checked}  // checked
    },
    new int[] {
        Color.BLACK,
        Color.RED
    }
);
navigationView.setItemTextColor(csl);
navigationView.setItemIconTintList(csl);

Split a large pandas dataframe

you can use list comprehensions to do this in a single line

n = 4
chunks = [df[i:i+n] for i in range(0,df.shape[0],n)]

GroupBy pandas DataFrame and select most common value

A little late to the game here, but I was running into some performance issues with HYRY's solution, so I had to come up with another one.

It works by finding the frequency of each key-value, and then, for each key, only keeping the value that appears with it most often.

There's also an additional solution that supports multiple modes.

On a scale test that's representative of the data I'm working with, this reduced runtime from 37.4s to 0.5s!

Here's the code for the solution, some example usage, and the scale test:

import numpy as np
import pandas as pd
import random
import time

test_input = pd.DataFrame(columns=[ 'key',          'value'],
                          data=  [[ 1,              'A'    ],
                                  [ 1,              'B'    ],
                                  [ 1,              'B'    ],
                                  [ 1,              np.nan ],
                                  [ 2,              np.nan ],
                                  [ 3,              'C'    ],
                                  [ 3,              'C'    ],
                                  [ 3,              'D'    ],
                                  [ 3,              'D'    ]])

def mode(df, key_cols, value_col, count_col):
    '''                                                                                                                                                                                                                                                                                                                                                              
    Pandas does not provide a `mode` aggregation function                                                                                                                                                                                                                                                                                                            
    for its `GroupBy` objects. This function is meant to fill                                                                                                                                                                                                                                                                                                        
    that gap, though the semantics are not exactly the same.                                                                                                                                                                                                                                                                                                         

    The input is a DataFrame with the columns `key_cols`                                                                                                                                                                                                                                                                                                             
    that you would like to group on, and the column                                                                                                                                                                                                                                                                                                                  
    `value_col` for which you would like to obtain the mode.                                                                                                                                                                                                                                                                                                         

    The output is a DataFrame with a record per group that has at least one mode                                                                                                                                                                                                                                                                                     
    (null values are not counted). The `key_cols` are included as columns, `value_col`                                                                                                                                                                                                                                                                               
    contains a mode (ties are broken arbitrarily and deterministically) for each                                                                                                                                                                                                                                                                                     
    group, and `count_col` indicates how many times each mode appeared in its group.                                                                                                                                                                                                                                                                                 
    '''
    return df.groupby(key_cols + [value_col]).size() \
             .to_frame(count_col).reset_index() \
             .sort_values(count_col, ascending=False) \
             .drop_duplicates(subset=key_cols)

def modes(df, key_cols, value_col, count_col):
    '''                                                                                                                                                                                                                                                                                                                                                              
    Pandas does not provide a `mode` aggregation function                                                                                                                                                                                                                                                                                                            
    for its `GroupBy` objects. This function is meant to fill                                                                                                                                                                                                                                                                                                        
    that gap, though the semantics are not exactly the same.                                                                                                                                                                                                                                                                                                         

    The input is a DataFrame with the columns `key_cols`                                                                                                                                                                                                                                                                                                             
    that you would like to group on, and the column                                                                                                                                                                                                                                                                                                                  
    `value_col` for which you would like to obtain the modes.                                                                                                                                                                                                                                                                                                        

    The output is a DataFrame with a record per group that has at least                                                                                                                                                                                                                                                                                              
    one mode (null values are not counted). The `key_cols` are included as                                                                                                                                                                                                                                                                                           
    columns, `value_col` contains lists indicating the modes for each group,                                                                                                                                                                                                                                                                                         
    and `count_col` indicates how many times each mode appeared in its group.                                                                                                                                                                                                                                                                                        
    '''
    return df.groupby(key_cols + [value_col]).size() \
             .to_frame(count_col).reset_index() \
             .groupby(key_cols + [count_col])[value_col].unique() \
             .to_frame().reset_index() \
             .sort_values(count_col, ascending=False) \
             .drop_duplicates(subset=key_cols)

print test_input
print mode(test_input, ['key'], 'value', 'count')
print modes(test_input, ['key'], 'value', 'count')

scale_test_data = [[random.randint(1, 100000),
                    str(random.randint(123456789001, 123456789100))] for i in range(1000000)]
scale_test_input = pd.DataFrame(columns=['key', 'value'],
                                data=scale_test_data)

start = time.time()
mode(scale_test_input, ['key'], 'value', 'count')
print time.time() - start

start = time.time()
modes(scale_test_input, ['key'], 'value', 'count')
print time.time() - start

start = time.time()
scale_test_input.groupby(['key']).agg(lambda x: x.value_counts().index[0])
print time.time() - start

Running this code will print something like:

   key value
0    1     A
1    1     B
2    1     B
3    1   NaN
4    2   NaN
5    3     C
6    3     C
7    3     D
8    3     D
   key value  count
1    1     B      2
2    3     C      2
   key  count   value
1    1      2     [B]
2    3      2  [C, D]
0.489614009857
9.19386196136
37.4375009537

Hope this helps!

How to convert List<string> to List<int>?

Convert string value into integer list

var myString = "010"; 
int myInt;
List<int> B = myString.ToCharArray().Where(x => int.TryParse(x.ToString(), out myInt)).Select(x => int.Parse(x.ToString())).ToList();

Listing available com ports with Python

refinement on moylop260's answer:

import serial.tools.list_ports
comlist = serial.tools.list_ports.comports()
connected = []
for element in comlist:
    connected.append(element.device)
print("Connected COM ports: " + str(connected))

This lists the ports that exist in hardware, including ones that are in use. A whole lot more information exists in the list, per the pyserial tools documentation

eclipse stuck when building workspace

You may want to take a look at How to report a deadlock. You may also want to check the Error view and/or the error log ([workspace]/.metadata/.log). If that doesn't help, you'll probably need to include more info about which plugins you have installed and which projects you have. Can you create a minimal workspace which reproduces the problem?

How to identify object types in java

You want instanceof:

if (value instanceof Integer)

This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do

if (value.getClass() == Integer.class)

or

if (Integer.class.equals(value.getClass())

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

Solution

  1. I am using volley library. I parse response automatic in volley using GSON

    [
            {
                "name": "Naruto: Shippuuden",
                "description": "It has been two and a half years since Naruto Uzumaki left Konohagakure, the Hidden Leaf Village, for intense training following events which fueled his desire to be stronger. Now Akatsuki, the mysterious organization of elite rogue ninja, is closing in on their grand plan which may threaten the safety of the entire shinobi world.",
                "Rating": "8.16",
                "episode": 500,
                "categorie":"Animation | Drama | Adventure",
                "studio":"Studio Pierrot",
                "img": "https://myanimelist.cdn-dena.com/images/anime/5/17407.jpg"
            },
            {
                "name": "One Piece",
                "description": "Gol D. Roger was known as the 'Pirate King',the strongest and most infamous being to have sailed the Grand Line. The capture and death of Roger by the World Government brought a change throughout the world. His last words before his death revealed the existence of the greatest treasure in the world, One Piece. It was this revelation that brought about the Grand Age of Pirates, men who dreamed of finding One Piece—which promises an unlimited amount of riches and fame—and quite possibly the pinnacle of glory and the title of the Pirate King.",
                "Rating": "8.54",
                "episode": 700,
                 "categorie":"Animation | Drama | Adventure",
                "studio":"Toei Animation",
                "img": "https://myanimelist.cdn-dena.com/images/anime/6/73245.jpg"
            }
        ]

2.This my model


    public class DataResponse implements Serializable {
    
        @SerializedName("studio")
        private String studio;
    
        @SerializedName("img")
        private String img;
    
        @SerializedName("categorie")
        private String categorie;
    
        @SerializedName("Rating")
        private String rating;
    
        @SerializedName("name")
        private String name;
    
        @SerializedName("description")
        private String description;
    
        @SerializedName("episode")
        private int episode;
    
        public void setStudio(String studio){
            this.studio = studio;
        }
    
        public String getStudio(){
            return studio;
        }
    
        public void setImg(String img){
            this.img = img;
        }
    
        public String getImg(){
            return img;
        }
    
        public void setCategorie(String categorie){
            this.categorie = categorie;
        }
    
        public String getCategorie(){
            return categorie;
        }
    
        public void setRating(String rating){
            this.rating = rating;
        }
    
        public String getRating(){
            return rating;
        }
    
        public void setName(String name){
            this.name = name;
        }
    
        public String getName(){
            return name;
        }
    
        public void setDescription(String description){
            this.description = description;
        }
    
        public String getDescription(){
            return description;
        }
    
        public void setEpisode(int episode){
            this.episode = episode;
        }
    
        public int getEpisode(){
            return episode;
        }
    
        @Override
        public String toString(){
            return 
                "Response{" + 
                "studio = '" + studio + '\'' + 
                ",img = '" + img + '\'' + 
                ",categorie = '" + categorie + '\'' + 
                ",rating = '" + rating + '\'' + 
                ",name = '" + name + '\'' + 
                ",description = '" + description + '\'' + 
                ",episode = '" + episode + '\'' + 
                "}";
            }
    }

  1. my api method
define globle

private List<DataResponse> dataResponses = new ArrayList<>();


    private void volleyAutomation(String url) {
            JSONArray array = new JSONArray();
            JsonArrayRequest request_json = new JsonArrayRequest(Request.Method.GET, url, array,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
    
                            GsonBuilder gsonBuilder = new GsonBuilder();
                            Gson gson = gsonBuilder.create();
                           dataResponses = Arrays.asList(gson.fromJson(response.toString(), DataResponse[].class));
    
                            rvList(dataResponses);
                            Log.d("respknce___", String.valueOf(dataResponses.size()));
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
    
                }
            });
            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
            requestQueue.add(request_json);
        }

How to check if a variable is null or empty string or all whitespace in JavaScript?

You can use if(addr && (addr = $.trim(addr)))

This has the advantage of actually removing any outer whitespace from addr instead of just ignoring it when performing the check.

Reference: http://api.jquery.com/jQuery.trim/

How do I add an "Add to Favorites" button or link on my website?

  if (window.sidebar) { // Mozilla Firefox Bookmark
     window.sidebar.addPanel(document.title,location.href,"");

It adds the bookmark but in the sidebar.

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

"Fatal error: Unable to find local grunt." when running "grunt" command

You have to install grunt in your project folder

  1. create your package.json

    $ npm init
    
  2. install grunt for this project, this will be installed under node_modules/. --save-dev will add this module to devDependency in your package.json

    $ npm install grunt --save-dev
    
  3. then create gruntfile.js and run

    $ grunt 
    

Controller not a function, got undefined, while defining controllers globally

I had this error because I didn't understand the difference between angular.module('myApp', []) and angular.module('myApp').

This creates the module 'myApp' and overwrites any existing module named 'myApp':

angular.module('myApp', [])

This retrieves an existing module 'myApp':

angular.module('myApp')

I had been overwriting my module in another file, using the first call above which created another module instead of retrieving as I expected.

More detail here: https://docs.angularjs.org/guide/module

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

First you should install binary:

On Linux

sudo apt-get update
sudo apt-get install libleptonica-dev 
sudo apt-get install tesseract-ocr tesseract-ocr-dev
sudo apt-get install libtesseract-dev

On Mac

brew install tesseract

On Windows

download binary from https://github.com/UB-Mannheim/tesseract/wiki. then add pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe' to your script.

Then you should install python package using pip:

pip install tesseract
pip install tesseract-ocr

references: https://pypi.org/project/pytesseract/ (INSTALLATION section) and https://github.com/tesseract-ocr/tesseract/wiki#installation

Get last 5 characters in a string

The accepted answer of this post will cause error in the case when the string length is lest than 5. So i have a better solution. We can use this simple code :

If(str.Length <= 5, str, str.Substring(str.Length - 5))

You can test it with variable length string.

    Dim str, result As String
    str = "11!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)
    str = "I will be going to school in 2011!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)

Another simple but efficient solution i found :

str.Substring(str.Length - Math.Min(5, str.Length))

Loop through files in a folder in matlab

Looping through all the files in the folder is relatively easy:

files = dir('*.csv');
for file = files'
    csv = load(file.name);
    % Do some stuff
end

Behaviour of increment and decrement operators in Python

Yeah, I missed ++ and -- functionality as well. A few million lines of c code engrained that kind of thinking in my old head, and rather than fight it... Here's a class I cobbled up that implements:

pre- and post-increment, pre- and post-decrement, addition,
subtraction, multiplication, division, results assignable
as integer, printable, settable.

Here 'tis:

class counter(object):
    def __init__(self,v=0):
        self.set(v)

    def preinc(self):
        self.v += 1
        return self.v
    def predec(self):
        self.v -= 1
        return self.v

    def postinc(self):
        self.v += 1
        return self.v - 1
    def postdec(self):
        self.v -= 1
        return self.v + 1

    def __add__(self,addend):
        return self.v + addend
    def __sub__(self,subtrahend):
        return self.v - subtrahend
    def __mul__(self,multiplier):
        return self.v * multiplier
    def __div__(self,divisor):
        return self.v / divisor

    def __getitem__(self):
        return self.v

    def __str__(self):
        return str(self.v)

    def set(self,v):
        if type(v) != int:
            v = 0
        self.v = v

You might use it like this:

c = counter()                          # defaults to zero
for listItem in myList:                # imaginary task
     doSomething(c.postinc(),listItem) # passes c, but becomes c+1

...already having c, you could do this...

c.set(11)
while c.predec() > 0:
    print c

....or just...

d = counter(11)
while d.predec() > 0:
    print d

...and for (re-)assignment into integer...

c = counter(100)
d = c + 223 # assignment as integer
c = c + 223 # re-assignment as integer
print type(c),c # <type 'int'> 323

...while this will maintain c as type counter:

c = counter(100)
c.set(c + 223)
print type(c),c # <class '__main__.counter'> 323

EDIT:

And then there's this bit of unexpected (and thoroughly unwanted) behavior,

c = counter(42)
s = '%s: %d' % ('Expecting 42',c) # but getting non-numeric exception
print s

...because inside that tuple, getitem() isn't what used, instead a reference to the object is passed to the formatting function. Sigh. So:

c = counter(42)
s = '%s: %d' % ('Expecting 42',c.v) # and getting 42.
print s

...or, more verbosely, and explicitly what we actually wanted to happen, although counter-indicated in actual form by the verbosity (use c.v instead)...

c = counter(42)
s = '%s: %d' % ('Expecting 42',c.__getitem__()) # and getting 42.
print s

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

Yes , Provisioning profiles which are for distribution purpose, i.e. Distrutions provisioning profiles do not support debugging and gives this error. Simply create and use debug provisioning profile (take care of this when creating provisioning profile from developer.apple.com account).

How do you normalize a file path in Bash?

readlink is the bash standard for obtaining the absolute path. It also has the advantage of returning empty strings if paths or a path doesn't exist (given the flags to do so).

To get the absolute path to a directory that may or may not exist, but who's parents do exist, use:

abspath=$(readlink -f $path)

To get the absolute path to a directory that must exist along with all parents:

abspath=$(readlink -e $path)

To canonicalise the given path and follow symlinks if they happen to exist, but otherwise ignore missing directories and just return the path anyway, it's:

abspath=$(readlink -m $path)

The only downside is that readlink will follow links. If you do not want to follow links, you can use this alternative convention:

abspath=$(cd ${path%/*} && echo $PWD/${path##*/})

That will chdir to the directory part of $path and print the current directory along with the file part of $path. If it fails to chdir, you get an empty string and an error on stderr.

Why is division in Ruby returning an integer instead of decimal value?

There is also the Numeric#fdiv method which you can use instead:

9.fdiv(5)  #=> 1.8

Replace given value in vector

If you want to replace lot of values in single go, you can use 'library(car)'.

Example

library(car)

x <- rep(1:5,3)

xr <- recode(x, '3=1; 4=2')

x
## [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
xr
## [1] 1 2 1 2 5 1 2 1 2 5 1 2 1 2 5

Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

run "export TEMPDIR=/someDir" where some dir is a valid directory other than /tmp. Run this on prompt before running your python command. In my case it is "pip install rasa[spacy]" which was earlier failing.

The export command allows you to temporarily use the specified dir as temp dir.

Is it possible to add an array or object to SharedPreferences on Android

To write,

SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(this);
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put(2);
Editor editor = prefs.edit();
editor.putString("key", jsonArray.toString());
System.out.println(jsonArray.toString());
editor.commit();

To Read,

try {
    JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
    for (int i = 0; i < jsonArray2.length(); i++) {
         Log.d("your JSON Array", jsonArray2.getInt(i)+"");
    }
} catch (Exception e) {
    e.printStackTrace();
}

Other way to do same:

//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson


//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString("key", jsonText);
prefsEditor.apply();

Using GSON in Java:

public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();    

}

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}

Using GSON in Kotlin

fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val editor: Editor = prefs.edit()
    val gson = Gson()
    val json: String = gson.toJson(list)
    editor.putString(key, json)
    editor.apply()
}

fun getArrayList(key: String?): java.util.ArrayList<String?>? {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val gson = Gson()
    val json: String = prefs.getString(key, null)
    val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
    return gson.fromJson(json, type)
}

Get the correct week number of a given date

public int GetWeekNumber()
{
   CultureInfo ciCurr = CultureInfo.CurrentCulture;
   int weekNum = ciCurr.Calendar.GetWeekOfYear(DateTime.Now, 
   CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
   return weekNum;
}

Set content of iframe

Use the "contents" function:

$('#some-id').contents().find('html').html("some-html")

Relevant fiddle: http://jsfiddle.net/fDFca/

Difference between Running and Starting a Docker container

run command creates a container from the image and then starts the root process on this container. Running it with run --rm flag would save you the trouble of removing the useless dead container afterward and would allow you to ignore the existence of docker start and docker remove altogether.

enter image description here

run command does a few different things:

docker run --name dname image_name bash -c "whoami"
  1. Creates a Container from the image. At this point container would have an id, might have a name if one is given, will show up in docker ps
  2. Starts/executes the root process of the container. In the code above that would execute bash -c "whoami". If one runs docker run --name dname image_name without a command to execute container would go into stopped state immediately.
  3. Once the root process is finished, the container is stopped. At this point, it is pretty much useless. One can not execute anything anymore or resurrect the container. There are basically 2 ways out of stopped state: remove the container or create a checkpoint (i.e. an image) out of stopped container to run something else. One has to run docker remove before launching container under the same name.

How to remove container once it is stopped automatically? Add an --rm flag to run command:

docker run --rm --name dname image_name bash -c "whoami"

How to execute multiple commands in a single container? By preventing that root process from dying. This can be done by running some useless command at start with --detached flag and then using "execute" to run actual commands:

docker run --rm -d --name dname image_name tail -f /dev/null
docker exec dname bash -c "whoami"
docker exec dname bash -c "echo 'Nnice'"

Why do we need docker stop then? To stop this lingering container that we launched in the previous snippet with the endless command tail -f /dev/null.

jquery to change style attribute of a div class

You can't use $('#Id').attr('style',' color:red'); and $('#Id').css('padding-left','20%');
at the same time.
You can either use attr or css but both only works when they are used alone.

Android ImageButton with a selected state?

Create an XML-file in a res/drawable folder. For instance, "btn_image.xml":

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_state_1"
          android:state_pressed="true"
          android:state_selected="true"/>
    <item android:drawable="@drawable/bg_state_2"
          android:state_pressed="true"
          android:state_selected="false"/>
    <item android:drawable="@drawable/bg_state_selected"
          android:state_selected="true"/>
    <item android:drawable="@drawable/bg_state_deselected"/>
</selector>

You can combine those files you like, for instance, change "bg_state_1" to "bg_state_deselected" and "bg_state_2" to "bg_state_selected".

In any of those files you can write something like:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="#ccdd00"/>
    <corners android:radius="5dp"/>
</shape>

Create in a layout file an ImageView or ImageButton with the following attributes:

<ImageView
    android:id="@+id/image"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:adjustViewBounds="true"
    android:background="@drawable/btn_image"
    android:padding="10dp"
    android:scaleType="fitCenter"
    android:src="@drawable/star"/>

Later in code:

image.setSelected(!image.isSelected());

How to search if dictionary value contains certain string with Python

import json 'mtach' in json.dumps(myDict) is true if found

How can I make one python file run another?

You could use this script:

def run(runfile):
  with open(runfile,"r") as rnf:
    exec(rnf.read())

Syntax:

run("file.py")

Bash: infinite sleep (infinite blocking)

Maybe this seems ugly, but why not just run cat and let it wait for input forever?

Java 8: Lambda-Streams, Filter by Method with Exception

Your example can be written as:

import utils.stream.Unthrow;

class Bank{
   ....
   public Set<String> getActiveAccountNumbers() {
       return accounts.values().stream()
           .filter(a -> Unthrow.wrap(() -> a.isActive()))
           .map(a -> Unthrow.wrap(() -> a.getNumber()))
           .collect(Collectors.toSet());
   }
   ....
}

The Unthrow class can be taken here https://github.com/SeregaLBN/StreamUnthrower

What is (x & 1) and (x >>= 1)?

In addition to the answer of "dasblinkenlight" I think an example could help. I will only use 8 bits for a better understanding.

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

This is because 1 will be represented in bits as 00000001. Only the last bit is set to 1. Let's assume x is 185 which will be represented in bits as 10111001. If you apply a bitwise AND operation on x with 1 this will be the result:

00000001
10111001
--------
00000001

The first seven bits of the operation result will be 0 after the operation and will carry no information in this case (see Logical AND operation). Because whatever the first seven bits of the operand x were before, after the operation they will be 0. But the last bit of the operand 1 is 1 and it will reveal if the last bit of operand x was 0 or 1. So in this example the result of the bitwise AND operation will be 1 because our last bit of x is 1. If the last bit would have been 0, then the result would have been also 0, indicating that the last bit of operand x is 0:

00000001
10111000
--------
00000000

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift

Let's pick the example from above. For x >>= 1 this would be:

10111001
--------
01011100

And for left shift x <<= 1 it would be:

10111001
--------
01110010

Please pay attention to the note of user "dasblinkenlight" in regard to shifts.

adding child nodes in treeview

SqlConnection con = new SqlConnection(@"Data Source=NIKOLAY;Initial Catalog=PlanZadanie;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        DataTable dt = new DataTable();
        public void loadTree(TreeView tree)
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT [RAZDEL_ID],[NAME_RAZDEL] FROM [tbl_RAZDEL]";
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    tree.Nodes.Add(reader.GetString(1));
                    tree.Nodes[0].Nodes.Add("yourChildNode");
                    tree.ExpandAll();

                }

                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("?????? ? ??????????: " + ex.Message);
            }


        }

NoClassDefFoundError for code in an Java library on Android

Try going to Project -> Properties -> Java Build Path -> Order & Export and ensure Android Private Libraries are checked for your project and for all other library projects you are using. i got the solution by following below link NoClassDefFoundError Android Project?

How to add option to select list in jQuery

This is working fine, try out this.

var ob = $("#myListBox");

for (var i = 0; i < buildings.length; i++) {
     var val = buildings[i];
     var text = buildings[i];

     ob.prepend("<option value="+ val +">" + text + "</option>");
}

Java Inheritance - calling superclass method

It is possible to use super to call the method from mother class, but this would mean you probably have a design problem. Maybe B.alphaMethod1() shouldn't override A's method and be called B.betaMethod1().

If it depends on the situation, you can put some code logic like :

public void alphaMethod1(){
    if (something) {
        super.alphaMethod1();
        return;
    }
    // Rest of the code for other situations
}

Like this it will only call A's method when needed and will remain invisible for the class user.

How to break out of while loop in Python?

Don't use while True and break statements. It's bad programming.

Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.

The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.

Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.

How to convert WebResponse.GetResponseStream return into a string?

You should create a StreamReader around the stream, then call ReadToEnd.

You should consider calling WebClient.DownloadString instead.

How to automatically convert strongly typed enum into int?

This seems impossible with the native enum class, but probably you can mock a enum class with a class:

In this case,

enum class b
{
    B1,
    B2
};

would be equivalent to:

class b {
 private:
  int underlying;
 public:
  static constexpr int B1 = 0;
  static constexpr int B2 = 1;
  b(int v) : underlying(v) {}
  operator int() {
      return underlying;
  }
};

This is mostly equivalent to the original enum class. You can directly return b::B1 for in a function with return type b. You can do switch case with it, etc.

And in the spirit of this example you can use templates (possibly together with other things) to generalize and mock any possible object defined by the enum class syntax.

JUnit 4 compare Sets

Apache commons to the rescue again.

assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));

Works like a charm. I don't know why but I found that with collections the following assertEquals(coll1, coll2) doesn't always work. In the case where it failed for me I had two collections backed by Sets. Neither hamcrest nor junit would say the collections were equal even though I knew for sure that they were. Using CollectionUtils it works perfectly.

Is there a way to compile node.js source files?

Node.js runs on top of the V8 Javascript engine, which itself optimizes performance by compiling javascript code into native code... so no reason really for compiling then, is there?

https://developers.google.com/v8/design#mach_code

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

Pass correct "this" context to setTimeout callback?

EDIT: In summary, back in 2010 when this question was asked the most common way to solve this problem was to save a reference to the context where the setTimeout function call is made, because setTimeout executes the function with this pointing to the global object:

var that = this;
if (this.options.destroyOnHide) {
     setTimeout(function(){ that.tip.destroy() }, 1000);
} 

In the ES5 spec, just released a year before that time, it introduced the bind method, this wasn't suggested in the original answer because it wasn't yet widely supported and you needed polyfills to use it but now it's everywhere:

if (this.options.destroyOnHide) {
     setTimeout(function(){ this.tip.destroy() }.bind(this), 1000);
}

The bind function creates a new function with the this value pre-filled.

Now in modern JS, this is exactly the problem arrow functions solve in ES6:

if (this.options.destroyOnHide) {
     setTimeout(() => { this.tip.destroy() }, 1000);
}

Arrow functions do not have a this value of its own, when you access it, you are accessing the this value of the enclosing lexical scope.

HTML5 also standardized timers back in 2011, and you can pass now arguments to the callback function:

if (this.options.destroyOnHide) {
     setTimeout(function(that){ that.tip.destroy() }, 1000, this);
}

See also:

Doctrine - How to print out the real sql, not just the prepared statement?

More clear solution:

 /**
 * Get string query 
 * 
 * @param Doctrine_Query $query
 * @return string
 */
public function getDqlWithParams(Doctrine_Query $query){
    $vals = $query->getFlattenedParams();
    $sql = $query->getDql();
    $sql = str_replace('?', '%s', $sql);
    return vsprintf($sql, $vals);
}

Settings to Windows Firewall to allow Docker for Windows to share drive

For AVG Internet Security, enabling Internet Connection Sharing Mode under the Firewall settings did the trick for me.

enter image description here

Is there a way to crack the password on an Excel VBA Project?

There is another (somewhat easier) solution, without the size problems. I used this approach today (on a 2003 XLS file, using Excel 2007) and was successful.

  1. Backup the xls file
  2. Open the file in a HEX editor and locate the DPB=... part
  3. Change the DPB=... string to DPx=...
  4. Open the xls file in Excel
  5. Open the VBA editor (ALT + F11)
  6. the magic: Excel discovers an invalid key (DPx) and asks whether you want to continue loading the project (basically ignoring the protection)
  7. You will be able to overwrite the password, so change it to something you can remember
  8. Save the xls file*
  9. Close and reopen the document and work your VBA magic!

*NOTE: Be sure that you have changed the password to a new value, otherwise the next time you open the spreadsheet Excel will report errors (Unexpected Error), then when you access the list of VBA modules you will now see the names of the source modules but receive another error when trying to open forms/code/etc. To remedy this, go back to the VBA Project Properties and set the password to a new value. Save and re-open the Excel document and you should be good to go!

How to check if a float value is a whole number

To check if a float value is a whole number, use the float.is_integer() method:

>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False

The method was added to the float type in Python 2.6.

Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating point arithmetic can be imprecise (a float is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:

>>> for n in range(12000, -1, -1):
...     if (n ** (1.0/3)).is_integer():
...         print n
... 
27
8
1
0

which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:

>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996

You'd have to check for numbers close to the whole number instead, or not use float() to find your number. Like rounding down the cube root of 12000:

>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648

If you are using Python 3.5 or newer, you can use the math.isclose() function to see if a floating point value is within a configurable margin:

>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True

For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:

def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

Add CSS to <head> with JavaScript?

Here's a function that will dynamically create a CSS rule in all major browsers. createCssRule takes a selector (e.g. "p.purpleText"), a rule (e.g. "color: purple;") and optionally a Document (the current document is used by default):

var addRule;

if (typeof document.styleSheets != "undefined" && document.styleSheets) {
    addRule = function(selector, rule) {
        var styleSheets = document.styleSheets, styleSheet;
        if (styleSheets && styleSheets.length) {
            styleSheet = styleSheets[styleSheets.length - 1];
            if (styleSheet.addRule) {
                styleSheet.addRule(selector, rule)
            } else if (typeof styleSheet.cssText == "string") {
                styleSheet.cssText = selector + " {" + rule + "}";
            } else if (styleSheet.insertRule && styleSheet.cssRules) {
                styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
            }
        }
    }
} else {
    addRule = function(selector, rule, el, doc) {
        el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
    };
}

function createCssRule(selector, rule, doc) {
    doc = doc || document;
    var head = doc.getElementsByTagName("head")[0];
    if (head && addRule) {
        var styleEl = doc.createElement("style");
        styleEl.type = "text/css";
        styleEl.media = "screen";
        head.appendChild(styleEl);
        addRule(selector, rule, styleEl, doc);
        styleEl = null;
    }
};

createCssRule("body", "background-color: purple;");

Pass mouse events through absolutely-positioned element

There is a javascript version available which manually redirects events from one div to another.

I cleaned it up and made it into a jQuery plugin.

Here's the Github repository: https://github.com/BaronVonSmeaton/jquery.forwardevents

Unfortunately, the purpose I was using it for - overlaying a mask over Google Maps did not capture click and drag events, and the mouse cursor does not change which degrades the user experience enough that I just decided to hide the mask under IE and Opera - the two browsers which dont support pointer events.

How to implement a binary search tree in Python?

    def BinaryST(list1,key):
    start = 0
    end = len(list1)
    print("Length of List: ",end)

    for i in range(end):
        for j in range(0, end-i-1):
            if(list1[j] > list1[j+1]):
                temp = list1[j]
                list1[j] = list1[j+1]
                list1[j+1] = temp

    print("Order List: ",list1)

    mid = int((start+end)/2)
    print("Mid Index: ",mid)

    if(key == list1[mid]):
        print(key," is on ",mid," Index")

    elif(key > list1[mid]):
        for rindex in range(mid+1,end):
            if(key == list1[rindex]):
                print(key," is on ",rindex," Index")
                break
            elif(rindex == end-1):
                print("Given key: ",key," is not in List")
                break
            else:
                continue

    elif(key < list1[mid]):
        for lindex in range(0,mid):
            if(key == list1[lindex]):
                print(key," is on ",lindex," Index")
                break
            elif(lindex == mid-1):
                print("Given key: ",key," is not in List")
                break
            else:
                continue


size = int(input("Enter Size of List: "))
list1 = []
for e in range(size):
    ele = int(input("Enter Element in List: "))
    list1.append(ele)

key = int(input("\nEnter Key for Search: "))

print("\nUnorder List: ",list1)
BinaryST(list1,key)

Can I pass parameters by reference in Java?

Another option is to use an array, e.g. void method(SomeClass[] v) { v[0] = ...; } but 1) the array must be initialized before method invoked, 2) still one cannot implement e.g. swap method in this way... This way is used in JDK, e.g. in java.util.concurrent.atomic.AtomicMarkableReference.get(boolean[]).

HorizontalScrollView within ScrollView Touch Handling

This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.

What do Clustered and Non clustered index actually mean?

With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.

With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indices, although each new index will increase the time it takes to write new records.

It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.

Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.

Disable form auto submit on button click

another one:

if(this.checkValidity() == false) {

                $(this).addClass('was-validated');
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();

                return false;
}

mkdir's "-p" option

The man pages is the best source of information you can find... and is at your fingertips: man mkdir yields this about -p switch:

-p, --parents
    no error if existing, make parent directories as needed

Use case example: Assume I want to create directories hello/goodbye but none exist:

$mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$mkdir -p hello/goodbye
$

-p created both, hello and goodbye

This means that the command will create all the directories necessaries to fulfill your request, not returning any error in case that directory exists.

About rlidwka, Google has a very good memory for acronyms :). My search returned this for example: http://www.cs.cmu.edu/~help/afs/afs_acls.html

 Directory permissions

l (lookup)
    Allows one to list the contents of a directory. It does not allow the reading of files. 
i (insert)
    Allows one to create new files in a directory or copy new files to a directory. 
d (delete)
    Allows one to remove files and sub-directories from a directory. 
a (administer)
    Allows one to change a directory's ACL. The owner of a directory can always change the ACL of a directory that s/he owns, along with the ACLs of any subdirectories in that directory. 

File permissions

r (read)
    Allows one to read the contents of file in the directory. 
w (write)
    Allows one to modify the contents of files in a directory and use chmod on them. 
k (lock)
    Allows programs to lock files in a directory. 

Hence rlidwka means: All permissions on.

It's worth mentioning, as @KeithThompson pointed out in the comments, that not all Unix systems support ACL. So probably the rlidwka concept doesn't apply here.

How to replace multiple strings in a file using PowerShell

A third option, for a pipelined one-liner is to nest the -replaces:

PS> ("ABC" -replace "B","C") -replace "C","D"
ADD

And:

PS> ("ABC" -replace "C","D") -replace "B","C"
ACD

This preserves execution order, is easy to read, and fits neatly into a pipeline. I prefer to use parentheses for explicit control, self-documentation, etc. It works without them, but how far do you trust that?

-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.

Please see:

help about_operators

Generic type conversion FROM string

With inspiration from the Bob's answer, these extensions also support null value conversion and all primitive conversion back and fourth.

public static class ConversionExtensions
{
        public static object Convert(this object value, Type t)
        {
            Type underlyingType = Nullable.GetUnderlyingType(t);

            if (underlyingType != null && value == null)
            {
                return null;
            }
            Type basetype = underlyingType == null ? t : underlyingType;
            return System.Convert.ChangeType(value, basetype);
        }

        public static T Convert<T>(this object value)
        {
            return (T)value.Convert(typeof(T));
        }
}

Examples

            string stringValue = null;
            int? intResult = stringValue.Convert<int?>();

            int? intValue = null;
            var strResult = intValue.Convert<string>();

How can I trigger a JavaScript event click

I'm quite ashamed that there are so many incorrect or undisclosed partial applicability.

The easiest way to do this is through Chrome or Opera (my examples will use Chrome) using the Console. Enter the following code into the console (generally in 1 line):

var l = document.getElementById('testLink');
for(var i=0; i<5; i++){
  l.click();
}

This will generate the required result

Dynamic instantiation from string name of a class in dynamically imported module?

tl;dr

Import the root module with importlib.import_module and load the class by its name using getattr function:

# Standard import
import importlib
# Load "module.submodule.MyClass"
MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
# Instantiate the class (pass arguments to the constructor, if needed)
instance = MyClass()

explanations

You probably don't want to use __import__ to dynamically import a module by name, as it does not allow you to import submodules:

>>> mod = __import__("os.path")
>>> mod.join
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'join'

Here is what the python doc says about __import__:

Note: This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().

Instead, use the standard importlib module to dynamically import a module by name. With getattr you can then instantiate a class by its name:

import importlib
my_module = importlib.import_module("module.submodule")
MyClass = getattr(my_module, "MyClass")
instance = MyClass()

You could also write:

import importlib
module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
MyClass = getattr(importlib.import_module(module_name), class_name)
instance = MyClass()

This code is valid in python = 2.7 (including python 3).

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

Four fewer characters, but 2 more ms

%%timeit
df.isna().T.any()
# 52.4 ms ± 352 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
df.isna().any(axis=1)
# 50 ms ± 423 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

I'd probably use axis=1

How to rename a component in Angular CLI?

While the OP asks for a CLI command, some of the answers focus on the IDEs. In this answer I just confirm, that the current WebStorm/IntelliJ does allow renaming the component. All that needs to be done is attempting to rename the class in the .ts file. You will be presented with:

enter image description here

and the rename will be performed in all relevant places.

How to generate a random string of 20 characters

I'd use this approach:

String randomString(final int length) {
    Random r = new Random(); // perhaps make it a class variable so you don't make a new one every time
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString();
}

If you want a byte[] you can do this:

byte[] randomByteString(final int length) {
    Random r = new Random();
    byte[] result = new byte[length];
    for(int i = 0; i < length; i++) {
        result[i] = r.nextByte();
    }
    return result;
}

Or you could do this

byte[] randomByteString(final int length) {
    Random r = new Random();
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString().getBytes();
}

Disable back button in android

if you are using FragmentActivity. then do like this

first call This inside your Fragment.

public void callParentMethod(){
    getActivity().onBackPressed();
}

and then Call onBackPressed method in side your parent FragmentActivity class.

@Override
public void onBackPressed() {
  //super.onBackPressed();
  //create a dialog to ask yes no question whether or not the user wants to exit
  ...
}

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

For Iranian people: We need use proxy or VPN to building app.

Reason: The boycott by Google's servers causes that you can't build app or upgrade your requirement.

Angular2 *ngFor in select list, set active based on string from object

This should work

<option *ngFor="let title of titleArray" 
    [value]="title.Value" 
    [attr.selected]="passenger.Title==title.Text ? true : null">
  {{title.Text}}
</option>

I'm not sure the attr. part is necessary.

Show/hide div if checkbox selected

change the input boxes like

<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox

and js code as

function showMe (box) {

    var chboxs = document.getElementsByName("c1");
    var vis = "none";
    for(var i=0;i<chboxs.length;i++) { 
        if(chboxs[i].checked){
         vis = "block";
            break;
        }
    }
    document.getElementById(box).style.display = vis;


}

here is a demo fiddle

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

u must specify the width and height also

 <section class="bg-solid-light slideContainer strut-slide-0" style="background-image: url(https://accounts.icharts.net/stage/icharts-images/chartbook-images/Chart1457601371484.png); background-repeat: no-repeat;width: 100%;height: 100%;" >

How to reset a select element with jQuery

$('#baba option:first').attr('selected',true);

Getting session value in javascript

You can access your session variable like '<%= Session["VariableName"]%>'

the text in single quotes will give session value. 1)

<script>
var session ='<%= Session["VariableName"]%>'
</script>

2) you can take a hidden field and assign value at server;

hiddenfield.value= session["xyz"].tostring();

//and in script you access the hiddenfield  like

alert(document.getElementbyId("hiddenfield").value);

initializing a boolean array in java

I just need to initialize all the array elements to Boolean false.

Either use boolean[] instead so that all values defaults to false:

boolean[] array = new boolean[size];

Or use Arrays#fill() to fill the entire array with Boolean.FALSE:

Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.FALSE);

Also note that the array index is zero based. The freq[Global.iParameter[2]] = false; line as you've there would cause ArrayIndexOutOfBoundsException. To learn more about arrays in Java, consult this basic Oracle tutorial.

c# .net change label text

When I had this problem I could see only a part of my text and this is the solution for that:

Be sure to set the AutoSize property to true.

output.AutoSize = true;

How do you convert Html to plain text?

For anyone looking for an exact solution to the OP question for a textual abbreviation of a given html document, without newlines and HTML tags, please find the solution below.

Like with every proposed solution, there are some assumptions with the code below:

  • script or style tags should not contain script and style tags as a part of script
  • only major inline elements will be inlined without space, i.e. he<span>ll</span>o should output hello. List of inline tags: https://www.w3schools.com/htmL/html_blocks.asp

Considering the above, the following string extension with compiled regular expressions will output expected plain text with regard to html escaped characters and null on null input.

public static class StringExtensions
{
    public static string ConvertToPlain(this string html)
    {
        if (html == null)
        {
            return html;
        }

        html = scriptRegex.Replace(html, string.Empty);
        html = inlineTagRegex.Replace(html, string.Empty);
        html = tagRegex.Replace(html, " ");
        html = HttpUtility.HtmlDecode(html);
        html = multiWhitespaceRegex.Replace(html, " ");

        return html.Trim();
    }

    private static readonly Regex inlineTagRegex = new Regex("<\\/?(a|span|sub|sup|b|i|strong|small|big|em|label|q)[^>]*>", RegexOptions.Compiled | RegexOptions.Singleline);
    private static readonly Regex scriptRegex = new Regex("<(script|style)[^>]*?>.*?</\\1>", RegexOptions.Compiled | RegexOptions.Singleline);
    private static readonly Regex tagRegex = new Regex("<[^>]+>", RegexOptions.Compiled | RegexOptions.Singleline);
    private static readonly Regex multiWhitespaceRegex = new Regex("\\s+", RegexOptions.Compiled | RegexOptions.Singleline);
}

Difference between scaling horizontally and vertically for databases

Traditional relational databases were designed as client/server database systems. They can be scaled horizontally but the process to do so tends to be complex and error prone. NewSQL databases like NuoDB are memory-centric distributed database systems designed to scale out horizontally while maintaining the SQL/ACID properties of traditional RDBMS.

For more information on NuoDB, read their technical white paper.

How to modify PATH for Homebrew?

To avoid unnecessary duplication, I added the following to my ~/.bash_profile

case ":$PATH:" in
  *:/usr/local/bin:*) ;;     # do nothing if $PATH already contains /usr/local/bin
  *) PATH=/usr/local/bin:$PATH ;;  # in every other case, add it to the front
esac

Credit: https://superuser.com/a/580611

How do search engines deal with AngularJS applications?

This has drastically changed.

http://searchengineland.com/bing-offers-recommendations-for-seo-friendly-ajax-suggests-html5-pushstate-152946

If you use: $locationProvider.html5Mode(true); you are set.

No more rendering pages.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

Interview Question: Merge two sorted singly linked lists without creating new nodes

LLNode *mergeSorted(LLNode *h1, LLNode *h2) 
{ 
  LLNode *h3=NULL;
  LLNode *h3l;
  if(h1==NULL && h2==NULL)
    return NULL; 
  if(h1==NULL) 
    return h2; 
  if(h2==NULL) 
    return h1; 
  if(h1->data<h2->data) 
  {
    h3=h1;
    h1=h1->next; 
  }
  else 
  { 
    h3=h2; 
    h2=h2->next; 
  }
  LLNode *oh=h3;
  while(h1!=NULL && h2!=NULL) 
  {
    if(h1->data<h2->data) 
    {
      h3->next=h1;
      h3=h3->next;
      h1=h1->next; 
    } 
    else 
    {
      h3->next=h2; 
      h3=h3->next; 
      h2=h2->next; 
    } 
  } 
  if(h1==NULL)
    h3->next=h2;
  if(h2==NULL)
    h3->next=h1;
  return oh;
}

Difference between DataFrame, Dataset, and RDD in Spark

Simply RDD is core component, but DataFrame is an API introduced in spark 1.30.

RDD

Collection of data partitions called RDD. These RDD must follow few properties such is:

  • Immutable,
  • Fault Tolerant,
  • Distributed,
  • More.

Here RDD is either structured or unstructured.

DataFrame

DataFrame is an API available in Scala, Java, Python and R. It allows to process any type of Structured and semi structured data. To define DataFrame, a collection of distributed data organized into named columns called DataFrame. You can easily optimize the RDDs in the DataFrame. You can process JSON data, parquet data, HiveQL data at a time by using DataFrame.

val sampleRDD = sqlContext.jsonFile("hdfs://localhost:9000/jsondata.json")

val sample_DF = sampleRDD.toDF()

Here Sample_DF consider as DataFrame. sampleRDD is (raw data) called RDD.

How to distinguish between left and right mouse click with jQuery

event.which === 1 ensures it's a left-click (when using jQuery).

But you should also think about modifier keys: ctrlcmdshiftalt

If you're only interested in catching simple, unmodified left-clicks, you can do something like this:

var isSimpleClick = function (event) {
  return !(
    event.which !== 1 || // not a left click
    event.metaKey ||     // "open link in new tab" (mac)
    event.ctrlKey ||     // "open link in new tab" (windows/linux)
    event.shiftKey ||    // "open link in new window"
    event.altKey         // "save link as"
  );
};

$('a').on('click', function (event) {
  if (isSimpleClick(event)) {
    event.preventDefault();
    // do something...
  }
});

Create table using Javascript

This is how to loop through a javascript object and put the data into a table, code modified from @Vanuan's answer.

_x000D_
_x000D_
<body>_x000D_
    <script>_x000D_
    function createTable(objectArray, fields, fieldTitles) {_x000D_
      let body = document.getElementsByTagName('body')[0];_x000D_
      let tbl = document.createElement('table');_x000D_
      let thead = document.createElement('thead');_x000D_
      let thr = document.createElement('tr');_x000D_
_x000D_
      for (p in objectArray[0]){_x000D_
        let th = document.createElement('th');_x000D_
        th.appendChild(document.createTextNode(p));_x000D_
        thr.appendChild(th);_x000D_
        _x000D_
      }_x000D_
     _x000D_
      thead.appendChild(thr);_x000D_
      tbl.appendChild(thead);_x000D_
_x000D_
      let tbdy = document.createElement('tbody');_x000D_
      let tr = document.createElement('tr');_x000D_
      objectArray.forEach((object) => {_x000D_
        let n = 0;_x000D_
        let tr = document.createElement('tr');_x000D_
        for (p in objectArray[0]){_x000D_
          var td = document.createElement('td');_x000D_
          td.setAttribute("style","border: 1px solid green");_x000D_
          td.appendChild(document.createTextNode(object[p]));_x000D_
          tr.appendChild(td);_x000D_
          n++;_x000D_
        };_x000D_
        tbdy.appendChild(tr);    _x000D_
      });_x000D_
      tbl.appendChild(tbdy);_x000D_
      body.appendChild(tbl)_x000D_
      return tbl;_x000D_
    }_x000D_
_x000D_
    createTable([_x000D_
                  {name: 'Banana', price: '3.04'}, // k[0]_x000D_
                  {name: 'Orange', price: '2.56'},  // k[1]_x000D_
                  {name: 'Apple', price: '1.45'}_x000D_
               ])_x000D_
    </script>
_x000D_
_x000D_
_x000D_

How to handle a lost KeyStore password in Android?

I feel I need to make it an answer because this could not be just in comments. Like @ElDoRado1239 says in his answer (dont forget to upvote his answer ;)

  • Looks for ..Project\.gradle\2.4\taskArtifacts\taskArtifacts.bin in my case was in ..Project\.gradle\2.2.1\taskArtifacts\taskArtifacts.bin because I use gradle 2.2.1
  • Then look for storePassword like @Moxet Khan says in comments...in my case was at line signingConfig.storePassword¬í t my.forgoten.password—signingConfig.keyAlias

Hope help somebody else!!!

What are Covering Indexes and Covered Queries in SQL Server?

a covering index is the one which gives every required column and in which SQL server don't have hop back to the clustered index to find any column. This is achieved using non-clustered index and using INCLUDE option to cover columns. Non-key columns can be included only in non-clustered indexes. Columns can’t be defined in both the key column and the INCLUDE list. Column names can’t be repeated in the INCLUDE list. Non-key columns can be dropped from a table only after the non-key index is dropped first. Please see details here

Clearing a text field on button click

If you are trying to "Submit and Reset" the the "form" with one Button click, Try this!

Here I have used jQuery function, it can be done by simple JavaScript also...

        <form id="form_data">
           <input type="anything"  name="anything" />
           <input type="anything"  name="anything" />

             <!-- Save and Reset button -->
           <button type="button" id="btn_submit">Save</button>
           <button type="reset" id="btn_reset" style="display: none;"></button>
        </form>

<script type="text/javascript">
$(function(){
    $('#btn_submit').click(function(){
        // Do what ever you want
       $('#btn_reset').click();  // Clicking reset button
    });
});
</script>

Exporting data In SQL Server as INSERT INTO

After search a lot, it was my best shot:

If you have a lot of data and needs a compact and elegant script, try it: SSMS Tools Pack

It generates a union all select statements to insert items into target tables and handle transactions pretty well.

Screenshot

jQuery Combobox/select autocomplete?

I know this has been said earlier, but jQuery Autocomplete will do exactly what you need. You should check out the docs as the autocomplete is very customizable. If you are familiar with javascript then you should be able to work this out. If not I can give you a few pointers, as I have done this once before, but beware I am not well versed in javascript myself either, so bear with me on this.

I think the first thing you should do is just get a simple autocomplete text field working on your page, and then you can customize it from there.

The autocomplete widget accepts JSON data as it's 'source:' option. So you should set-up your app to produce the 20 top level categories, and subcategories in JSON format.

The next thing to know is that when the user types into your textfield, the autocomplete widget will send the typed values in a parameter called "term".

So let's say you first set-up your site to deliver the JSON data from a URL like this:

/categories.json

Then your autocomplete source: option would be 'source: /categories.json'.

When a user types into the textfield, such as 'first-cata...' the autocomplete widget will start sending the value in the 'term' parameter like this:

/categories.json?term=first-cata

This will return JSON data back to the widget filtered by anything that matches 'first-cata', and this is displayed as an autocomplete suggestion.

I am not sure what you are programming in, but you can specify how the 'term' parameter finds a match. So you can customize this, so that the term finds a match in the middle of a word if you want. Example, if the user types 'or' you code could make a match on 'sports'.

Lastly, you made a comment that you want to be able to select a category name but have the autocomplete widget submit the category ID not the name.

This can easily be done with a hidden field. This is what is shown in the jQuery autocomplete docs.

When a user selects a category, your JavaScript should update a hidden field with the ID.

I know this answer is not very detailed, but that is mainly because I am not sure what you are programming in, but the above should point you in the right direction. The thing to know is that you can do practically any customizing you want with this widget, if you are willing to spend the time to learn it.

These are the broad strokes, but you can look here for some notes I made when I implemented something similar to what you want in a Rails app.

Hope this helped.

Iterating over and deleting from Hashtable in Java

You can use Enumeration:

Hashtable<Integer, String> table = ...

Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
    Integer key = enumKey.nextElement();
    String val = table.get(key);
    if(key==0 && val.equals("0"))
        table.remove(key);
}

Remove multiple whitespaces

this will replace multiple tabs with a single tab

preg_replace("/\s{2,}/", "\t", $string);

Login failed for user 'DOMAIN\MACHINENAME$'

  1. Change the App Pool Identity to Local System
  2. On SQL Mgmt > Security > Logins
    1. Find NT AUTHORITY\SYSTEM double click
    2. User Mappings > Check your database and give it a role below.
    3. Remember also to create the user data base o security logins with a correct password.

Is quitting an application frowned upon?

For the first (starting ) activity of the application,

@Override
public void onBackPressed(){

    // Exit
    moveTaskToBack(true);
}

worked for me. I want to close the app here. And to come back from other activites; I used intents, e.g.

@Override
public void onBackPressed(){

    // Going back....
    Intent intent = new Intent(ActivityB.this, ActivityA.class);
    startActivity(intent);
    finish();
}

Note: This code is useful for the scenario where the developer wants to come back from ActivityZ to ActivityA and then close the app.

The request failed or the service did not respond in a timely fashion?

This really works - i had verified lot of sites and finally got the answer.

This may occurs when the master.mdf or the mastlog.ldf gets corrupt . In order to solve the issue goto the following path.

C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL , there you will find a folder ” Template Data ” , copy the master.mdf and mastlog.ldf and replace it in

C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA folder .

That's it. Now start the MS SQL service and you are done.

Setting dynamic scope variables in AngularJs - scope.<some_string>

If you were trying to do what I imagine you were trying to do, then you only have to treat scope like a regular JS object.

This is what I use for an API success response for JSON data array...

function(data){

    $scope.subjects = [];

    $.each(data, function(i,subject){
        //Store array of data types
        $scope.subjects.push(subject.name);

        //Split data in to arrays
        $scope[subject.name] = subject.data;
    });
}

Now {{subjects}} will return an array of data subject names, and in my example there would be a scope attribute for {{jobs}}, {{customers}}, {{staff}}, etc. from $scope.jobs, $scope.customers, $scope.staff

Show ImageView programmatically

//LinearLayOut Setup
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));

//ImageView Setup
ImageView imageView = new ImageView(this);

//setting image resource
imageView.setImageResource(R.drawable.play);

//setting image position
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
LayoutParams.WRAP_CONTENT));

//adding view to layout
linearLayout.addView(imageView);
//make visible to program
setContentView(linearLayout);

Why is visible="false" not working for a plain html table?

Who "they"? I don't think there's a visible attribute in html.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:

IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END 

Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.


If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.

IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE clockDate = '08/10/2012' AND userName = 'test'
END 

As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.

How can I concatenate a string within a loop in JSTL/JSP?

Is JSTL's join(), what you searched for?

<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />

Python in Xcode 4+?

You should try PyDev plug in for Eclipse. I tried alot of editors/IDE's to use with python, but the only one i liked the most is the PyDev plugin for Eclipse. It has code completion, debugger and many other nice features. Plus both are free.

How to pip install a package with min and max version range?

An elegant method would be to use the ~= compatible release operator according to PEP 440. In your case this would amount to:

package~=0.5.0

As an example, if the following versions exist, it would choose 0.5.9:

  • 0.5.0
  • 0.5.9
  • 0.6.0

For clarification, each pair is equivalent:

~= 0.5.0
>= 0.5.0, == 0.5.*

~= 0.5
>= 0.5, == 0.*

I'm getting favicon.ico error

Try this add "icon" with your stylesheet Maybe it solve your error "favicon.ico:1 not found "

OR First Try to understand about favicon.enter image description here SET your favicon icon file in your folder. You can generate your favicon using "https://favicon.io/favicon-generator/".

What's the difference between git reset --mixed, --soft, and --hard?

There are a number of answers here with a misconception about git reset --soft. While there is a specific condition in which git reset --soft will only change HEAD (starting from a detached head state), typically (and for the intended use), it moves the branch reference you currently have checked out. Of course it can't do this if you don't have a branch checked out (hence the specific condition where git reset --soft will only change HEAD).

I've found this to be the best way to think about git reset. You're not just moving HEAD (everything does that), you're also moving the branch ref, e.g., master. This is similar to what happens when you run git commit (the current branch moves along with HEAD), except instead of creating (and moving to) a new commit, you move to a prior commit.

This is the point of reset, changing a branch to something other than a new commit, not changing HEAD. You can see this in the documentation example:

Undo a commit, making it a topic branch

          $ git branch topic/wip     (1)
          $ git reset --hard HEAD~3  (2)
          $ git checkout topic/wip   (3)
  1. You have made some commits, but realize they were premature to be in the "master" branch. You want to continue polishing them in a topic branch, so create "topic/wip" branch off of the current HEAD.
  2. Rewind the master branch to get rid of those three commits.
  3. Switch to "topic/wip" branch and keep working.

What's the point of this series of commands? You want to move a branch, here master, so while you have master checked out, you run git reset.

The top voted answer here is generally good, but I thought I'd add this to correct the several answers with misconceptions.

Change your branch

git reset --soft <ref>: resets the branch pointer for the currently checked out branch to the commit at the specified reference, <ref>. Files in your working directory and index are not changed. Committing from this stage will take you right back to where you were before the git reset command.

Change your index too

git reset --mixed <ref>

or equivalently

git reset <ref>:

Does what --soft does AND also resets the index to the match the commit at the specified reference. While git reset --soft HEAD does nothing (because it says move the checked out branch to the checked out branch), git reset --mixed HEAD, or equivalently git reset HEAD, is a common and useful command because it resets the index to the state of your last commit.

Change your working directory too

git reset --hard <ref>: does what --mixed does AND also overwrites your working directory. This command is similar to git checkout <ref>, except that (and this is the crucial point about reset) all forms of git reset move the branch ref HEAD is pointing to.

A note about "such and such command moves the HEAD":

It is not useful to say a command moves the HEAD. Any command that changes where you are in your commit history moves the HEAD. That's what the HEAD is, a pointer to wherever you are. HEADis you, and so will move whenever you do.

Java: Find .txt files in specified folder

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;

public class FileFinder extends SimpleFileVisitor<Path> {
    private PathMatcher matcher;
    public ArrayList<Path> foundPaths = new ArrayList<>();

    public FileFinder(String pattern) {
        matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Path name = file.getFileName();

        if (matcher.matches(name)) {
            foundPaths.add(file);
        }

        return FileVisitResult.CONTINUE;
    }
}

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) throws IOException {
        Path fileDir = Paths.get("files");
        FileFinder finder = new FileFinder("*.txt");
        Files.walkFileTree(fileDir, finder);

        ArrayList<Path> foundFiles = finder.foundPaths;

        if (foundFiles.size() > 0) {
            for (Path path : foundFiles) {
                System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS));
            }
        } else {
            System.out.println("No files were founds!");
        }
    }
}

What is the &#xA; character?

That would be an HTML Encoded Line Feed character (using the hexadecimal value).

The decimal value would be &#10;

Javascript window.open pass values using POST

Even though this question was long time ago, thanks all for the inputs that helping me out a similar problem. I also made a bit modification based on the others' answers here and making multiple inputs/valuables into a Single Object (json); and hope this helps someone.

js:

//example: params={id:'123',name:'foo'};

mapInput.name = "data";
mapInput.value = JSON.stringify(params); 

php:

$data=json_decode($_POST['data']); 

echo $data->id;
echo $data->name;

Thread-safe List<T> property

I would think making a sample ThreadSafeList class would be easy:

public class ThreadSafeList<T> : IList<T>
{
    protected List<T> _internalList = new List<T>();

    // Other Elements of IList implementation

    public IEnumerator<T> GetEnumerator()
    {
        return Clone().GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return Clone().GetEnumerator();
    }

    protected static object _lock = new object();

    public List<T> Clone()
    {
        List<T> newList = new List<T>();

        lock (_lock)
        {
            _internalList.ForEach(x => newList.Add(x));
        }

        return newList;
    }
}

You simply clone the list before requesting an enumerator, and thus any enumeration is working off a copy that can't be modified while running.

Change value of input placeholder via model?

The accepted answer still threw a Javascript error in IE for me (for Angular 1.2 at least). It is a bug but the workaround is to use ngAttr detailed on https://docs.angularjs.org/guide/interpolation

<input type="text" ng-model="inputText" ng-attr-placeholder="{{somePlaceholder}}" />

Issue: https://github.com/angular/angular.js/issues/5025

Convert an NSURL to an NSString

You can use any one way

NSString *string=[NSString stringWithFormat:@"%@",url1];

or

NSString *str=[url1 absoluteString];

NSLog(@"string :: %@",string);

string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif

NSLog(@"str :: %@", str);

str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif

On localhost, how do I pick a free port number?

Do not bind to a specific port. Instead, bind to port 0:

sock.bind(('', 0))

The OS will then pick an available port for you. You can get the port that was chosen using sock.getsockname()[1], and pass it on to the slaves so that they can connect back.

Masking password input from the console : Java

A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)

import java.io.Console;
public class Main {

    public void passwordExample() {        
        Console console = System.console();
        if (console == null) {
            System.out.println("Couldn't get Console instance");
            System.exit(0);
        }

        console.printf("Testing password%n");
        char[] passwordArray = console.readPassword("Enter your secret password: ");
        console.printf("Password entered was: %s%n", new String(passwordArray));

    }

    public static void main(String[] args) {
        new Main().passwordExample();
    }
}

Executing <script> elements inserted with .innerHTML

Thanks to Larry's script, which worked perfectly well in IE10, this is what I've used:

$('#' + id)[0].innerHTML = result;
$('#' + id + " script").each(function() { this.text = this.text || $(this).text();} );

How to read XML using XPath in Java

Getting started example:

xml file:

<inventory>
    <book year="2000">
        <title>Snow Crash</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553380958</isbn>
        <price>14.95</price>
    </book>

    <book year="2005">
        <title>Burning Tower</title>
        <author>Larry Niven</author>
        <author>Jerry Pournelle</author>
        <publisher>Pocket</publisher>
        <isbn>0743416910</isbn>
        <price>5.99</price>
    </book>

    <book year="1995">
        <title>Zodiac</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553573862</isbn>
        <price>7.50</price>
    </book>

    <!-- more books... -->

</inventory>

Java code:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


try {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("c:\\tmp\\my.xml"));

    // normalize text representation
    doc.getDocumentElement().normalize();
    System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());

    NodeList listOfBooks = doc.getElementsByTagName("book");
    int totalBooks = listOfBooks.getLength();
    System.out.println("Total no of books : " + totalBooks);

    for(int i=0; i<listOfBooks.getLength() ; i++) {

        Node firstBookNode = listOfBooks.item(i);
        if(firstBookNode.getNodeType() == Node.ELEMENT_NODE) {

            Element firstElement = (Element)firstBookNode;                              
            System.out.println("Year :"+firstElement.getAttribute("year"));

            //-------
            NodeList firstNameList = firstElement.getElementsByTagName("title");
            Element firstNameElement = (Element)firstNameList.item(0);

            NodeList textFNList = firstNameElement.getChildNodes();
            System.out.println("title : " + ((Node)textFNList.item(0)).getNodeValue().trim());
        }
    }//end of for loop with s var
} catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
} catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
} catch (Throwable t) {
    t.printStackTrace ();
}                

Body set to overflow-y:hidden but page is still scrollable in Chrome

Setting a height on your body and html of 100% should fix you up. Without a defined height your content is not overflowing, so you will not get the desired behavior.

html, body {
  overflow-y:hidden;
  height:100%;
}

Get distance between two points in canvas

To find the distance between 2 points, you need to find the length of the hypotenuse in a right angle triangle with a width and height equal to the vertical and horizontal distance:

Math.hypot(endX - startX, endY - startY)

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Found another (manual) answer which worked well for me

  1. Select the column.
  2. Choose Data tab
  3. Text to Columns - opens new box
  4. (choose Delimited), Next
  5. (uncheck all boxes, use "none" for text qualifier), Next
  6. use the ymd option from the Date dropdown.
  7. Click Finish

add new row in gridview after binding C#, ASP.net

protected void TableGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowIndex == -1 && e.Row.RowType == DataControlRowType.Header)
   {
      GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.DataRow,DataControlRowState.Insert);
      for (int i = 0; i < e.Row.Cells.Count; i++)
      {
         TableCell tCell = new TableCell();
         tCell.Text = "&nbsp;";
         gvRow.Cells.Add(tCell);
         Table tbl = e.Row.Parent as Table;
         tbl.Rows.Add(gvRow);
      }
   }
}

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

This code worked for me

public static void main(String[] args) {
    try {
        java.net.URL myUr = new java.net.URL("http://path");
        System.out.println("Instantiated new URL: " + connection_url);
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

Instantiated new URL: http://path

Expand/collapse section in UITableView in iOS

I have done the same thing using multiple sections .

class SCTierBenefitsViewController: UIViewController {
    @IBOutlet private weak var tblTierBenefits: UITableView!
    private var selectedIndexPath: IndexPath?
    private var isSelected:Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        tblTierBenefits.register(UINib(nibName:"TierBenefitsTableViewCell", bundle: nil), forCellReuseIdentifier:"TierBenefitsTableViewCell")
        tblTierBenefits.register(UINib(nibName:"TierBenefitsDetailsCell", bundle: nil), forCellReuseIdentifier:"TierBenefitsDetailsCell")

        tblTierBenefits.rowHeight = UITableViewAutomaticDimension;
        tblTierBenefits.estimatedRowHeight = 44.0;
        tblTierBenefits.tableFooterView = UIView()
    }

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

}

extension SCTierBenefitsViewController : UITableViewDataSource{

    func numberOfSections(in tableView: UITableView) -> Int {
        return 7
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (isSelected && section == selectedIndexPath?.section) ? 2 : 1 
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return  0.01
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.row {
        case 0:
            let cell:TierBenefitsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "TierBenefitsTableViewCell")! as! TierBenefitsTableViewCell
            cell.selectionStyle = .none
            cell.contentView.setNeedsLayout()
            cell.contentView.layoutIfNeeded()
            return cell

        case 1:
            let cell:TierBenefitsDetailsCell = tableView.dequeueReusableCell(withIdentifier: "TierBenefitsDetailsCell")! as! TierBenefitsDetailsCell
            cell.selectionStyle = .none
            return cell

        default:
            break
        }

        return UITableViewCell()
    }
}

extension SCTierBenefitsViewController : UITableViewDelegate{

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {

            if let _selectedIndexPath = selectedIndexPath ,selectedIndexPath?.section == indexPath.section {
                tblTierBenefits.beginUpdates()
                expandCollapse(indexPath: _selectedIndexPath, isExpand: false)
                selectedIndexPath = nil
            }
            else{
                tblTierBenefits.beginUpdates()
                if selectedIndexPath != nil {
                    tblTierBenefits.reloadSections([(selectedIndexPath?.section)!], with: .none)
                }
                expandCollapse(indexPath: indexPath, isExpand: true)
            }
        }
    }

    private func  expandCollapse(indexPath: IndexPath?,isExpand: Bool){
        isSelected = isExpand
        selectedIndexPath = indexPath
        tblTierBenefits.reloadSections([(indexPath?.section)!], with: .none)
        tblTierBenefits.endUpdates()
    }

}

Order by in Inner Join

Avoid SELECT * in your main query.

Avoid duplicate columns: the JOIN condition ensures One.One_Name and two.One_Name will be equal therefore you don't need to return both in the SELECT clause.

Avoid duplicate column names: rename One.ID and Two.ID using 'aliases'.

Add an ORDER BY clause using the column names ('alises' where applicable) from the SELECT clause.

Suggested re-write:

SELECT T1.ID AS One_ID, T1.One_Name, 
       T2.ID AS Two_ID, T2.Two_name
  FROM One AS T1
       INNER JOIN two AS T2
          ON T1.One_Name = T2.One_Name
 ORDER 
    BY One_ID;

Build the full path filename in Python

This works fine:

os.path.join(dir_name, base_filename + "." + filename_suffix)

Keep in mind that os.path.join() exists only because different operating systems use different path separator characters. It smooths over that difference so cross-platform code doesn't have to be cluttered with special cases for each OS. There is no need to do this for file name "extensions" (see footnote) because they are always connected to the rest of the name with a dot character, on every OS.

If using a function anyway makes you feel better (and you like needlessly complicating your code), you can do this:

os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))

If you prefer to keep your code clean, simply include the dot in the suffix:

suffix = '.pdf'
os.path.join(dir_name, base_filename + suffix)

That approach also happens to be compatible with the suffix conventions in pathlib, which was introduced in python 3.4 after this question was asked. New code that doesn't require backward compatibility can do this:

suffix = '.pdf'
pathlib.PurePath(dir_name, base_filename + suffix)

You might prefer the shorter Path instead of PurePath if you're only handling paths for the local OS.

Warning: Do not use pathlib's with_suffix() for this purpose. That method will corrupt base_filename if it ever contains a dot.


Footnote: Outside of Micorsoft operating systems, there is no such thing as a file name "extension". Its presence on Windows comes from MS-DOS and FAT, which borrowed it from CP/M, which has been dead for decades. That dot-plus-three-letters that many of us are accustomed to seeing is just part of the file name on every other modern OS, where it has no built-in meaning.

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.

Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.

VB.NET - Click Submit Button on Webbrowser page

I searched for any solution to not use the "SendKeys(CHR(13))" methode I ever used to submit stuff in Browser. In this case I was happy to see your

InvokeMember("click")

but dont know why you know that you have to write "click" in there. Anyway Thanks

How to get main div container to align to centre?

The basic principle of centering a page is to have a body CSS and main_container CSS. It should look something like this:

body {
     margin: 0;
     padding: 0;
     text-align: center;
}
#main_container {
     margin: 0 auto;
     text-align: left;
}

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

How to detect DIV's dimension changed?

using Bharat Patil answer simply return false inside the your bind callback to prevent maximum stack error see example below:

$('#test_div').bind('resize', function(){
   console.log('resized');
   return false;
});

String parsing in Java with delimiter tab "\t" using split

String[] columnDetail = new String[11];
columnDetail = column.split("\t", -1); // unlimited
OR
columnDetail = column.split("\t", 11); // if you are sure about limit.
 * The {@code limit} parameter controls the number of times the
 * pattern is applied and therefore affects the length of the resulting
 * array.  If the limit <i>n</i> is greater than zero then the pattern
 * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
 * length will be no greater than <i>n</i>, and the array's last entry
 * will contain all input beyond the last matched delimiter.  If <i>n</i>
 * is non-positive then the pattern will be applied as many times as
 * possible and the array can have any length.  If <i>n</i> is zero then
 * the pattern will be applied as many times as possible, the array can
 * have any length, and trailing empty strings will be discarded.

How to find current transaction level?

If you are talking about the current transaction nesting level, then you would use @@TRANCOUNT.

If you are talking about transaction isolation level, use DBCC USEROPTIONS and look for an option of isolation level. If it isn't set, it's read committed.

Passing HTML to template using Flask/Jinja2

From the jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

Example:

 <div class="info">
   {{data.email_content|safe}}
 </div>

Named placeholders in string formatting

I created also a util/helper class (using jdk 8) which can format a string an replaces occurrences of variables.

For this purpose I used the Matchers "appendReplacement" method which does all the substitution and loops only over the affected parts of a format string.

The helper class isn't currently well javadoc documented. I will changes this in the future ;) Anyway I commented the most important lines (I hope).

    public class FormatHelper {

    //Prefix and suffix for the enclosing variable name in the format string.
    //Replace the default values with any you need.
    public static final String DEFAULT_PREFIX = "${";
    public static final String DEFAULT_SUFFIX = "}";

    //Define dynamic function what happens if a key is not found.
    //Replace the defualt exception with any "unchecked" exception type you need or any other behavior.
    public static final BiFunction<String, String, String> DEFAULT_NO_KEY_FUNCTION =
            (fullMatch, variableName) -> {
                throw new RuntimeException(String.format("Key: %s for variable %s not found.",
                                                         variableName,
                                                         fullMatch));
            };
    private final Pattern variablePattern;
    private final Map<String, String> values;
    private final BiFunction<String, String, String> noKeyFunction;
    private final String prefix;
    private final String suffix;

    public FormatHelper(Map<String, String> values) {
        this(DEFAULT_NO_KEY_FUNCTION, values);
    }

    public FormatHelper(
            BiFunction<String, String, String> noKeyFunction, Map<String, String> values) {
        this(DEFAULT_PREFIX, DEFAULT_SUFFIX, noKeyFunction, values);
    }

    public FormatHelper(String prefix, String suffix, Map<String, String> values) {
        this(prefix, suffix, DEFAULT_NO_KEY_FUNCTION, values);
    }

    public FormatHelper(
            String prefix,
            String suffix,
            BiFunction<String, String, String> noKeyFunction,
            Map<String, String> values) {
        this.prefix = prefix;
        this.suffix = suffix;
        this.values = values;
        this.noKeyFunction = noKeyFunction;

        //Create the Pattern and quote the prefix and suffix so that the regex don't interpret special chars.
        //The variable name is a "\w+" in an extra capture group.
        variablePattern = Pattern.compile(Pattern.quote(prefix) + "(\\w+)" + Pattern.quote(suffix));
    }

    public static String format(CharSequence format, Map<String, String> values) {
        return new FormatHelper(values).format(format);
    }

    public static String format(
            CharSequence format,
            BiFunction<String, String, String> noKeyFunction,
            Map<String, String> values) {
        return new FormatHelper(noKeyFunction, values).format(format);
    }

    public static String format(
            String prefix, String suffix, CharSequence format, Map<String, String> values) {
        return new FormatHelper(prefix, suffix, values).format(format);
    }

    public static String format(
            String prefix,
            String suffix,
            BiFunction<String, String, String> noKeyFunction,
            CharSequence format,
            Map<String, String> values) {
        return new FormatHelper(prefix, suffix, noKeyFunction, values).format(format);
    }

    public String format(CharSequence format) {

        //Create matcher based on the init pattern for variable names.
        Matcher matcher = variablePattern.matcher(format);

        //This buffer will hold all parts of the formatted finished string.
        StringBuffer formatBuffer = new StringBuffer();

        //loop while the matcher finds another variable (prefix -> name <- suffix) match
        while (matcher.find()) {

            //The root capture group with the full match e.g ${variableName}
            String fullMatch = matcher.group();

            //The capture group for the variable name resulting from "(\w+)" e.g. variableName
            String variableName = matcher.group(1);

            //Get the value in our Map so the Key is the used variable name in our "format" string. The associated value will replace the variable.
            //If key is missing (absent) call the noKeyFunction with parameters "fullMatch" and "variableName" else return the value.
            String value = values.computeIfAbsent(variableName, key -> noKeyFunction.apply(fullMatch, key));

            //Escape the Map value because the "appendReplacement" method interprets the $ and \ as special chars.
            String escapedValue = Matcher.quoteReplacement(value);

            //The "appendReplacement" method replaces the current "full" match (e.g. ${variableName}) with the value from the "values" Map.
            //The replaced part of the "format" string is appended to the StringBuffer "formatBuffer".
            matcher.appendReplacement(formatBuffer, escapedValue);
        }

        //The "appendTail" method appends the last part of the "format" String which has no regex match.
        //That means if e.g. our "format" string has no matches the whole untouched "format" string is appended to the StringBuffer "formatBuffer".
        //Further more the method return the buffer.
        return matcher.appendTail(formatBuffer)
                      .toString();
    }

    public String getPrefix() {
        return prefix;
    }

    public String getSuffix() {
        return suffix;
    }

    public Map<String, String> getValues() {
        return values;
    }
}

You can create a class instance for a specific Map with values (or suffix prefix or noKeyFunction) like:

    Map<String, String> values = new HashMap<>();
    values.put("firstName", "Peter");
    values.put("lastName", "Parker");


    FormatHelper formatHelper = new FormatHelper(values);
    formatHelper.format("${firstName} ${lastName} is Spiderman!");
    // Result: "Peter Parker is Spiderman!"
    // Next format:
    formatHelper.format("Does ${firstName} ${lastName} works as photographer?");
    //Result: "Does Peter Parker works as photographer?"

Further more you can define what happens if a key in the values Map is missing (works in both ways e.g. wrong variable name in format string or missing key in Map). The default behavior is an thrown unchecked exception (unchecked because I use the default jdk8 Function which cant handle checked exceptions) like:

    Map<String, String> map = new HashMap<>();
    map.put("firstName", "Peter");
    map.put("lastName", "Parker");


    FormatHelper formatHelper = new FormatHelper(map);
    formatHelper.format("${missingName} ${lastName} is Spiderman!");
    //Result: RuntimeException: Key: missingName for variable ${missingName} not found.

You can define a custom behavior in the constructor call like:

Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");


FormatHelper formatHelper = new FormatHelper(fullMatch, variableName) -> variableName.equals("missingName") ? "John": "SOMETHING_WRONG", values);
formatHelper.format("${missingName} ${lastName} is Spiderman!");
// Result: "John Parker is Spiderman!"

or delegate it back to the default no key behavior:

...
    FormatHelper formatHelper = new FormatHelper((fullMatch, variableName) ->   variableName.equals("missingName") ? "John" :
            FormatHelper.DEFAULT_NO_KEY_FUNCTION.apply(fullMatch,
                                                       variableName), map);
...

For better handling there are also static method representations like:

Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");

FormatHelper.format("${firstName} ${lastName} is Spiderman!", map);
// Result: "Peter Parker is Spiderman!"

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

Different CURRENT_TIMESTAMP and SYSDATE in oracle

  • SYSDATE provides date and time of a server.
  • CURRENT_DATE provides date and time of client.(i.e., your system)
  • CURRENT_TIMESTAMP provides data and timestamp of a clinet.

When to use <span> instead <p>?

Span is completely non-semantic. It has no meaning, and serves merely as an element for cosmetic effects.

Paragraphs have semantic meaning - they tell a machine (like a browser or a screen reader) that the content they encapsulate is a block of text, and has the same meaning as a paragraph of text in a book.

How can I get current location from user in iOS

In iOS 6, the

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

is deprecated.

Use following code instead

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
    CLLocation *location = [locations lastObject];
    NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}

For iOS 6~8, the above method is still necessary, but you have to handle authorization.

_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
    [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
    //[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
   ) {
     // Will open an confirm dialog to get user's approval 
    [_locationManager requestWhenInUseAuthorization]; 
    //[_locationManager requestAlwaysAuthorization];
} else {
    [_locationManager startUpdatingLocation]; //Will update location immediately 
}

This is the delegate method which handle user's authorization

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
    case kCLAuthorizationStatusNotDetermined: {
        NSLog(@"User still thinking..");
    } break;
    case kCLAuthorizationStatusDenied: {
        NSLog(@"User hates you");
    } break;
    case kCLAuthorizationStatusAuthorizedWhenInUse:
    case kCLAuthorizationStatusAuthorizedAlways: {
        [_locationManager startUpdatingLocation]; //Will update location immediately
    } break;
    default:
        break;
    }
}

Delete all the records

When the table is very large, it's better to delete table itself with drop table TableName and recreate it, if one has create table query; rather than deleting records one by one, using delete from statement because that can be time consuming.

Possible to make labels appear when hovering over a point in matplotlib?

A slight edit on an example provided in http://matplotlib.org/users/shell.html:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')

line, = ax.plot(np.random.rand(100), '-', picker=5)  # 5 points tolerance


def onpick(event):
    thisline = event.artist
    xdata = thisline.get_xdata()
    ydata = thisline.get_ydata()
    ind = event.ind
    print('onpick points:', *zip(xdata[ind], ydata[ind]))


fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

This plots a straight line plot, as Sohaib was asking

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

#temp is materalized and CTE is not.

CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.

The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.

The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).

How can I enable Assembly binding logging?

  1. Create a new Application Pool

  2. Go to the Advanced Settings of this application pool

  3. Set the Enable 32-Bit Application to True

  4. Point your web application to use this new Pool

Screenshot (IIS-ApplicationPool)

How to load a jar file at runtime

This works for me:

File file  = new File("c:\\myjar.jar");

URL url = file.toURL();  
URL[] urls = new URL[]{url};

ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.mypackage.myclass");

How do I move an existing Git submodule within a Git repository?

The trick seems to be understanding that the .git directory for submodules are now kept in the master repository, under .git/modules, and each submodule has a .git file that points to it. This is the procedure you need now:

  • Move the submodule to its new home.
  • Edit the .git file in the submodule's working directory, and modify the path it contains so that it points to the right directory in the master repository's .git/modules directory.
  • Enter the master repository's .git/modules directory, and find the directory corresponding to your submodule.
  • Edit the config file, updating the worktree path so that it points to the new location of the submodule's working directory.
  • Edit the .gitmodules file in the root of the master repository, updating the path to the working directory of the submodule.
  • git add -u
  • git add <parent-of-new-submodule-directory> (It's important that you add the parent, and not the submodule directory itself.)

A few notes:

  • The [submodule "submodule-name"] lines in .gitmodules and .git/config must match each other, but don't correspond to anything else.
  • The submodule working directory and .git directory must correctly point to each other.
  • The .gitmodules and .git/config files should be synchronised.

How to parse float with two decimal places in javascript?

You can use toFixed() to do that

var twoPlacedFloat = parseFloat(yourString).toFixed(2)

How to create a custom exception type in Java?

You need to create a class that extends from Exception. It should look like this:

public class MyOwnException extends Exception {
    public MyOwnException () {

    }

    public MyOwnException (String message) {
        super (message);
    }

    public MyOwnException (Throwable cause) {
        super (cause);
    }

    public MyOwnException (String message, Throwable cause) {
        super (message, cause);
    }
}

Your question does not specify if this new exception should be checked or unchecked.

As you can see here, the two types are different:

  • Checked exceptions are meant to flag a problematic situation that should be handled by the developer who calls your method. It should be possible to recover from such an exception. A good example of this is a FileNotFoundException. Those exceptions are subclasses of Exception.

  • Unchecked exceptions are meant to represent a bug in your code, an unexpected situation that you might not be able to recover from. A NullPointerException is a classical example. Those exceptions are subclasses of RuntimeException

Checked exception must be handled by the calling method, either by catching it and acting accordingly, or by throwing it to the calling method. Unchecked exceptions are not meant to be caught, even though it is possible to do so.

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

As per UI Doc :

  1. First get index of tab which you want to activate.

    var index = $('#tabs a[href="'+id+'"]').parent().index();
    
  2. Activate it

    tabs.tabs( "option", "active", index );
    

Display last git commit comment

For something a little more readable, run this command once:

git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"

so that when you then run:

git lg

you get a nice readout. To show only the last line:

git lg -1

Solution found here

Use of #pragma in C

To sum it up, #pragma tells the compiler to do stuff. Here are a couple of ways I use it:

  • #pragma can be used to ignore compiler warnings. For example, to make GCC shut up about implicit function declarations, you can write:

    #pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
    

    An older version of libportable does this portably.

  • #pragma once, when written at the top of a header file, will cause said header file to be included once. libportable checks for pragma once support.

How do I restart nginx only after the configuration test was successful on Ubuntu?

I use the following command to reload Nginx (version 1.5.9) only if a configuration test was successful:

/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload

If you need to do this often, you may want to use an alias. I use the following:

alias n='/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload'

The trick here is done by the "&&" which only executes the second command if the first was successful. You can see here a more detailed explanation of the use of the "&&" operator.

You can use "restart" instead of "reload" if you really want to restart the server.

Dynamically create and submit form

Try with this code -
It is a totally dynamic solution:

    var form = $(document.createElement('form'));
    $(form).attr("action", "reserves.php");
    $(form).attr("method", "POST");

    var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val("bla");
    $(form).append($(input));
    $(form).submit();

How to gracefully handle the SIGKILL signal in Java

There is one way to react to a kill -9: that is to have a separate process that monitors the process being killed and cleans up after it if necessary. This would probably involve IPC and would be quite a bit of work, and you can still override it by killing both processes at the same time. I assume it will not be worth the trouble in most cases.

Whoever kills a process with -9 should theoretically know what he/she is doing and that it may leave things in an inconsistent state.

WAITING at sun.misc.Unsafe.park(Native Method)

unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.

So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.

Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.